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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/trtc.esm.js CHANGED
@@ -9,7 +9,7 @@ var rm=Object.create;var rs=Object.defineProperty,sm=Object.defineProperties,ol=
9
9
 
10
10
  `,u+=o)),s&&(u+=`
11
11
  Refer to: ${Al("en",a)}
12
- `),u}var jm=Object.prototype.hasOwnProperty;var Dt=r=>typeof r=="function",si=r=>typeof r=="undefined";var Cl=r=>typeof r=="boolean";var qm=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 Rl(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(qm(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(jm.call(r,i))return!1;return!0}}return!1}var Xm=0,Qm=1,yl=2;function zm({retryFunction:r,settings:i,onError:e,onRetrying:t,onRetryFailed:s,onRetrySuccess:o,context:n}){return function(...a){let{retries:c=5,timeout:d=1e3}=i,u=0,m=-1,p=Xm,_=(C,y)=>f(this,null,function*(){let D=n||this;try{let B=yield r.apply(D,a);u>0&&o&&o.call(this,u),u=0,C(B)}catch(B){let ve=()=>{clearTimeout(m),u=0,p=yl,y(B)},vo=()=>{p!==yl&&u<(Dt(c)?c():c)?(u++,p=Qm,Dt(t)&&t.call(this,u,ve),m=window.setTimeout(()=>{m=-1,_(C,y)},Dt(d)?d(u):d)):(ve(),Dt(s)&&s.call(this,B))};Dt(e)?e.call(this,{error:B,retry:vo,reject:y,retryFuncArgs:a,retriedCount:u}):vo()}});return new Promise(_)}}var Ot=zm;var bl=Ie(Oe(),1),Ym=new bl.default,T=Ym;var oi=($=>($.ROOM_DESTROY="1",$.JOIN_START="21",$.JOIN_SCHEDULE_SUCCESS="22",$.JOIN_SIGNAL_CONNECTION_START="23",$.JOIN_SIGNAL_CONNECTION_END="24",$.JOIN_SEND_CMD="25",$.JOIN_RECEIVED_CMD_RES="26",$.JOIN_SUCCESS="27",$.JOIN_FAILED="28",$.LEAVE_START="51",$.LEAVE_SEND_CMD="52",$.LEAVE_SUCCESS="53",$.PUBLISH_START="61",$.SEND_FIRST_VIDEO_FRAME="62",$.PUBLISH_FAILED="63",$.SUBSCRIBE_START="81",$.SUBSCRIBE_SUCCESS="82",$.SUBSCRIBE_FAILED="84",$.UNSUBSCRIBE_SUCCESS="83",$.LOCAL_TRACK_CAPTURE_START="101",$.LOCAL_TRACK_CAPTURE_SUCCESS="102",$.LOCAL_TRACK_CAPTURE_FAILED="103",$.LOCAL_TRACK_PUBLISHED="104",$.LOCAL_TRACK_UNPUBLISHED="105",$.LOCAL_TRACK_REPLACED="106",$.SWITCH_DEVICE_SUCCESS="107",$.TRACK_MUTED="108",$.TRACK_UNMUTED="109",$.REMOTE_TRACK_SUBSCRIBED="110",$.REMOTE_TRACK_UNSUBSCRIBED="111",$.LOCAL_TRACK_RECAPTURE="112",$.PLAY_TRACK_START="151",$.PLAYER_STATE_CHANGED="152",$.VIDEO_LOADED_DATA="153",$.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",$.SIGNAL_CONNECTION_STATE_CHANGED="201",$.PEER_CONNECTION_STATE_CHANGED="202",$.SINGLE_CONNECTION_STAT="203",$.SPC_RECONNECTED="204",$.HEARTBEAT_REPORT="251",$.RECEIVED_PUBLISHED_USER_LIST="252",$.REMOTE_PUBLISH_STATE_CHANGED="253",$.AUDIO_LEVEL_INTERVAL="260",$.NETWORK_QUALITY="261",$.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",$.QUALITY_LIMITATION_CHANGED="263",$.LOG="264",$))(oi||{});var Xa=class{constructor(){this._roomIdMap=new Map;typeof registerProcessor=="undefined"&&(this._configs={sdkAppId:"",userId:"",version:ye,env:zt.QCLOUD,browserVersion:Nt.name+Nt.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){ti||!A.isAbleToUpload||this._configs.env===zt.QCLOUD&&this.uploadEventToKibana(P(N({},i),{result:"success"}))}logFailedEvent(i){if(ti||!A.isAbleToUpload)return;let{eventType:e,code:t,error:s,userId:o}=i,n={roomId:this._roomIdMap.get(o||this._configs.userId),userId:o,eventType:e,result:"failed",code:t||(s==null?void 0:s.extraCode)||(s==null?void 0:s.code)||S.UNKNOWN};this._configs.env===zt.QCLOUD&&this.uploadEventToKibana(P(N({},n),{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:Mo(),sdkAppId:this._configs.sdkAppId,userId:e||this._configs.userId,version:ye,log:i};t&&(s.errorInfo=t.message,t.stack&&(s.errorInfo+=`
12
+ `),u}var jm=Object.prototype.hasOwnProperty;var Dt=r=>typeof r=="function",si=r=>typeof r=="undefined";var Cl=r=>typeof r=="boolean";var qm=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 Rl(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(qm(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(jm.call(r,i))return!1;return!0}}return!1}var Xm=0,Qm=1,yl=2;function zm({retryFunction:r,settings:i,onError:e,onRetrying:t,onRetryFailed:s,onRetrySuccess:o,context:n}){return function(...a){let{retries:c=5,timeout:d=1e3}=i,u=0,m=-1,p=Xm,_=(C,y)=>f(this,null,function*(){let D=n||this;try{let B=yield r.apply(D,a);u>0&&o&&o.call(this,u),u=0,C(B)}catch(B){let ve=()=>{clearTimeout(m),u=0,p=yl,y(B)},vo=()=>{p!==yl&&u<(Dt(c)?c():c)?(u++,p=Qm,Dt(t)&&t.call(this,u,ve),m=window.setTimeout(()=>{m=-1,_(C,y)},Dt(d)?d(u):d)):(ve(),Dt(s)&&s.call(this,B))};Dt(e)?e.call(this,{error:B,retry:vo,reject:y,retryFuncArgs:a,retriedCount:u}):vo()}});return new Promise(_)}}var Ot=zm;var bl=Ie(Oe(),1),Ym=new bl.default,T=Ym;var oi=($=>($.ROOM_DESTROY="1",$.JOIN_START="21",$.JOIN_SCHEDULE_SUCCESS="22",$.JOIN_SIGNAL_CONNECTION_START="23",$.JOIN_SIGNAL_CONNECTION_END="24",$.JOIN_SEND_CMD="25",$.JOIN_RECEIVED_CMD_RES="26",$.JOIN_SUCCESS="27",$.JOIN_FAILED="28",$.LEAVE_START="51",$.LEAVE_SEND_CMD="52",$.LEAVE_SUCCESS="53",$.PUBLISH_START="61",$.SEND_FIRST_VIDEO_FRAME="62",$.PUBLISH_FAILED="63",$.SUBSCRIBE_START="81",$.SUBSCRIBE_SUCCESS="82",$.SUBSCRIBE_FAILED="84",$.UNSUBSCRIBE_SUCCESS="83",$.LOCAL_TRACK_CAPTURE_START="101",$.LOCAL_TRACK_CAPTURE_SUCCESS="102",$.LOCAL_TRACK_CAPTURE_FAILED="103",$.LOCAL_TRACK_PUBLISHED="104",$.LOCAL_TRACK_UNPUBLISHED="105",$.LOCAL_TRACK_REPLACED="106",$.SWITCH_DEVICE_SUCCESS="107",$.TRACK_MUTED="108",$.TRACK_UNMUTED="109",$.REMOTE_TRACK_SUBSCRIBED="110",$.REMOTE_TRACK_UNSUBSCRIBED="111",$.LOCAL_TRACK_RECAPTURE="112",$.PLAY_TRACK_START="151",$.PLAYER_STATE_CHANGED="152",$.VIDEO_LOADED_DATA="153",$.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",$.SIGNAL_CONNECTION_STATE_CHANGED="201",$.PEER_CONNECTION_STATE_CHANGED="202",$.SINGLE_CONNECTION_STAT="203",$.SPC_RECONNECTED="204",$.HEARTBEAT_REPORT="251",$.RECEIVED_PUBLISHED_USER_LIST="252",$.REMOTE_PUBLISH_STATE_CHANGED="253",$.AUDIO_LEVEL_INTERVAL="260",$.NETWORK_QUALITY="261",$.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",$.QUALITY_LIMITATION_CHANGED="263",$.LOG="264",$))(oi||{});var Xa=class{constructor(){l(this,"_roomIdMap",new Map);l(this,"_configs");typeof registerProcessor=="undefined"&&(this._configs={sdkAppId:"",userId:"",version:ye,env:zt.QCLOUD,browserVersion:Nt.name+Nt.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){ti||!A.isAbleToUpload||this._configs.env===zt.QCLOUD&&this.uploadEventToKibana(P(N({},i),{result:"success"}))}logFailedEvent(i){if(ti||!A.isAbleToUpload)return;let{eventType:e,code:t,error:s,userId:o}=i,n={roomId:this._roomIdMap.get(o||this._configs.userId),userId:o,eventType:e,result:"failed",code:t||(s==null?void 0:s.extraCode)||(s==null?void 0:s.code)||S.UNKNOWN};this._configs.env===zt.QCLOUD&&this.uploadEventToKibana(P(N({},n),{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:Mo(),sdkAppId:this._configs.sdkAppId,userId:e||this._configs.userId,version:ye,log:i};t&&(s.errorInfo=t.message,t.stack&&(s.errorInfo+=`
13
13
  ${t.stack}`)),this.sendRequest(yi(this._configs.sdkAppId,Ei.LOG),s)}sendRequest(i,e){if(!A.isAbleToUpload){setTimeout(()=>{this.sendRequest(i,e)},1e3);return}Kt({url:i,body:JSON.stringify(e)}).catch(()=>{})}},Y=new Xa;var Qa=null,za=!0;document&&document.head.insertAdjacentHTML("beforeend",Object.values(ct).map(r=>`<link rel="dns-prefetch" href="https://${r}">`).join(`\r
14
14
  `));function kt(r){le(r)&&r!==za&&(za=r,A.info(`setIsNeedToSchedule ${r}`))}T.on("28",()=>kt(!0));T.on("63",()=>kt(!0));T.on("84",()=>kt(!0));T.on("201",r=>{r.state==="RECONNECTING"&&kt(!0)});T.on("202",r=>{r.state==="RECONNECTING"&&kt(!0)});function Km(r,i,e){let t={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let s=performance.getEntriesByType("resource"),o=Nr(r,h.MAIN),n=Nr(r,h.BACKUP);for(let a of s)if(a.startTime>=e&&(a.name===o||a.name===n)&&a.transferSize>0){let c=a.name===o?h.MAIN:h.BACKUP,d=Math.round(a.duration),u=Math.round(a.domainLookupStart-a.startTime),m=a.redirectStart>0?Math.round(a.redirectEnd-a.redirectStart):0,p=a.fetchStart>0?Math.round(a.domainLookupStart-a.fetchStart):0,_=Math.round(a.domainLookupEnd-a.domainLookupStart),C=Math.round(a.requestStart-a.secureConnectionStart),y=Math.round(a.secureConnectionStart-a.connectStart),D=Math.round(a.responseStart-a.requestStart),B=Math.round(a.responseEnd-a.responseStart),ve=[_,C,y,D,B];Y.uploadEvent({log:`stat-schedule-net:${d}(${u}(${m}->${p})->${ve.join("->")}) ${c}`,userId:i}),t=P(N({},t),{totalCost:d,local:u,dns:_,tcp:y,tls:C,request:D,response:B});break}}catch(s){A.error("getScheduleDetailCost error",s)}return t}function vl(d){return f(this,arguments,function*({userId:r,sdkAppId:i,useStringRoomId:e,roomId:t,userSig:s,version:o,frameWorkType:n,role:a,latencyLevel:c}){if(!za&&Qa)return{isCached:!0,result:Qa};let u={delta:0,count:[1,1],msg:[],detail:[]};try{let m=new FormData;m.append("userId",String(r)),m.append("sdkAppId",String(i)),m.append("isStrGroupId",String(e)),m.append("groupId",String(t)),m.append("sdkVersion",o),m.append("userSig",String(s)),a&&m.append("role",String(a)),c&&m.append("latencyLevel",String(c)),n&&m.append("frameWorkType",String(n));let p=w(),_=yield ep(m,u,i);_.config&&(_.config.loggerDomain&&Bi(_.config.loggerDomain),le(_.config.scheduleCache)&&kt(!_.config.scheduleCache)),u.delta=w()-p;let C=Km(Number(i),r,p);return Qa=_,{isCached:!1,result:_,detailCost:C}}catch(m){let p=fe(m)?m[0]:m,_=ee(p.code)?p.code:0,C=`schedule failed${p.message?`: ${p.message}`:""}`,y=new R({code:S.SCHEDULE_FAILED,extraCode:_,message:x({key:L.JOIN_ROOM_FAILED,data:{error:C,code:_}})});throw A.error(C,_),y}})}var bi={main:"",backup:""};function Ya(r){fe(r)?(bi.main=r[0],bi.backup=r[1]):bi.main=r}function Nr(r,i=h.MAIN,e=!1){return`https://${bi[i]||Ol(r,i,e)}/api/v1/config`}function Dl(r,i=h.MAIN){return`https://${bi[i]||Ol(r,i)}/api/v1/trtcAutoConf`}function Ol(r,i=h.MAIN,e=!1){if(Os(r))return i===h.MAIN?ct.MAIN_OVERSEA:ct.BACKUP_OVERSEA;let t;return Os(r)?e?t=i===h.MAIN?ct.MAIN_OVERSEA_OLD:ct.BACKUP_OVERSEA_OLD:t=i===h.MAIN?ct.MAIN_OVERSEA:ct.BACKUP_OVERSEA:t=i===h.MAIN?ct.MAIN:ct.BACKUP,t}function Zm(r,i,e){return new Promise((t,s)=>{Kt({url:r,body:i,timeout:e.timeout}).then(o=>{o.data.code===0?t(o.data.data):s({code:o.data.code,message:o.data.msg})}).catch(s)})}var Nl=(r,i)=>Ot({retryFunction:Zm,settings:{retries:3,timeout:0},onError:i,onRetrying:r});function ep(r,i,e){return new Promise((t,s)=>{let o=null;Ms([Nl(n=>i.count[0]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:d})=>{i.msg[0]=n.message,o||(c>=2&&(d[0]=Nr(e,h.MAIN,!0)),a())})(Nr(e,h.MAIN),r,{get timeout(){return vr(2+i.count[0])*1e3}}),Nl(n=>i.count[1]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:d})=>{i.msg[1]=n.message,o||(c>=2&&(d[0]=Nr(e,h.BACKUP,!0)),a())})(Nr(e,h.BACKUP),r,{get timeout(){return vr(2+i.count[1])*1e3}})]).then(n=>{o=n,t(o)}).catch(s)})}var tp=function(){return new URLSearchParams(location.search).get("trtc_env")||""},Os=r=>Number(r)<14e8,yi=function(r,i){let e;ls?e=ls:e=Os(r)?Ra:Ca;let t=Math.floor(Math.random()*ss(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${t}&sdkappid=${r}&cmdtype=${i}`},ks="unknown";function kl(){if(ks!=="unknown")return ks;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&&(ks=Ll(t,s)),ks}function Ll(r,i){if(ko[r])return r;switch(r){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function Ka(r){ks=Ll(r)}function Or(){return ko[kl()]}function ip(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 rp(r,i=48e3){return Pl(r/4,i)}function Pl(r,i=48e3){return r*1e3/i}function sp(r,i=48e3){return xl(r,i)*4}function xl(r,i=48e3){return r*i/1e3}var wl=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},vt=()=>{let r=navigator.language;return r=r.substring(0,2),r==="zh"},Je=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 vr(r,i=1,e=1){return r<=1?e:vr(r-1,e,i+e)}function Lt(r){return r>8?30*1e3:vr(r)*1e3}function ge(r){return Reflect.apply(Object.prototype.toString,r,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var te=r=>typeof r=="function",g=r=>typeof r=="undefined",z=r=>typeof r=="string",ee=r=>typeof r=="number",le=r=>typeof r=="boolean",_t=r=>ge(r)==="object",fe=r=>ge(r)==="array",op=r=>ge(r)==="MediaStreamTrack".toLowerCase(),gt=r=>r.isRemote,Ls=r=>ge(r)==="promise",Ps=r=>te(r)&&r.prototype.constructor===r,nn=r=>Ps(r)?r.prototype.constructor.name:"",np=typeof AudioWorkletNode!="undefined";function Ms(r){return new Promise((i,e)=>{let t=[];r.forEach(s=>{s.then(i).catch(o=>{t.push(o),t.length===r.length&&e(t)})})})}function w(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var Ml=r=>+r<10?`0${r}`:r,ap=r=>{let i=r.match(/^\d+\.\d+\.\d+/)[0];if(!i)return r;let e=i.split("."),t=Ml(e[1])+Ml(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${t}`},cp=Object.prototype.hasOwnProperty,{toString:AE}=Object.prototype;function Za(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(Je(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(cp.call(r,i))return!1;return!0}}return!1}function Ni(r,i){return{userId:i,hasAudio:!!(r&Ti),hasVideo:!!(r&gi),hasAuxiliary:!!(r&$i),hasSmall:!!(r&us),audioMuted:!!(r&Vo),videoMuted:!!(r&Uo),audioAvailable:!!(r&Ti)&&!(r&Vo),videoAvailable:!!(r&gi)&&!(r&Uo)}}function dp(r){let i={urls:r.url.startsWith("turn:")||r.url.startsWith("turns:")?r.url:`turn:${r.url}`};return!g(r.username)&&!g(r.credential)&&(i.username=r.username,i.credential=r.credential,i.credentialType="password",g(r.credentialType)||(i.credentialType=r.credentialType)),i}function xs(r,i=!0){if(!z(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 ni=function(r,i,e,t){if(!(_t(r)&&_t(i)))return 0;let s=0,o=Object.keys(i),n;for(let a=0,c=o.length;a<c;a++)if(n=o[a],!(g(i[n])||e&&e.includes(n)))if(_t(r[n])&&_t(i[n]))s+=ni(r[n],i[n],e,t);else{if(t&&t.includes(i[n]))continue;r[n]!==i[n]&&(r[n]=Dr(i[n]),s+=1)}return s};function Dr(r){if(fe(r)){let i=[];return r.forEach((e,t)=>{i[t]=Dr(e)}),i}if(_t(r)){let i={};return Object.keys(r).forEach(e=>{i[e]=Dr(r[e])}),i}return r}var ws=r=>{let i=[];if(fe(r))i=[...r];else if(z(r)){let e=document.getElementById(r);e&&i.push(e)}else r&&i.push(r);return i},lp=r=>z(r)?document.getElementById(r):r,up=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"}),hp=()=>up.format(new Date);function Et(r,{keysToInclude:i,keysToExclude:e}){try{if(fe(r))return`[${r.map(n=>Et(n,{keysToInclude:i,keysToExclude:e})).join(",")}]`;if(!Je(r)||!fe(i)&&!fe(e))return JSON.stringify(r);let t={},s=new Set(i),o=new Set(e);return Object.keys(r).forEach(n=>{(o.size===0&&s.has(n)||s.size===0&&!o.has(n))&&(t[n]=Je(r[n])||fe(r[n])?JSON.parse(Et(r[n],{keysToExclude:e,keysToInclude:i})):r[n])}),JSON.stringify(t)}catch(t){return"{}"}}function ec(r,i=!1){let e=[];return Object.keys(r).forEach(t=>{i===r[t]&&e.push(t)}),Et(r,{keysToInclude:e})}function an(r){return r.replace(/[\u4e00-\u9fa5]/g,"aa").length}var tc=()=>{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},Vs=r=>f(void 0,null,function*(){return new Promise((i,e)=>{let t;if(z(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(new R({code:S.INVALID_PARAMETER,message:`load image failed, url: ${r}`}))}})}),ic=r=>{let i=r.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]<<0},cn=r=>(Object.keys(r).forEach(i=>{ee(r[i])&&(i.startsWith("uint")||i.startsWith("int"))?r[i]=Math.floor(r[i]):(Je(r[i])||fe(r[i]))&&cn(r[i])}),r);function Mr(r){return new Promise(i=>setTimeout(i,r))}var rc=(r,i)=>{let e=null;return function(...t){return e||(e=r.apply(i||this,t),e.finally(()=>e=null),e)}};var kr=class{constructor(i){l(this,"userId");l(this,"remoteUserId");l(this,"id");l(this,"sdkAppId");l(this,"type");l(this,"isLocal");this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=Cl(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,si(this.userId)||Rl(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 E=oi;var mp="%cTRTC%c%s",pp="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",fp="display: inline",_p=!(Be||pe||Ga),sc=class{constructor(){l(this,"_isEnableUploadLog",!0);l(this,"_localJoinedUser",new Map);l(this,"_queue",[]);l(this,"_timeoutId",-1);l(this,"_logLevel",1);l(this,"_logLevelToUpload",2);!ur&&!ds&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){T.on(E.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var e;((e=i==null?void 0:i.config)==null?void 0:e.logLevelToUpload)&&nt[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),T.on(E.JOIN_SUCCESS,({room:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),T.once(E.JOIN_FAILED,()=>{this.startUpload()}),T.on(E.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:o})=>{i.map.has(s)?i.map.get(s).logs.push(t):i.map.set(s,{userId:s,sdkAppId:o,logs:[t]})});else if(z(t.userId)&&ee(t.sdkAppId)){let{userId:s,sdkAppId:o}=t;i.map.has(s)?i.map.get(s).logs.push(t):i.map.set(s,{userId:s,sdkAppId:o,logs:[t]})}}return i.map.size>0&&(i.splicedQueue=this._queue.splice(0,e)),i}upload(){return f(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 o=0;o<s.length;o++){let{userId:n,sdkAppId:a,logs:c}=s[o];yield this.uploadLogWithRetry(JSON.stringify({timestamp:Mo(),sdkAppId:String(a),userId:n,version:ye,log:c.map(d=>d.log).join(`
15
15
  `)}),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 Ot({retryFunction:()=>Kt({url:yi(e,Ei.LOG),body:i,timeout:5e3}),settings:{retries:3,timeout:1e3},onError:({retry:t})=>{t()}})()}getPrefix(i){let e=new Date;e.setTime(as());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}] <${nt[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){g(nt[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(z(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch(e){return""}}log(i,e,t=!0,s,o){var c;e.unshift(this.getPrefix(i));let n={log:e.reduce((d,u)=>`${d} ${this.logChunkToString(u)}`.trim(),""),level:i,userId:s,sdkAppId:o,forAllJoinedClients:t};if(T.emit(E.LOG,{log:n}),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push(n),i<this._logLevel)return;let a=((c=nt[i])==null?void 0:c.toLowerCase())||"info";_p?console[a](mp,pp,fp,...e):console[a](...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 kr(i)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;nt[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}},A=new sc;var Ep=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)})},Us=Ep;var oc=class{constructor(){l(this,"_prefix","TRTC");l(this,"_queue",new Map);this.checkStorage()}getRealKey(i){return`${this._prefix}_${i}`}checkStorage(){if(!ii())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 o=JSON.parse(s);if(o&&o.expiresIn<Date.now())return!0}return!1}).forEach(t=>localStorage.removeItem(t))}doFlush(){if(!!ii())try{for(let[i,e]of this._queue)localStorage.setItem(i,JSON.stringify(e))}catch(i){A.warn(i)}}getItem(i){if(!ii())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(!!ii())try{let t={expiresIn:Date.now()+Lo,value:e};this._queue.set(this.getRealKey(i),t)}catch(t){A.warn(t)}}deleteItem(i){if(!ii())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(!!ii())try{localStorage.clear()}catch(i){A.warn(i)}}},dn=new oc;var wt={};os(wt,{HTTPS_API:()=>Pp,IS_GET_CAPABILITIES_SUPPORTED:()=>_c,IS_GET_SETTINGS_SUPPORTED:()=>xt,IS_INSERTABLE_STREAM_SUPPORTED:()=>Tt,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>En,IS_SEI_SUPPORTED:()=>Gs,IS_SPC_SUPPORTED:()=>Pr,basis:()=>Up,checkSystemRequirementsInternal:()=>_n,decodeSupportStatus:()=>fn,encodeSupportStatus:()=>mc,getBrowserInfo:()=>Op,getDisplayResolution:()=>ql,isAddTransceiverSupported:()=>tt,isBrowserSupported:()=>pc,isGetReceiversSupported:()=>Xi,isGetSendersSupported:()=>Di,isGetTransceiversSupported:()=>Pt,isGetUserMediaSupported:()=>Xl,isMediaDevicesSupported:()=>pn,isMediaSessionSupported:()=>Yl,isMediaStreamTrackProcessorSupported:()=>Mp,isReplaceTrackSupported:()=>fc,isRequestVideoFrameCallbackSupported:()=>Qi,isSIMDSupported:()=>Vp,isScreenCaptureApiAvailable:()=>$s,isSelectedCandidatePair:()=>vi,isSetParametersSupported:()=>Hs,isSmallStreamAPISupported:()=>zl,isSmallStreamSupported:()=>Fs,isStopTransceiverSupported:()=>wp,isTRTCSupported:()=>kp,isUnifiedPlanDefault:()=>xp,isUsedInHttpProtocol:()=>di,isWebAudioSupported:()=>Ql,isWebCodecSupported:()=>gn,isWebCodecsSupported:()=>jl,isWebRTCSupported:()=>Ec,isWebTransportSupported:()=>Kl});var hc=Ie(Wl(),1);var bp=1,Np=0,ln=class{constructor(i=!0){this.countMap=new Map;this.distributionMap=new Map;this.log=A.createLogger({id:"kv"});i&&(T.on("102",({track:e,cost:t})=>{this.addSuccessEvent({key:e.kind===h.AUDIO?un.START_MICROPHONE:cc.START_CAMERA,cost:t})}),T.on("103",({track:e,error:t})=>{this.addFailedEvent({key:e.kind===h.AUDIO?un.START_MICROPHONE:cc.START_CAMERA,error:t})}))}getReportData(){let i={msg_sdk_basic_info:{uint32_sdk_version:ic(this.version||ye),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(([e,t])=>({uint32_key:e,uint32_count:t})),stats_distribution:[...this.distributionMap.entries()].map(([e,t])=>({uint32_key:e,distribution_items:[...t.entries()].map(([s,o])=>({uint32_item_key:s,uint32_item_value:o}))}))};return this.countMap.clear(),this.distributionMap.clear(),i}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(i){let e=+String(i).slice(-3);return e>=700&&e<799}isErrorCodeKey(i){let e=+String(i).slice(-3);return e>=600&&e<699}isCountKey(i){let e=+String(i).slice(-3);return e>=0&&e<599}isNumberKey(i){let e=+String(i).slice(-3);return e>=800&&e<899}addCount({key:i,useUV:e=!1}){if(!this.isCountKey(i)){this.log.debug(`${i} is not count key, last 3 number should be 0~599`);return}e&&this.countMap.has(i)||this.countMap.set(i,(this.countMap.get(i)||0)+1)}addEnum({key:i,value:e,useUV:t=!0}){var o;if(!this.isEnumKey(i))return this.log.debug(`${i} is not enum key, last 3 number should be 700~799`);if(t&&this.countMap.has(i))return;this.countMap.set(i,(this.countMap.get(i)||0)+1);let s=((o=this.distributionMap)==null?void 0:o.get(i))||new Map;s.set(e,(s.get(e)||0)+1),this.distributionMap.set(i,s)}addNumber({key:i,value:e,split:t=100,useUV:s=!1}){var a;if(!this.isNumberKey(i))return this.log.debug(`${i} is not number key, last 3 number should be 800~899`);if(s&&this.countMap.has(i))return;this.countMap.set(i,(this.countMap.get(i)||0)+1);let o=((a=this.distributionMap)==null?void 0:a.get(i))||new Map,n=0;if(ee(t))n=Math.floor(e/t);else for(let c=t.length-1;c>0;c--)if(e>t[c]){n=c;break}o.set(n,(o.get(n)||0)+1),this.distributionMap.set(i,o)}addSuccessEvent({key:i,cost:e,timeKey:t,split:s}){if(!!i&&(this.addEnum({key:i,value:bp,useUV:!1}),e)){let o=+String(i).slice(-3);o<800&&o>=700?this.addNumber({key:t||i+100,value:e,split:s}):t||this.log.debug(`time stat ignored, ${i}`)}}addFailedEvent({key:i,error:e}){if(!i)return;let t=S.UNKNOWN;e&&(ee(e)?t=e:(!g(e.extraCode)||!g(e.code))&&(t=e.extraCode||e.code)),this.addEnum({key:i,value:Np,useUV:!1}),this.addEnum({key:i,value:t,useUV:!1})}},hn=(G=>(G[G.enterRoom=500700]="enterRoom",G[G.exitRoom=500701]="exitRoom",G[G.switchRole=500702]="switchRole",G[G.destroy=500703]="destroy",G[G.startLocalAudio=500704]="startLocalAudio",G[G.updateLocalAudio=500705]="updateLocalAudio",G[G.stopLocalAudio=500706]="stopLocalAudio",G[G.startLocalVideo=500707]="startLocalVideo",G[G.updateLocalVideo=500708]="updateLocalVideo",G[G.stopLocalVideo=500709]="stopLocalVideo",G[G.startScreenShare=500710]="startScreenShare",G[G.updateScreenShare=500711]="updateScreenShare",G[G.stopScreenShare=500712]="stopScreenShare",G[G.startRemoteVideo=500713]="startRemoteVideo",G[G.updateRemoteVideo=500714]="updateRemoteVideo",G[G.stopRemoteVideo=500715]="stopRemoteVideo",G[G.muteRemoteAudio=500716]="muteRemoteAudio",G[G.setRemoteAudioVolume=500717]="setRemoteAudioVolume",G[G.use=500718]="use",G[G.sendSEIMessage=5e5]="sendSEIMessage",G[G.sendCustomMessage=500001]="sendCustomMessage",G))(hn||{}),dc=(d=>(d[d.AudioMixer=550700]="AudioMixer",d[d.AIDenoiser=551700]="AIDenoiser",d[d.VirtualBackground=570700]="VirtualBackground",d[d.Beauty=571700]="Beauty",d[d.Watermark=572700]="Watermark",d[d.BasicBeauty=574700]="BasicBeauty",d[d.CDNStreaming=590700]="CDNStreaming",d[d.DeviceDetector=591700]="DeviceDetector",d[d.Debug=592700]="Debug",d))(dc||{}),lc=(d=>(d[d.AudioMixer=550701]="AudioMixer",d[d.AIDenoiser=551701]="AIDenoiser",d[d.VirtualBackground=570701]="VirtualBackground",d[d.Beauty=571701]="Beauty",d[d.Watermark=572701]="Watermark",d[d.BasicBeauty=574701]="BasicBeauty",d[d.CDNStreaming=590701]="CDNStreaming",d[d.DeviceDetector=591701]="DeviceDetector",d[d.Debug=592701]="Debug",d))(lc||{}),uc=(d=>(d[d.AudioMixer=550702]="AudioMixer",d[d.AIDenoiser=551702]="AIDenoiser",d[d.VirtualBackground=570702]="VirtualBackground",d[d.Beauty=571702]="Beauty",d[d.Watermark=572702]="Watermark",d[d.BasicBeauty=574702]="BasicBeauty",d[d.CDNStreaming=590702]="CDNStreaming",d[d.DeviceDetector=591702]="DeviceDetector",d[d.Debug=592702]="Debug",d))(uc||{});var un=(t=>(t[t.START_MICROPHONE=501700]="START_MICROPHONE",t[t.MICROPHONE_CAHNNELS=501701]="MICROPHONE_CAHNNELS",t[t.MICROPHONE_SAMPLERATE=501702]="MICROPHONE_SAMPLERATE",t))(un||{});var cc=(i=>(i[i.START_CAMERA=511700]="START_CAMERA",i))(cc||{});var vp=new ln(!0),qi=new ln(!1);var v=vp;var K={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},Dp=new Map([[re,["Firefox",Fo]],[gr,["Edg",Go]],[Rr,["Chrome",sn]],[$e,["Safari",Ci]],[ht,["TBS",jo]],[Ts,["XWEB",qo]],[Tr&&Wi,["WeChat",Xo]],[Ss,["QQ(Win)",Qo]],[Ir,["QQ(Mobile)",_r]],[Sr,["QQ(Mobile X5)",_r]],[Is,["QQ(Mac)",zo]],[As,["QQ(iPad)",Yo]],[Rs,["MI",Ko]],[ys,["HW",Zo]],[bs,["Samsung",en]],[Ar,["OPPO",tn]],[Cr,["VIVO",rn]],[Er,["EDGE",Ho]],[Es,["SogouMobile",Wo]],[gs,["Sogou",Jo]]]);function Op(){let r=Dp.get(!0),i=r?r[0]:"unknown",e=r?r[1]:"unknown";return{browserName:i,browserVersion:e}}var pc=function(){return!(Ha||Er||gr&&$a<80||re&&Ba<56)},jl=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every(i=>i in window)},pn=function(){if(!navigator.mediaDevices)return di()||A.error(Ce.NOT_SUPPORTED_MEDIA),!1;let r=["getUserMedia","enumerateDevices"];return r.filter(i=>i in navigator.mediaDevices).length===r.length},Jl=!1;function di(){return location.protocol==="http:"&&!ti?(Jl||A.error(x({key:L.NOT_SUPPORTED_HTTP})),Jl=!0,!0):!1}var Mp=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},mc=function(){return f(this,null,function*(){if(K.detail.isH264EncodeSupported&&K.detail.isVp8EncodeSupported)return{isH264EncodeSupported:K.detail.isH264EncodeSupported,isVp8EncodeSupported:K.detail.isVp8EncodeSupported};let r,i=!1,e=!1;try{let t=new RTCPeerConnection,s=document.createElement(h.CANVAS);s.getContext("2d");let o=s.captureStream(0);return t.addTrack(o.getVideoTracks()[0],o),r=yield t.createOffer(),r.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),r.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),t.close(),K.detail.isH264EncodeSupported=i,K.detail.isVp8EncodeSupported=e,{isH264EncodeSupported:K.detail.isH264EncodeSupported,isVp8EncodeSupported:K.detail.isVp8EncodeSupported}}catch(t){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}})},fn=function(){return f(this,null,function*(){if(K.detail.isH264DecodeSupported&&K.detail.isVp8DecodeSupported)return{isH264DecodeSupported:K.detail.isH264DecodeSupported,isVp8DecodeSupported:K.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}}})},_n=rc(()=>f(void 0,null,function*(){if(K.result&&K.detail.isH264EncodeSupported&&K.detail.isVp8EncodeSupported&&K.detail.isH264DecodeSupported&&K.detail.isVp8DecodeSupported)return K;let r=Date.now(),i=pc(),e=Ec(),t=jl(),s=pn(),{isH264EncodeSupported:o,isVp8EncodeSupported:n}=yield mc(),{isH264DecodeSupported:a,isVp8DecodeSupported:c}=yield fn();if(!o||!n){let d=yield mc();A.warn(`detect encode again h264:${o} vp8:${n} result: ${JSON.stringify(d)}`),o=d.isH264EncodeSupported,n=d.isVp8EncodeSupported}if(o&&a&&(Ar||Cr||Wa)&&!ht&&ei()<79){let{encode:d,decode:u}=yield Lp();o=d,a=u}return K.result=i&&e&&s&&(o||n)&&(a||c),K.detail.isBrowserSupported=i,K.detail.isWebRTCSupported=e,K.detail.isWebCodecsSupported=t,K.detail.isMediaDevicesSupported=s,K.detail.isScreenShareSupported=$s(),K.detail.isSmallStreamSupported=Fs(),K.detail.isH264EncodeSupported=o,K.detail.isVp8EncodeSupported=n,K.detail.isH264DecodeSupported=a,K.detail.isVp8DecodeSupported=c,K.result||A.error(`${navigator.userAgent} ${ec(K.detail,!1)}`),Bp(),v.addNumber({key:523800,value:Date.now()-r}),K})),kp=function(){return K.result},$s=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},mn=null;function Lp(){return f(this,null,function*(){return mn||(mn=new Promise(r=>f(this,null,function*(){let i={encode:!1,decode:!1},e=()=>{};try{A.warn("detectH264Supported start");let t=document.createElement("canvas"),s=t.getContext("2d");t.width=320,t.height=240;let o=setInterval(()=>{s.fillText("test",Math.floor(Math.random()*320),Math.floor(Math.random()*240))},66),n=-1,a=-1;e=()=>{clearInterval(n),clearInterval(o),clearTimeout(a),d.close(),u.close(),c.getTracks().forEach(y=>y.stop())},a=setTimeout(()=>{e(),r(i)},2*1e3);let c=t.captureStream(),d=new RTCPeerConnection({}),u=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});d.addEventListener("icecandidate",y=>u.addIceCandidate(y.candidate)),u.addEventListener("icecandidate",y=>d.addIceCandidate(y.candidate)),d.addTrack(c.getVideoTracks()[0],c);let m=yield d.createOffer();yield d.setLocalDescription(m),yield u.setRemoteDescription(m);let p=yield u.createAnswer(),_=hc.default.parse(p.sdp),C=_.media[0].rtp.findIndex(y=>y.codec==="H264");_.media[0].rtp=[_.media[0].rtp[C]],_.media[0].fmtp=_.media[0].fmtp.filter(y=>y.payload===_.media[0].rtp[0].payload),_.media[0].rtcpFb&&(_.media[0].rtcpFb=_.media[0].rtcpFb.filter(y=>y.payload===_.media[0].rtp[0].payload)),p.sdp=hc.default.write(_),yield u.setLocalDescription(p),yield d.setRemoteDescription(p),n=setInterval(()=>f(this,null,function*(){i.encode&&i.decode&&(e(),r(i));let y=yield d.getSenders()[0].getStats(),D=yield u.getReceivers()[0].getStats();i.encode||y.forEach(B=>{B.type==="outbound-rtp"&&B.mediaType===h.VIDEO&&B.bytesSent>0&&(i.encode=!0)}),i.decode||D.forEach(B=>{B.type==="inbound-rtp"&&B.mediaType===h.VIDEO&&B.bytesReceived>0&&(i.decode=!0)})}),100)}catch(t){e(),A.warn(t),r(i)}})).then(r=>((!r.encode||!r.decode)&&A.warn(`detectH264Supported encode: ${r.encode} decode: ${r.decode} ${lt}`),r)),mn)})}var Pp=(r,i,e)=>{location.protocol==="http:"&&!ti&&(r[i]=()=>{throw new R({code:S.INVALID_OPERATION,message:Ce.NOT_SUPPORTED_HTTP})})},vi=function(r){return r.type==="candidate-pair"&&r.nominated&&(r.state==="in-progress"||r.state==="succeeded")?!(le(r.selected)&&!r.selected):!1};function ql(){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 Xl(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function Ql(){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 zl(){return"captureStream"in HTMLCanvasElement.prototype}function Fs(){return Tr||Be||ft&&ft<63?!1:!!(pc()&&zl())}var xp=function(){if(g(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let r=null,i=!1;try{r=new RTCPeerConnection({sdpSemantics:Si}),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 Di(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function Pt(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function tt(){return Ns===11?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var Pr=(()=>!(!tt()||pt&&ft<86))();function wp(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}function fc(){return"RTCRtpSender"in window&&"replaceTrack"in window.RTCRtpSender.prototype}function Hs(){return"RTCRtpSender"in window&&"setParameters"in window.RTCRtpSender.prototype&&Di()}var xt=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,_c=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,Tt="createEncodedStreams"in window.RTCRtpSender.prototype&&ei()>=86,En="RTCRtpScriptTransform"in window,Gs="RTCRtpSender"in window&&(Tt||En),Ec=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(i=>i in window).length>0};function gn(){let r={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return g(window.AudioDecoder)||(r.AudioDecoder=!0),g(window.AudioEncoder)||(r.AudioEncoder=!0),g(window.VideoDecoder)||(r.VideoDecoder=!0),g(window.VideoEncoder)||(r.VideoEncoder=!0),g(window.ImageDecoder)||(r.ImageDecoder=!0),r}function Yl(){return"mediaSession"in navigator&&!g(navigator.mediaSession.setActionHandler)}function Kl(){return!g(window.WebTransport)}function Vp(){return typeof WebAssembly=="undefined"?!1:WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]))}function Up(){let r={browser:`${Nt.name}/${Nt.version}`,os:on(),displayResolution:ql(),isScreenShareSupported:$s(),isWebRTCSupported:Ec(),isGetUserMediaSupported:Xl(),isWebAudioSupported:Ql(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:gn(),isMediaSessionSupported:Yl(),isWebTransportSupported:Kl()};return navigator.userAgent.includes("miniProgram")&&(r.browser=`mini/${r.browser}`),r}var Zl="checkResult";function Bp(){dn.setItem(Zl,{ua:navigator.userAgent,checkResult:K})}(function(){di();let i=dn.getItem(Zl);i&&i.ua===navigator.userAgent&&(K=i.checkResult),_n()})();function Qi(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var tu=Ie(Oe(),1);var eu=Symbol("instance"),mg=Symbol("abortCtrl"),Tn=Symbol("cacheResult"),Ws=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,qs.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},Js=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function $p(r){return typeof r=="object"&&r&&"then"in r}var js=new Map;function ue(r,i,e={}){return(t,s,o)=>{let n=e.action||s;if(!e.context){let c=js.get(t)||[];js.has(t)||js.set(t,c),c.push({from:r,to:i,action:n})}let a=o.value;o.value=function(...c){let d=this;if(e.context&&(d=F.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===i)return e.sync?d[Tn]:Promise.resolve(d[Tn]);d.state instanceof Ws&&d.state.action==e.abortAction&&d.state.abort(d);let u=null;Array.isArray(r)?r.length==0?d.state instanceof Ws&&d.state.abort(d):(typeof d.state!="string"||!r.includes(d.state))&&(u=new Js(d._state,`${d.name} ${n} to ${i} failed: current state ${d._state} not from ${r.join("|")}`)):r!==d.state&&(u=new Js(d._state,`${d.name} ${n} to ${i} failed: current state ${d._state} not from ${r}`));let m=D=>{if(e.fail&&e.fail.call(this,D),e.sync){if(e.ignoreError)return D;throw D}else return e.ignoreError?Promise.resolve(D):Promise.reject(D)};if(u)return m(u);let p=d.state,_=new Ws(p,i,n);qs.call(d,_);let C=D=>{var B;return d[Tn]=D,_.aborted||(qs.call(d,i),(B=e.success)===null||B===void 0||B.call(this,d[Tn])),D},y=D=>{let B=D instanceof Error?D.message:String(D);return qs.call(d,p,D),m(new Js(d._state,`action '${n}' failed :${B}`,D instanceof Error?D:new Error(B)))};try{let D=a.apply(this,c);return $p(D)?D.then(C).catch(y):e.sync?C(D):Promise.resolve(C(D))}catch(D){return y(D)}}}}var Fp=(()=>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 qs(r,i){let e=this._state;this._state=r;let t=r.toString();r&&this.emit(t,e),this.emit(F.STATECHANGED,r,e,i),this.updateDevTools({value:r,old:e,err:i instanceof Error?i.message:String(i)})}var F=class extends tu.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=F.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[eu];s?this.name=s.name+"-"+s.count++:t[eu]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=js.get(i)||[],t=new Set,s=[],o=[],n=new Set,a=Object.getPrototypeOf(i);js.has(a)&&(a.stateDiagram.forEach(d=>t.add(d)),a.allStates.forEach(d=>n.add(d))),e.forEach(({from:d,to:u,action:m})=>{typeof d=="string"?s.push({from:d,to:u,action:m}):d.length?d.forEach(p=>{s.push({from:p,to:u,action:m})}):o.push({to:u,action:m})}),s.forEach(({from:d,to:u,action:m})=>{n.add(d),n.add(u),n.add(m+"ing"),t.add(`${d} --> ${m}ing : ${m}`),t.add(`${m}ing --> ${u} : ${m} \u{1F7E2}`),t.add(`${m}ing --> ${d} : ${m} \u{1F534}`)}),o.forEach(({to:d,action:u})=>{t.add(`${u}ing --> ${d} : ${u} \u{1F7E2}`),n.forEach(m=>{m!==d&&t.add(`${m} --> ${u}ing : ${u}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:n}}),c}static get(i){let e;return typeof i=="string"?(e=F.instances.get(i),e||F.instances.set(i,e=new F(i,void 0,Object.create(F.prototype)))):(e=F.instances2.get(i),e||F.instances2.set(i,e=new F(i.constructor.name,void 0,Object.create(F.prototype)))),e}static getState(i){var e;return(e=F.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){Fp(F.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){qs.call(this,i)}};F.STATECHANGED="stateChanged";F.UPDATEAFSM="updateAFSM";F.INIT="[*]";F.ON="on";F.OFF="off";F.instances=new Map;F.instances2=new WeakMap;var iu=(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)},Hp=(window==null?void 0:window.cancelIdleCallback)||function(r){clearTimeout(r)},Gp=(window==null?void 0:window.cancelAnimationFrame)||(window==null?void 0:window.mozCancelAnimationFrame),Xs=class{static generateTaskID(){return this.currentTaskID++}static run(i=Ai,e,t){i===Gi?t=N({delay:2e3,count:0,backgroundTask:!0},t):i===Ii?t=N({delay:1e4,count:0},t):i===fr?t=N({fps:60,delay:16.6,count:0,backgroundTask:!0},t):t=N({delay:2e3,count:0,backgroundTask:!0},t),_t(e)&&(t=N(N({},t),e)),te(i)&&(e=i,i=Ai);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([`
@@ -40,7 +40,7 @@ let sum=0;let rms;for(let i=0;i<firstChannel.length;++i){sum+=firstChannel[i]*fi
40
40
  rms=Math.sqrt(sum/firstChannel.length);this.volume=Math.max(rms,this.volume*0.95);this.tick-=firstChannel.length;if(this.tick<0){this.tick+=(this.intervalTime/1000)*sampleRate;this.port.postMessage({volume:this.volume,cacheLen:cl,outputLen:l});}
41
41
  return true;}}
42
42
  registerProcessor("volume-meter",VolumeMeter);
43
- `,Yi=class{constructor(i){l(this,"_volume",0);l(this,"_log");l(this,"_scriptProcessorNode",null);l(this,"_audioWorkletNode",null);l(this,"_interval",200);l(this,"ready",this.preload());let{log:e}=i;this._log=e,T.on(E.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){return Yi.workletReady||(Yi.workletReady=zi(Yi.audioContext,URL.createObjectURL(new Blob([Qp],{type:"application/javascript"})))),Yi.workletReady.then(()=>this.initAudioWorklet()).catch(()=>this.initScriptProcessor())}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Yi.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{this._volume=e.data.volume||0,!i&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),i=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(i){Y.logFailedEvent({userId:this._log.userId,eventType:Ue.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=qe("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{let e=i.inputBuffer.getChannelData(0),t=0;for(let s=0;s<e.length;++s)t+=e[s]*e[s];this._volume=Math.sqrt(t/e.length)||0}}catch(i){this._log.error(`volumeMeter init script processor error: ${i}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,T.off(E.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}},Ks=Yi;l(Ks,"audioContext",qe("volume-meter")),l(Ks,"workletReady");var yn=class extends St{constructor(e){super();l(this,"_volumeMeter");this._volumeMeter=new Ks(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return f(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),s=new Float32Array(t>>2);e.copyTo(s,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:s},[s.buffer]),e.close()}}};var _u=Ie(Oe(),1);var pu=r=>i=>i.deviceId===r;var Zs=class{constructor(i,e="Input"){l(this,"kind");l(this,"type");l(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(s=>s.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&Vr(this.devices[0])){this.devices=t;return}e&&(t.forEach(s=>{if(s.deviceId&&!this.devices.find(pu(s.deviceId))){let o=`${this.kind}${this.type}Added`;A.warn(`${o}: ${JSON.stringify(s)}`),e.emit(o,s)}}),this.devices.forEach(s=>{if(s.deviceId&&!t.find(pu(s.deviceId))){let o=`${this.kind}${this.type}Removed`;A.warn(`${o}: ${JSON.stringify(s)}`),e.emit(o,s)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},yc=class extends _u.EventEmitter{constructor(){super();l(this,"audioInputs",new Zs(h.AUDIO));l(this,"videoInputs",new Zs(h.VIDEO));l(this,"audioOutputs",new Zs(h.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||Z.run(Gi,()=>{this.update()},{delay:1e4}))}init(){bn().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return f(this,arguments,function*(e=0){let t=yield bn(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}},Se=ds||ur?null:new yc;function Vr(r){return r.deviceId===r.groupId&&r.groupId===""}function bn(){return f(this,arguments,function*(r=0){if(di()||!pn())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(r!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{Vr(t)&&(t.kind===h.AUDIO_INPUT?e.audio=!0:t.kind===h.VIDEO_INPUT&&(e.video=!0))}),r===2&&(e.audio=!1),r===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e)}catch(s){A.debug("capture before getDevices failed: ",s)}i=yield navigator.mediaDevices.enumerateDevices(),t==null||t.getTracks().forEach(s=>s.stop())}}return i.map((e,t)=>{let s={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${t}`};return e.deviceId.length>0&&bc.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(s.getCapabilities=()=>e.getCapabilities()),s})})}function Fe(r=!1){return Se.update(r?1:0).then(i=>i.audioInputs.devices)}function Xe(r=!1){return Se.update(r?2:0).then(i=>i.videoInputs.devices)}var fu=!1;function Eu(){return f(this,null,function*(){try{fu||(fu=!0,A.info(`speakers:${(yield Mi()).map(r=>` ${r.deviceId.slice(0,8)}: ${r.label}`)}`))}catch(r){}})}function Mi(r=!1){return f(this,null,function*(){return Se.update(r?1:0).then(i=>i.audioOutputs.devices)})}var bc=new Set;function gu(r){if(r instanceof CanvasCaptureMediaStreamTrack||!(r instanceof MediaStreamTrack))return!1;let i=r.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let t=`${((r==null?void 0:r.getSettings())||{}).deviceId}_${h.VIDEO_INPUT}`;return!!bc.has(t)}function Tu(r){if(r instanceof CanvasCaptureMediaStreamTrack||!(r instanceof MediaStreamTrack))return!1;let i=r.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("\u9EA6\u514B\u98CE"))return!0;let t=`${((r==null?void 0:r.getSettings())||{}).deviceId}_${h.AUDIO_INPUT}`;return!!bc.has(t)}function Nc(r,i){return f(this,null,function*(){let t=(yield Fe()).find(s=>s.deviceId===Hi);return(t==null?void 0:t.groupId)===r&&t.label===i})}function Su(o){return f(this,arguments,function*({newDeviceId:r,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:s}){return r!==i?!1:s===h.AUDIO&&r===Hi?yield Nc(e,t):!0})}var Nn,vc=class extends Ys{constructor(e){super();this.log=e;l(this,"volumeMeter");l(this,"volumeDestination");l(this,"analyser",new Cn);this.volumeMeter=new yn({log:this.log}),this.volumeDestination=new St,this.volumeMeter.pipeTo(this.volumeDestination)}destory(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},Ur=class extends Bt{constructor(e){super(e,h.AUDIO);l(this,"_outputDeviceId");l(this,"_volume",1);l(this,"_destination",qe("player").createMediaStreamDestination());l(this,"pipeline");l(this,"volumeMeterMode","worklet");this.pipeline=new vc(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(){if((Ri==="15.2"||Ri==="15.3"||Ri==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let t=Nn||new Audio;t.setAttribute("autoplay","autoplay"),t.srcObject=this.getMediaStream(),t.muted=this.muted,this.element=t,t===Nn&&(Nn=void 0),this.bindElementEvents()}play(){return f(this,null,function*(){if(!!this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?this.pipeline.volumeMeter.init():this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(qe("player").createAnalyser()),this.setVolume(this._volume),Eu(),Ae(Ur.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destory(),super.stop(e)}setSinkId(e){return f(this,null,function*(){var t,s;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(s=(t=this.element).setSinkId)==null?void 0:s.call(t,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){!this.element||(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}},vn=class extends Ur{constructor(i){super(i),this.pipeline.source.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination)}setTrack(i){var e;this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(Me.MEDIA_TRACK_CHANGED,i),i?(this.bindTrackEvents(),this.pipeline.source.channelCount=((e=i.getSettings())==null?void 0:e.channelCount)||1,this.pipeline.replaceSource(i),!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([i]))):this.pipeline.source.deleteNode())}setSourceNode(i){!i||this.pipeline.source.node===i||(this.pipeline.replaceSource(i),i instanceof MediaStreamAudioSourceNode?this.pipeline.destination.setNode(this._destination):this.pipeline.destination.deleteNode(),this.element&&(this.element.srcObject=this.getMediaStream(),this.element.play().catch(()=>{}),this.setVolume(this._volume)))}setVolume(i){this._volume=i,this.element&&(this.element.volume=i)}},Dn=class extends Ur{constructor(e){super(e);l(this,"_sourceElement");this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination))}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,s,o;((s=(t=this.element)==null?void 0:t.error)==null?void 0:s.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(Me.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=((o=e.getSettings())==null?void 0:o.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`)):e<=1?(this.element?this._log.info(`set element volume: ${e}`):this._log.info("set element volume: no element"),this.element&&(this.element.volume=e)):(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),_e(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(e=0){this.pipeline.destory();let t=this._sourceElement||this.element;t&&yr&&(Nn=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var Ki=class extends F{constructor({userId:e,sdkAppId:t,mediaType:s,room:o,PlayerClass:n=s===1?Dn:je}){var a;super();l(this,"id",Us());l(this,"userId","");l(this,"isRemote");l(this,"mediaType");l(this,"room");l(this,"user");l(this,"_log");l(this,"_inputTrack");l(this,"_outputTrack");l(this,"isPlayCalled");l(this,"container",null);l(this,"player");l(this,"subVideoPlayerMap");l(this,"muted",!1);l(this,"abortCtrl");l(this,"objectFit","cover");l(this,"mirror");l(this,"isScreen",!1);l(this,"manager");l(this,"trackSettings");this.userId=e||"",this.mediaType=s,this._log=A.createLogger({id:`${this.kind[0]}t`,userId:(a=o||this.room)==null?void 0:a.userId,remoteUserId:this instanceof Qe?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof Qe}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(Me.PLAYER_STATE_CHANGED,c=>{T.emit(E.PLAYER_STATE_CHANGED,N({track:this},c)),this.emit("player-state-changed",c)}),this.kind===h.VIDEO&&(this.player.on(Me.LOADED_DATA,()=>{T.emit(E.VIDEO_LOADED_DATA,{track:this})}),this.player.on(Me.MEDIA_TRACK_CHANGED,c=>{var d;(d=this.subVideoPlayerMap)==null||d.forEach(u=>u.setTrack(c))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(Me.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||A}get kind(){return this.mediaType===1?h.AUDIO:h.VIDEO}get strMediaType(){return this.mediaType===4?h.VIDEO:this.mediaType===2?h.SCREEN:h.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}get isMediaTrackActive(){return this.mediaTrack?!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled:!1}play(e,t){return f(this,null,function*(){let s=fe(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(t)}`),t&&!g(t.muted)&&this.setPlayerMute(t.muted),t&&!g(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof je&&(this.player.setObjectFit(this.objectFit),this.container!==s&&s&&(this.container=s,this.player.setContainer(s)),fe(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t)));return}if(t&&!g(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===h.VIDEO)&&this.setPlayerMute(!0),t&&!g(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof je&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,s&&(this.container=s,this.player instanceof je&&this.player.setContainer(s)),T.emit(E.PLAY_TRACK_START,{track:this}),!this._outputTrack){this.log.info("play has not mediaTrack, abort");return}this._log.info(`play with options: ${JSON.stringify(t)}`);try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(),fe(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(o){throw this.handleAutoPlayFailed(),this.emit("error",o),o}})}setMirror(e,t){if(this.isScreen||this.kind!==h.VIDEO||g(e)||e===this.mirror)return;this.mirror=e;let s=this.player;t&&(s=t);let o=this.manager;if(le(this.mirror)){s.setViewMirror(this.mirror),o&&(o.mirror=!1);return}switch(this.mirror){case"view":{o&&(o.mirror=!1),s.setViewMirror(!0);break}case"publish":{o&&(o.mirror=!0),s.setViewMirror(!0);break}case"both":o&&(o.mirror=!0),s.setViewMirror(!1)}}playSubContainer(e,t){return f(this,null,function*(){if(!this._outputTrack||this.kind===h.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((o,n)=>{var a;e.find(c=>n===c)||(o.stop(),(a=this.subVideoPlayerMap)==null||a.delete(n))});for(let[o,n]of e.entries()){let a=this.subVideoPlayerMap.get(n);a?t&&(g(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new je({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${o+1}`})}))}let s=[...this.subVideoPlayerMap.values()];for(let o of s)o.setViewMirror(this.player.mirror),yield o.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(){!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(gt(this)?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(e=>{e.stop()}),this.container=null)}resume(){return f(this,null,function*(){var e;!this.isPlayCalled||(yield(e=this.player)==null?void 0:e.resume())})}close(){this.log.info("close"),this.isPlayCalled&&this.stop()}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),T.emit(e?E.TRACK_MUTED:E.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(e){ke(e,e).add(h.MUTE,this.onTrackMuted).add(h.UNMUTE,this.onTrackUnmuted).add(h.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===h.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){_e(e)}setInputMediaStreamTrack(e){var s;let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.trackSettings=(s=e.getSettings)==null?void 0:s.call(e),e.enabled=!this.muted,t&&this.uninstallTrackEvent(t),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,t||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var s;let t=this._outputTrack;e!==t&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(s=e.getSettings)==null?void 0:s.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(()=>this.handleAutoPlayFailed()),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(gt(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(){if(this.room&&this.room.enableAutoPlayDialog)new lu;else{let e=()=>{this.resume().then(()=>{document.removeEventListener("click",e,!0)})};document.addEventListener("click",e,!0)}}getVideoFrame(){return this.player instanceof je?this.player.getVideoFrame():""}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};b([ue([],F.INIT,{sync:!0})],Ki.prototype,"close",1);var zp=Object.prototype.hasOwnProperty,{toString:nS}=Object.prototype;function Yp(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(Je(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(zp.call(r,i))return!1;return!0}}return!1}var Ft=Yp;var Kp=function(r){return f(this,null,function*(){let i=ef(r);A.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],s=["label","deviceId"];i.audio&&(e=yield Fe(),A.info(`microphones: ${Et(e,{keysToInclude:s})}`)),i.video&&(t=yield Xe(),A.info(`cameras: ${Et(t,{keysToInclude:s})}`));try{let o=yield navigator.mediaDevices.getUserMedia(i);return _c&&o.getTracks().forEach(n=>{A.info(`${n.kind} capabilities: ${Et(n.getCapabilities(),{keysToInclude:$o})}`)}),o}catch(o){let{message:n}=o;throw o.name==="NotFoundError"&&(r.video&&t&&t.length===0&&(n=x({key:L.CAMERA_NOT_FOUND})),r.audio&&e&&e.length===0&&(n=x({key:L.MICROPHONE_NOT_FOUND}))),new R({code:S.INITIALIZE_FAILED,name:o.name,message:n,constraint:o.constraint})}})},Zp=Ot({retryFunction:Kp,settings:{retries:3,timeout:500},onError:({error:r,retry:i,reject:e,retryFuncArgs:t,retriedCount:s})=>{let o=s+1;r.name==="NotReadableError"||r.name==="OverconstrainedError"?(o===1?(t[0].video&&(t[0].maxResolution=!1,(!$e||t[0].width*t[0].height<=1920*1080)&&t[0].frameRate&&(t[0].frameRate=t[0].frameRate>10?10:5)),t[0].retryWhenExactFailed&&t[0].useExactDeviceId&&(t[0].useExactDeviceId=!1)):o===2?t[0].useDeviceIdOnly=!0:o===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(r),t[0].microphoneId&&Iu(t[0].microphoneId,!1),t[0].cameraId&&Iu(t[0].cameraId,!0)},onRetrying:r=>{A.warn(`getUserMedia NotReadableError observed, retrying [${r}/3]`)},onRetryFailed:r=>{Y.logFailedEvent({eventType:Ue.GET_USER_MEDIA_RETRY,error:r})},onRetrySuccess:r=>{Y.logSuccessEvent({eventType:Ue.GET_USER_MEDIA_RETRY}),Y.uploadEvent({log:`stat-${Ue.GET_USER_MEDIA_RETRY}-success-${r}`})}});function Iu(r,i){return f(this,null,function*(){let t=(i?yield Xe():yield Fe()).find(s=>s.deviceId===r);t&&te(t.getCapabilities)&&A.warn(Et(t.getCapabilities(),{keysToInclude:$o}))})}function ef(r){return{audio:tf(r),video:rf(r)}}function tf(r){if(!r.audio)return!1;if(r.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:r.sampleRate};return!Ft(r.microphoneId)&&(i.deviceId=r.useExactDeviceId?{exact:r.microphoneId}:r.microphoneId,r.useDeviceIdOnly)?i:(ee(r.channelCount)&&(i.channelCount=r.channelCount),le(r.echoCancellation)&&!r.echoCancellation&&(i.echoCancellation=!1),le(r.noiseSuppression)&&!r.noiseSuppression&&(i.noiseSuppression=!1),le(r.autoGainControl)&&!r.autoGainControl&&(i.autoGainControl=!1),Ft(i)?!0:i)}function rf(r){if(!r.video)return!1;if(r.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=r,e={};return r.cameraId?e.deviceId=r.useExactDeviceId?{exact:r.cameraId}:r.cameraId:r.facingMode&&(e.facingMode=r.facingMode),r.useDeviceIdOnly&&!Ft(e)?e:(r.width&&(e.width={ideal:r.width},i&&!re&&(e.width.max=r.width)),r.height&&(e.height={ideal:r.height},i&&!re&&(e.height.max=r.height)),re&&mt&&r.width&&r.height&&r.width*r.height<352*288&&(e.width=r.width,e.height=r.height),r.frameRate&&(e.frameRate=r.frameRate),Ft(e)?!0:e)}var Au=Zp;function On(r){return J((i,e)=>function(...t){return f(this,null,function*(){return yield r.apply(this,t),i.apply(this,t)})})}function It(r){return J((i,e)=>function(...t){return f(this,null,function*(){let s=yield i.apply(this,t);return yield r.call(this,...t),s})})}function J(r){return function(i,e,t){return t.value=r(t.value,e),t}}var Cu=(()=>{let r=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&A.info(`visibility change: ${document.visibilityState}`),!r&&(document.addEventListener("visibilitychange",()=>{A.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),r=!0)}})();var sf=0,Mn=class{constructor(){this.log=A.createLogger({id:`fq${++sf}`});this.isRunning=!1;this.queue=[]}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(i,e=!1){var o,n;let t=N({},i),s=new Promise((a,c)=>{t.resolve=a,t.reject=c});return t.promise=s,e?this.length<=1?this.queue.push(t):(n=(o=this.lastQueueItem)==null?void 0:o.promise)==null||n.then(t.resolve,t.reject):this.queue.push(t),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),s}shift(){let i=this.queue.shift();return this.log.debug(`shift ${this.length}`),i}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:i,args:e,context:t,resolve:s,reject:o}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(s,o).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},to=new WeakMap,kn=new WeakMap;function Ht(r=!1){return function(i,e,t){let s=t.value;return t.value=function(...o){let n=to.get(this)||new Mn;return to.set(this,n),n.push({fn:s,args:o,context:this},r)},t}}function Ru(r){return function(i,e,t){let s=t.value;return t.value=function(...o){let n=to.get(this);if(n){let a=n.queue.filter((c,d)=>{if(d===0)return!0;let u=!0;return c.args.forEach(m=>{o.find(p=>p===m)||(u=!1)}),u?(c.reject(new R({code:S.API_CALL_ABORTED,message:r})),!1):!0});n.queue=a}return s.apply(this,o)},t}}function Ln(r){return function(i,e,t){let s=t.value;return t.value=function(...o){var a,c,d;let n=[];return(c=(a=to.get(this))==null?void 0:a.queue)==null||c.forEach(u=>n.push(u)),(d=kn.get(this))==null||d.forEach(u=>u==null?void 0:u.queue.forEach(m=>n.push(m))),n.forEach(u=>{u.reject(new R({code:S.API_CALL_ABORTED,message:r}))}),to.delete(this),kn.delete(this),s.apply(this,o)},t}}function ui(r){return function(i,e,t){let s=t.value,o=n=>r(...n);return t.value=function(...n){let a=kn.get(this)||new Map,c=a.get(o(n))||new Mn;return a.set(o(n),c),kn.set(this,a),c.push({fn:s,args:n,context:this})},t}}var Dc=class extends Ki{constructor(e,t){super({mediaType:e,PlayerClass:t});l(this,"isRemote",!1);l(this,"deviceId");l(this,"groupId","");l(this,"label","");l(this,"_isRecapturing",!1);l(this,"_lastRecaptureTime",0);l(this,"_onMuteTimeoutId",-1);l(this,"_encodeCheckTimeoutId",-1);l(this,"profile")}get enableEncodeFrame(){return!1}get isPublished(){return this.state==="publish"}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){ke(e,e).add(h.MUTE,this.onTrackMuted).add(h.UNMUTE,this.onTrackUnmuted).add(h.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===h.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){_e(e)}setStateToCapture(){}capture(e){return f(this,null,function*(){var t;try{let s=w();T.emit(E.LOCAL_TRACK_CAPTURE_START,{track:this});let o;e.customSource?(o=new MediaStream,o.addTrack(e.customSource)):((t=this.mediaTrack)==null||t.stop(),o=yield Au(e));let n=o.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),T.emit(E.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:w()-s}),o}catch(s){throw T.emit(E.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:s}),this.log.error(`getUserMedia error observed ${s}`),s}})}setInputMediaStreamTrack(e){return this.state===F.INIT&&this.setStateToCapture(),super.setInputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.isPublished)return(t=this.room)==null?void 0:t.replaceTrack(this)}publish(e,t){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),t}unpublish(){this.room&&this.room.localTracks.delete(this),T.emit(E.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return f(this,null,function*(){if(this.mediaTrack&&xt){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:s}=this.mediaTrack;(yield Su({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=s,t&&(this.groupId=t),bn().then(n=>{let a=n.find(c=>c.deviceId===e);a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.mediaTrack||this.kind===h.AUDIO&&!Tu(this.mediaTrack)||this.kind===h.VIDEO&&!gu(this.mediaTrack)||this._isRecapturing||e&&mt&&$e)}onTrackMuted(){if(super.onTrackMuted(),Cu(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<pr){setTimeout(()=>this.onTrackMuted(),pr);return}this._onMuteTimeoutId=setTimeout(()=>f(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((Be||pe)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return f(this,null,function*(){if(Ae(Dc.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<pr){setTimeout(()=>this.onTrackEnded(),pr);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return f(this,null,function*(){var s;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),(s=this._inputTrack)==null||s.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let t={useExactDeviceId:!0};if(e==="user"||e==="environment")t.facingMode=e;else{let o;(this.kind==="audio"?yield Fe():yield Xe()).find(a=>a.deviceId===e)&&(o=e),t.deviceId=o}return this.capture(t).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),T.emit(E.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(o=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${o.message}`),this.emit("5",o),T.emit(E.LOCAL_TRACK_RECAPTURE,{track:this,error:o})})})}getRecoverCaptureDeviceId(){return f(this,null,function*(){let e=this instanceof he;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let s=(io.get(t)||0)+1;if(io.set(t,s),s>=3){let o=e?(yield Xe()).find(n=>!io.has(n.deviceId)):(yield Fe()).find(n=>!io.has(n.deviceId));o&&(this.log.warn(`${t} capture fail ${s} times, change new ${o.deviceId}`),t=o.deviceId)}}return t})}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),(e=this.manager)==null||e.removeInput(this)}},Qe=Dc;b([ue(F.INIT,"capture",{ignoreError:!0,sync:!0})],Qe.prototype,"setStateToCapture",1),b([Ht()],Qe.prototype,"capture",1),b([ue("capture","publish",{ignoreError:!0,success(){this.room.localTracks.add(this),T.emit(E.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this._encodeCheckTimeoutId=setTimeout(()=>{if(this.isPublished&&this.isMediaTrackActive){let r=this.kind===h.AUDIO,i=this.stat.bytesSent>0;v[i?"addSuccessEvent":"addFailedEvent"]({key:r?503700:513702}),i||(v.addEnum({key:r?503701:513703,value:Ds()}),Y.uploadEvent({log:`stat-encode-failed-${this.kind}-${Ji()||ri()}`,userId:this.userId}),this.log.warn("encode failed"),this.emit("6",this))}},5e3)},fail(r){let i="error",e=r.cause;e.message.includes("timeout")?i="timeout":e.code===S.API_CALL_ABORTED&&(i="api-call"),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:i,error:e})}})],Qe.prototype,"publish",1),b([J(r=>function(){return f(this,null,function*(){let i=this.state==="publish"?"started":"starting";r.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:i,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),ue([],"capture",{sync:!0})],Qe.prototype,"unpublish",1);var io=new Map;T.on(E.SWITCH_DEVICE_SUCCESS,r=>{r.track.deviceId&&io.delete(r.track.deviceId)});var Le=class extends Qe{constructor(e){super(1,vn);l(this,"mediaType",1);l(this,"volume",0);l(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});l(this,"playerMuted",!0);l(this,"pipeline");l(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});this.manager=e,this.pipeline=new wr(e),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}get playerMediaTrack(){return this.mediaTrack}setInputMediaStreamTrack(e){return f(this,null,function*(){yield Ae(Le.prototype,this,"setInputMediaStreamTrack").call(this,e);let t=this.trackSettings||{};v.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),v.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),v.addEnum({key:502700,value:0});let{sampleRate:s,channelCount:o}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:s,channelCount:o})}`),this.pipeline.source.channelCount=o||1,this.pipeline.replaceSource(e),this.updatePlayingState(!!e)})}capture({deviceId:e,customSource:t,useExactDeviceId:s=!0}){return super.capture({video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:s,customSource:t})}switchDevice(e){return f(this,null,function*(){if(!!this.mediaTrack){if(this.deviceId===e)if(e===Hi){if(yield Nc(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),this.room&&(yield this.room.replaceTrack(this)),T.emit(E.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(t){throw this.log.error(`switch microphone failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}}})}listenDeviceChange(){Se&&!Se.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&Se.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current microphone is lost: ${JSON.stringify(e)}`),ce(this.userId,{eventId:2003,param1:6,streamType:1});let t=yield Fe();t[0]?this.recapture(t[0].deviceId):Se.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(o){return f(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:s}){let n=!1;!g(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,n=!0),!g(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,n=!0),!g(s)&&s!==this.profile.autoGainControl&&(this.profile.autoGainControl=s,n=!0),n&&this.deviceId&&(yield this.recapture(this.deviceId))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&v.addEnum({key:502700,value:2}),this.resetPlayerSource()}enableTrackANS(e){if(!this._inputTrack)return;let t=this._inputTrack.getConstraints();return t.noiseSuppression=e,this._inputTrack.applyConstraints(t).catch(s=>this._log.warn(`${e?"enable":"disable"} ANS failed `,s))}addDenoiser(e){var t;if(ft<=92&&((t=this.trackSettings)==null?void 0:t.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}v.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.resetPlayerSource(),this.enableTrackANS(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.resetPlayerSource(),this.enableTrackANS(!0))}resetPlayerSource(){this.player.setSourceNode(this.pipeline.gain.node||this.pipeline.denoiser.node||this.pipeline.source.node)}close(){this.pipeline.remove(),Se.off("audioInputAdded",this.handleMicrophoneAdded,this),Se.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return f(this,null,function*(){try{yield Ae(Le.prototype,this,"recapture").call(this,e)}catch(t){let s=(yield Fe()).find(o=>o.deviceId!==e);if(s)yield Ae(Le.prototype,this,"recapture").call(this,s.deviceId);else throw t}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduce((t,s)=>s?s({frame:t}):t,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}};var hi=class{constructor(i,e=!1){this.dataView=i;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-2,t=[],s=0;for(let n=i;n<=e;n++){let a=this.dataView.getInt8(n);switch(a){case 0:case 1:case 2:case 3:s===2&&(t.push(3),s=0),a==0?s++:s=0,t.push(a);break;default:s=0,t.push(a);break}}t.push(this.dataView.getInt8(this.dataView.byteLength-1));let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=o}removePreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,t=[],s=0;for(let n=i;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:s++,t.push(this.dataView.getInt8(n));break;case 3:s!==2&&t.push(this.dataView.getInt8(n)),s=0;break;default:t.push(this.dataView.getInt8(n)),s=0;break}let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=o}get isSEI(){return this.dataView.getUint8(4)===6}get seiPayloadStartIndex(){let i=6;for(let e=6;e<this.dataView.buffer.byteLength&&(i++,this.dataView.getUint8(e)===255);e++);return i}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let i=0,e=6;for(let o=6;o<this.dataView.buffer.byteLength;o++){let n=this.dataView.getUint8(o);if(e++,n===255)i+=255;else{i+=n;break}}let t=new ArrayBuffer(i),s=new DataView(t);for(let o=0;o<t.byteLength;o++,e++)s.setInt8(o,this.dataView.getInt8(e));return s}};var Pn=class{constructor(){l(this,"_seiMessageList",[]);l(this,"_smallSeiMessageList",[]);l(this,"_seiPayloadType",243)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),s=e%255,o=[];o.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)o.push(255);o.push(s);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new hi(new DataView(new Uint8Array(o).buffer),!0)}sendSEI(i,e){e!=null&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(i),e!=null&&e.small&&this._smallSeiMessageList.push(i)}getNaluCount(i){let e=0,t=0,s=new DataView(i);for(let o=0;o<i.byteLength;o++)switch(s.getUint8(o)){case 0:e++;break;case 1:(e===2||e===3)&&t++,e=0;break;default:e=0;break}return t}encode(i,e){let t=e?this._smallSeiMessageList:this._seiMessageList;if(t.length>0&&i.data.byteLength>0){let s=this.getNaluCount(i.data),o=9-s;if(o<=0)return 0;let n=t.splice(0,o).reverse().map(this.encodeSEINalu.bind(this)),a=n.reduce((p,_)=>p+_.dataView.byteLength,0),c=new ArrayBuffer(a+i.data.byteLength),d=new DataView(c),u=new DataView(i.data),m=0;for(let p=0;p<n.length;p++)for(let _=0;_<n[p].dataView.byteLength;_++)d.setInt8(m++,n[p].dataView.getInt8(_));for(let p=0;p<i.data.byteLength;p++)d.setInt8(m++,u.getInt8(p));return i.data=c,n.length}return 0}};var he=class extends Qe{constructor(e,t=4){super(t,je);l(this,"profile",{width:640,height:480,frameRate:15,bitrate:500});l(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0});l(this,"small");l(this,"isNeedToSetBandwidth");l(this,"muteImage");l(this,"manager");l(this,"_seiCodec",new Pn);this.manager=e;let s=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),this.setProfile(P(N({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",s),this.on("publish",s),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!xt||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}setMute(e){return f(this,null,function*(){var t,s,o;if(z(e)){if(this.muteImage===e)return;yield(t=this.manager)==null?void 0:t.deleteWatermark("mute"),yield(s=this.manager)==null?void 0:s.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e}),this.muteImage=e,Ae(he.prototype,this,"setMute").call(this,!1)}else yield(o=this.manager)==null?void 0:o.deleteWatermark("mute"),this.muteImage=void 0,Ae(he.prototype,this,"setMute").call(this,e)})}capture({deviceId:e,facingMode:t,useExactDeviceId:s=!0,customSource:o,retryWhenExactFailed:n=!0}){return super.capture({audio:!1,video:!0,facingMode:t||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:s,retryWhenExactFailed:n,customSource:o})}setProfile(e){let t=N({},e),s=t.width>t.height;t.width*t.height<=160*120&&pe&&pt&&(this.log.warn(`resolution is ${t.width}*${t.height}, fallback to 240*180`),t.width=s?240:180,t.height=s?180:240,t.bitrate=Math.max(t.bitrate,150)),t.width*t.height>1280*720&&ja&&(t.width=s?1280:720,t.height=s?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(t):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(P(N({},this.profile),{width:1920,height:1080})))}applyProfile(){var s;if(!this.mediaTrack)return;let e=this.settings;if(e.height!==this.profile.height||e.width!==this.profile.width||e.frameRate!==this.profile.frameRate)return(s=this.mediaTrack)==null?void 0:s.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}).then(()=>{if(this.manager&&this.manager.changeInput(this),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth)return this.isNeedToSetBandwidth=!1,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:h.VIDEO,videoType:h.BIG})})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return xt&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e}get scaleResolutionDownBy(){let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:tc()&&this.profile.width>this.profile.height&&e.height>e.width?Math.max(e.width/this.profile.height,e.height/this.profile.width,1):Math.max(e.width/this.profile.width,e.height/this.profile.height,1)}isAllowed2k4k(e){var t;return!this.room||!this.room.scheduleResult||this.isScreen||e.height*e.width<2560*1440?!0:((t=this.room.scheduleResult.trtcAutoConf)==null?void 0:t["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return f(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e))return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),T.emit(E.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(t){throw this.log.error(`switch camera failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}})}listenDeviceChange(){Se&&!Se.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&Se.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current camera is lost: ${JSON.stringify(e)}`),ce(this.userId,{eventId:2003,param1:7,streamType:2});let t=yield Xe();t[0]?this.recapture(t[0].deviceId):Se.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return f(this,null,function*(){this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}encodeFrame(e,t){if(!this.manager)return e;let s=t?8:this.mediaType;return this.manager.encodePipeline.reduce((o,n)=>n?n({frame:o,mediaType:s}):o,e)}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}play(e,t){return f(this,null,function*(){return g(this.mirror)&&!this.isScreen&&this.setMirror("view"),Ae(he.prototype,this,"play").call(this,e,t)})}close(){Se.off("videoInputAdded",this.handleCameraAdded,this),Se.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return f(this,null,function*(){try{yield Ae(he.prototype,this,"recapture").call(this,e)}catch(t){let s=(yield Xe()).find(o=>o.deviceId!==e);if(s)yield Ae(he.prototype,this,"recapture").call(this,s.deviceId);else throw t}})}};var vu=Us();if(navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:vu,exposeOrigin:!0,permittedOrigins:["*"]})}catch(r){}var df=function(r){return f(this,null,function*(){let i=null,e=hf(r);A.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);r.systemAudio&&t.getAudioTracks().length===0&&(Rr&&ft<74||$e||re)&&A.warn("Your browser not support capture system audio");let s=t.getVideoTracks()[0];if(s){if(r.frameRate)try{yield s.applyConstraints({frameRate:{min:r.frameRate,ideal:r.frameRate},width:r.width,height:r.height})}catch(o){A.warn(`screen applyConstraints failed: ${o}`)}r.captureElement&&(yield lf(s,r.captureElement))}if(r.audio){let o=uf(r);A.info(`getUserMedia with constraints: ${JSON.stringify(o)}`),i=yield navigator.mediaDevices.getUserMedia(o),t.addTrack(i.getAudioTracks()[0])}return t})};function lf(r,i){return f(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&te(r.cropTo))try{if(!(((e=r.getCaptureHandle())==null?void 0:e.handle)===vu))return;let s=yield CropTarget.fromElement(i);yield r.cropTo(s)}catch(t){A.warn(`cropTo target failed ${t}`)}})}function uf(r){let i={echoCancellation:r.echoCancellation,autoGainControl:r.autoGainControl,noiseSuppression:r.noiseSuppression,sampleRate:r.sampleRate,channelCount:r.channelCount};return g(r.microphoneId)||(i.deviceId=r.microphoneId),{audio:i,video:!1}}function hf(r){let i={preferCurrentTab:r.preferDisplaySurface==="current-tab"||!!r.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:$e?{max:r.width}:{ideal:r.width,max:r.width},height:$e?{max:r.height}:{ideal:r.height,max:r.height},frameRate:r.frameRate,displaySurface:r.preferDisplaySurface||"monitor"};if(i.video=e,r.systemAudio){let{echoCancellation:t=!0,noiseSuppression:s=!1,autoGainControl:o=!1}=r;i.audio={echoCancellation:t,noiseSuppression:s,autoGainControl:o,sampleRate:48e3}}return i}var Du=df;var ze=class extends he{constructor(e){super(e,2);l(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});l(this,"objectFit","contain");l(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(u){return f(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:s,noiseSuppression:o,audioTrack:n,videoTrack:a,captureElement:c,preferDisplaySurface:d}){try{let m;return a||n?(m=new MediaStream,a&&m.addTrack(a),n&&m.addTrack(n)):m=yield Du({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:s,noiseSuppression:o,captureElement:c,preferDisplaySurface:d}),yield this.setInputMediaStreamTrack(m.getVideoTracks()[0]),m}catch(m){throw this.log.error(`getDisplayMedia error observed ${m}`),m instanceof R?m:new R({code:S.INITIALIZE_FAILED,name:m.name,message:m.message})}})}switchDevice(e){return f(this,null,function*(){throw new Error("Method not implemented.")})}};var Gt=class extends Le{constructor(i){super(i),this._log.id=`s-${this._log.id}`}};var mf="registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});",Oc;function Mc(r){return f(this,null,function*(){let i=qe("dump");Oc||(Oc=zi(i,URL.createObjectURL(new Blob([mf],{type:"application/javascript"})))),yield Oc;let e=new AudioWorkletNode(i,"dumper",{numberOfInputs:r.length,numberOfOutputs:0});return r.forEach((t,s)=>t.connect(e,0,s)),new ReadableStream({start(t){e.port.onmessage=s=>{t.enqueue(s.data)}},cancel(){r.forEach(t=>t.disconnect(e)),e.port.close()}})})}var xn=class extends Rn{constructor(e){super();this.room=e;l(this,"_localAudioTrack");l(this,"_localScreenAudioTrack");l(this,"log",A.createLogger({id:"am"}));l(this,"denoiser");l(this,"mixChangedDebounce");l(this,"encodePipeline",[]);l(this,"decodePipeline",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}dump(e){var u,m;if(!this._localAudioTrack)return;let t=[],s=[];(u=this._localAudioPipline)!=null&&u.source.node&&(t.push(this._localAudioPipline.source.node),s.push("mic")),(m=this._localAudioPipline)!=null&&m.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),s.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),s.push("mix")),this.log.info(`dump audio track ${s}, duration: ${e}`);let o=new AbortController,n=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),o.abort("timeout")},e*1e3),c=()=>{for(let p=0;p<s.length;p++){let _=URL.createObjectURL(new Blob(n[p])),C=document.createElement("a");C.href=_,C.download=`${s[p]}.pcm`,C.style.display="none",document.body.appendChild(C),C.click(),URL.revokeObjectURL(_),C.remove()}clearTimeout(a),o.abort("download")},d=Mc(t).then(p=>p.pipeTo(new WritableStream({write(_){_.forEach((C,y)=>n[y]=n[y]?n[y].concat(C[0]):[C[0]])}}),o).catch(_=>c));return{then:d.then.bind(d),download:c}}getPCM(e){var n;if(g(WritableStream)){this.log.warn("getPCM failed: browser not support WritableStream");return}if(!((n=this._localAudioPipline)!=null&&n.source.node)){this.log.warn("getPCM failed: no local audio track");return}let t=new Float32Array(1920),s=0,o=new AbortController;return Mc([this._localAudioPipline.source.node]).then(a=>a.pipeTo(new WritableStream({write(c){t.set(c[0][0],s),s+=c[0][0].length,s>=1920&&(s=0,e(t),t=new Float32Array(1920))}}),o).catch(c=>this.log.error(`stop getPCM reason:${c}`))),o}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return this._localAudioTrack!==null}changeInput(e){if(e instanceof Gt)return this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();if(e instanceof Le)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();if(e instanceof mi)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var e,t;return delete this.mixChangedDebounce,Promise.all([(e=this._localAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(e){e instanceof Gt?delete this._localScreenAudioTrack:e instanceof Le?delete this._localAudioTrack:e instanceof mi}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}removeDenoiser(e){var t;if(delete this.denoiser,(t=this._localAudioTrack)==null||t.removeDenoiser(e),this.mixChangedDebounce)return this.mixChangedDebounce}destroy(){this.close()}addEncodeProcessor({processor:e,type:t}){this.encodePipeline.includes(e)||(this.encodePipeline[t]=e)}addDecodeProcessor({processor:e,type:t}){this.decodePipeline.includes(e)||(this.decodePipeline[t]=e)}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};function wn(r=30,i=2){return J((e,t)=>function(...s){return new Promise((o,n)=>{let a=setTimeout(()=>{let c=new R({code:S.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${r}s`});A.warn(c),i===2?n(c):i===1&&o()},r*1e3);e.apply(this,s).then(o,n).finally(()=>{clearTimeout(a)})})})}var kc=class extends Ki{constructor(e,t,s){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:s,room:e});this.room=e;this.user=t;l(this,"tinyId");l(this,"isRemote",!0);l(this,"jitterBufferDelay",0);l(this,"_decodeCheckTimeoutId",-1);this.tinyId=t.tinyId}setMute(e){this.hasFlag&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.hasFlag&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===kc.STATE_SUBSCRIBE}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.hasFlag||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} hasFlag: ${this.hasFlag} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.updatePlayingState(this.hasFlag)}onTrackMuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackMuted()}onTrackUnmuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackUnmuted()}onTrackEnded(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackEnded()}},rt=kc;l(rt,"STATE_SUBSCRIBE","subscribe"),b([wn(5,1)],rt.prototype,"waitHasMediaTrack",1),b([ue(F.INIT,rt.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),T.emit(E.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0),this._decodeCheckTimeoutId=setTimeout(()=>{if(this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived>0){let r=this.kind===h.AUDIO,i=this.player.isPlaying||(r?this.getAudioLevel()>0:this.stat.framesDecoded>0);v[i?"addSuccessEvent":"addFailedEvent"]({key:r?504700:514702}),i||(v.addEnum({key:r?504701:514703,value:Ds()}),Y.uploadEvent({log:`stat-decode-failed-${this.kind}-${Ji()||ri()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===h.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`))}},5e3)},ignoreError:!0})],rt.prototype,"subscribe",1),b([ue(rt.STATE_SUBSCRIBE,F.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),T.emit(E.REMOTE_TRACK_UNSUBSCRIBED,{track:this}),clearTimeout(this._decodeCheckTimeoutId)}})],rt.prototype,"unsubscribe",1);var mi=class extends rt{constructor(e,t){super(e,t,1);l(this,"volume",0);l(this,"mediaType",1);l(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});l(this,"audioDecoder");this.manager=e.audioManager}onPlayerError(e){if(this.enableDecodeFrame){this._log.warn("use audio decoder"),this.room.enableInsertableStreams();let t=new AudioDecoder({error:s=>this._log.error(s),output:s=>{this.player.write(s)}});t.configure({codec:"opus",sampleRate:48e3,numberOfChannels:1}),this._log.info(`audioDecoder state:${t.state}`),this.audioDecoder=t}}get enableDecodeFrame(){var e,t;return this.manager?this.manager.decodePipeline.some(s=>s)||((t=(e=this.player.element)==null?void 0:e.error)==null?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&gn().AudioDecoder&&Tt:!1}decodeFrame(e){var s;if(!this.manager)return e;let t=this.manager.decodePipeline.reduce((o,n)=>n?n({frame:o}):o,e);return((s=this.audioDecoder)==null?void 0:s.state)==="configured"&&this.audioDecoder.decode(new EncodedAudioChunk({data:t.data,timestamp:t.timestamp,type:"key"})),t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get hasFlag(){return this.user.muteState.hasAudio}isFlagChanged(e){let t=e.hasAudio&&!e.audioMuted;return this.hasFlag||(this.volume=0),this.hasFlag!==t}};var ff=[-1,-1,1,-1,-1,1,1,1],_f=[0,0,1,0,0,1,1,1],Ye=class extends F{constructor(e,t){super();this.context=e;l(this,"name");l(this,"input");l(this,"output");l(this,"texture");l(this,"ctx2d",null);l(this,"fbo");l(this,"width",0);l(this,"height",0);l(this,"x",0);l(this,"y",0);l(this,"program");l(this,"vertexShader");l(this,"fragmentShader");l(this,"totalFrames",0);l(this,"dropFrames",0);l(this,"matchInputSize",!0);l(this,"texCoordBuffer");l(this,"positionBuffer");l(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});l(this,"cost",0);l(this,"_canvas",null);l(this,"_image");l(this,"log");if(this.context.on("disconnect",this.close,this),this.name=t.name,this.log=t.logger,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof Ge){if(e.ctx&&t.create2d){let s=document.createElement("canvas"),o=typeof s.transferControlToOffscreen=="function"?s.transferControlToOffscreen():s;o.width=this.width,o.height=this.height,this.ctx2d=o.getContext("2d"),this._image=o,this._canvas=o}return}try{let s=e.ctx;this.texCoordBuffer=this.createBuffer(_f),this.positionBuffer=this.createBuffer(ff),t.createTexture!==!1&&(this.texture=s.createTexture(),this.useTexture(),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.pixelStorei(s.PACK_ALIGNMENT,1),s.pixelStorei(s.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=s.createFramebuffer(),this.useBufferFrame(),this.useTexture(),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,this.width,this.height,0,s.RGBA,s.UNSIGNED_BYTE,null),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(s.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(s.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(s){this.context.destroy(new R({code:S.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${s.message||s}`}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,s=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),s}connect(e,...t){return e.addInput(this,...t),this.output=e,e}addInput(e,...t){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();if(this.context instanceof be&&this.render(e)||this.context instanceof Ge&&this.render2d(e))this.totalFrames++;else return!1;return this.cost=Date.now()-t,!0}render2d(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?this.draw2d(this.input.image,0,0,this.width,this.height):!1}update(){var e;(e=this.output)==null||e.update()}disconnect(...e){var t;(t=this.output)==null||t.removeInput(this,...e),delete this.output}removeInput(e,...t){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),(e=this.output)==null||e.removeInput(this),delete this.output,(t=this.input)==null||t.disconnect(),this.context instanceof be){let s=this.context.ctx;s.deleteBuffer(this.texCoordBuffer),s.deleteBuffer(this.positionBuffer),this.fbo&&s.deleteFramebuffer(this.fbo),this.texture&&s.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&s.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&s.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&s.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let t=this.context.ctx;e.forEach((s,o)=>{s&&(t.activeTexture(t.TEXTURE0+o),t.bindTexture(t.TEXTURE_2D,s))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,s=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,s),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),s}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let s=this.context.ctx;s.bindBuffer(s.ARRAY_BUFFER,e),s.bufferData(s.ARRAY_BUFFER,new Float32Array(t),s.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((s,o)=>{t.enableVertexAttribArray(o),t.bindBuffer(t.ARRAY_BUFFER,s),t.vertexAttribPointer(o,2,t.FLOAT,!1,0,0)})}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(!(this.width===e&&this.height===t)){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let s=this.context.ctx;s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,s.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let s=this.context.ctx;s.drawArrays(s.TRIANGLE_STRIP,0,4)}draw2d(e,t,s,o,n){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,t,s):this.ctx2d.drawImage(e,t,s,o,n),!0):!1}getInfo(){var m;let{totalFrames:e,x:t,y:s,width:o,height:n,name:a,cost:c}=this,d=Date.now(),u=(e-this.lastInfo.totalFrames)/((d-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:s,width:o,height:n,timestamp:d,fps:u,name:a,cost:c},N({parent:(m=this.input)==null?void 0:m.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,s=t.createTexture();return this.useTextures(s),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),s}};b([ue(F.INIT,"connected",{sync:!0})],Ye.prototype,"connect",1),b([ue("connected",F.INIT,{ignoreError:!0,sync:!0})],Ye.prototype,"disconnect",1),b([ue([],"closed",{sync:!0})],Ye.prototype,"close",1);function se(...r){}var Ef=r=>r();function xc(){this.dispose()}var gf=()=>typeof __FASTRX_DEVTOOLS__!="undefined",Tf=1,Wt=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new Pc(i,this,this.streamId++);return Ee.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},Br=class{constructor(){this.defers=new Set,this.disposed=!1}next(i){}complete(){this.dispose()}error(i){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=se,this.error=se,this.next=se,this.dispose=se,this.subscribe=se,this.doDefer()}subscribe(i){return i instanceof Wt?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(Ef),this.defers.clear()}defer(i){this.defers.add(i)}removeDefer(i){this.defers.delete(i)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},H=class extends Br{constructor(i){super(),this.sink=i,i.defer(this.bindDispose)}next(i){this.sink.next(i)}complete(){this.sink.complete()}error(i){this.sink.error(i)}},Vn=class extends Br{constructor(i,e=se,t=se,s=se){if(super(),this._next=e,this._error=t,this._complete=s,this.then=se,i instanceof Wt){let o={toString:()=>"subscribe",id:0,source:i};this.defer(()=>{Ee.defer(o,0)}),Ee.create(o),Ee.pipe(o),this.sourceId=o.id,this.subscribe(i),Ee.subscribe({id:o.id,end:!0}),e==se?this._next=n=>Ee.next(o,0,n):this.next=n=>{Ee.next(o,0,n),e(n)},s==se?this._complete=()=>Ee.complete(o,0):this.complete=()=>{this.dispose(),Ee.complete(o,0),s()},t==se?this._error=n=>Ee.complete(o,0,n):this.error=n=>{this.dispose(),Ee.complete(o,0,n),t()}}else this.subscribe(i)}next(i){this._next(i)}complete(){this.dispose(),this._complete()}error(i){this.dispose(),this._error(i)}};function $r(r,...i){return i.reduce((e,t)=>t(e),r)}function st(r,i,e){if(gf()){let t=Object.defineProperties(Object.setPrototypeOf(r,Wt.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:i,writable:!0,configurable:!0},args:{value:e,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});Ee.create(t);for(let s=0;s<e.length;s++){let o=e[s];typeof o=="function"&&o instanceof Wt&&Ee.addSource(t,o)}return t}return r}function j(r,i){return function(...e){return t=>{if(t instanceof Wt){let s=st(o=>{let n=new r(o,...e);n.sourceId=s.id,n.subscribe(t)},i,arguments);return s.source=t,Ee.pipe(s),s}else return s=>t(new r(s,...e))}}}function Li(r,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:r,payload:i}})}var Pc=class extends H{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{Ee.defer(this.source,this.id)})}next(i){Ee.next(this.source,this.id,i),this.sink.next(i)}complete(){Ee.complete(this.source,this.id),this.sink.complete()}error(i){Ee.complete(this.source,this.id,i),this.sink.error(i)}},Ee={addSource(r,i){Li("addSource",{id:r.id,name:r.toString(),source:{id:i.id,name:i.toString()}})},next(r,i,e){Li("next",{id:r.id,streamId:i,data:e&&e.toString()})},subscribe({id:r,end:i},e){Li("subscribe",{id:r,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(r,i,e){Li("complete",{id:r.id,streamId:i,err:e?e.toString():null})},defer(r,i){Li("defer",{id:r.id,streamId:i})},pipe(r){Li("pipe",{name:r.toString(),id:r.id,source:{id:r.source.id,name:r.source.toString()}})},update(r){Li("update",{id:r.id,name:r.toString()})},create(r){r.id||(r.id=Tf++),Li("create",{name:r.toString(),id:r.id})}},Un=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var wc=class extends Br{constructor(i){super(),this.source=i,this.sinks=new Set}add(i){i.defer(()=>this.remove(i)),this.sinks.add(i).size===1&&(this.reset(),this.subscribe(this.source))}remove(i){this.sinks.delete(i),this.sinks.size===0&&this.dispose()}next(i){this.sinks.forEach(e=>e.next(i))}complete(){this.sinks.forEach(i=>i.complete()),this.sinks.clear()}error(i){this.sinks.forEach(e=>e.error(i)),this.sinks.clear()}};function Bn(){return r=>{let i=new wc(r);if(r instanceof Wt){let e=st(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=r,Ee.pipe(e),e}return st(i.add.bind(i),"share",arguments)}}function Sf(...r){return st(i=>{let e=r.length,t=e,s=e,o=new Array(e),n=()=>{--s===0&&i.complete()},a=(c,d)=>{let u=new H(i);u.next=m=>{--t===0?(u.next=p=>{o[d]=p,i.next(o)},u.next(m)):o[d]=m},u.complete=n,u.subscribe(c)};r.forEach(a)},"combineLatest",arguments)}var Vc=class extends H{constructor(i,...e){super(i);let t=new H(this.sink);t.next=s=>this.buffer=s,t.complete=se,t.subscribe(Sf(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},KA=j(Vc,"withLatestFrom"),Uc=class extends H{constructor(i,e,t){super(i),this.bufferSize=e,this.startBufferEvery=t,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(i){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(i)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(i),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(i=>this.sink.next(i)),super.complete()}},ZA=j(Uc,"bufferCount"),Bc=class extends H{constructor(i,e){super(i),this.buffer=[];let t=new H(i);t.next=s=>{i.next(this.buffer),this.buffer=[]},t.complete=se,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},eC=j(Bc,"buffer");function Fc(r){let i=arguments,e=Bn()(st(t=>{e.next=s=>t.next(s),e.complete=()=>t.complete(),e.error=s=>t.error(s),r&&t.subscribe(r)},"subject",i));return e.next=se,e.complete=se,e.error=se,e}function Ou(r){return st(i=>{let e=0,t=setInterval(()=>i.next(e++),r);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}function $c(r,i){return e=>{let t=s=>e.next(s);e.defer(()=>i(t)),r(t)}}function ro(r,i){if("on"in r&&"off"in r)return st($c(e=>r.on(i,e),e=>r.off(i,e)),"fromEvent",arguments);if("addListener"in r&&"removeListener"in r)return st($c(e=>r.addListener(i,e),e=>r.removeListener(i,e)),"fromEvent",arguments);if("addEventListener"in r)return st($c(e=>r.addEventListener(i,e),e=>r.removeEventListener(i,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}var Hc=class extends H{constructor(i,e,t){super(i),this.f=e;let s=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=o=>{this.acc=o,this.complete=s,this.resetNext()}:(this.acc=t,this.complete=s)}next(i){this.acc=this.f(this.acc,i)}},If=j(Hc,"reduce");var Gc=class extends H{constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},Af=j(Gc,"filter"),Wc=class extends H{next(i){}},uC=j(Wc,"ignoreElements"),Jc=class extends H{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&this.complete()}},Mu=j(Jc,"take"),jc=class extends H{constructor(i,e){super(i);let t=new H(i);t.next=()=>i.complete(),t.complete=xc,t.subscribe(e)}},nd=j(jc,"takeUntil"),qc=class extends H{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):this.complete()}},Cf=j(qc,"takeWhile");var Xc=class extends H{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},hC=j(Xc,"skip"),Qc=class extends H{constructor(i,e){super(i),i.next=se;let t=new H(i);t.next=()=>{t.dispose(),i.resetNext()},t.complete=xc,t.subscribe(e)}},mC=j(Qc,"skipUntil"),zc=class extends H{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},ku=j(zc,"skipWhile"),Rf={leading:!0,trailing:!1},Yc=class extends H{constructor(i,e,t){super(i),this.durationSelector=e,this.trailing=t}cacheValue(i){this.last=i,this.disposed&&this.throttle(i)}send(i){this.sink.next(i),this.throttle(i)}throttle(i){this.reset(),this.subscribe(this.durationSelector(i))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},Kc=class extends H{constructor(i,e,t=Rf){super(i),this.durationSelector=e,this.config=t,this._throttle=new Yc(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(i){this._throttle.disposed&&this.config.leading?this._throttle.send(i):this._throttle.cacheValue(i)}complete(){this._throttle.throttle=se,this._throttle.complete(),super.complete()}},pC=j(Kc,"throttle");var Zc=class extends H{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},ed=class extends H{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new Zc(this.sink),this._debounce.dispose()}next(i){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=i,this._debounce.subscribe(this.durationSelector(i))}complete(){this._debounce.complete(),super.complete()}},fC=j(ed,"debounce");var td=class extends H{constructor(i,e,t){super(i),this.count=e,this.defaultValue=t}next(i){this.count--===0&&(this.defaultValue=i,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("not enough elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},_C=j(td,"elementAt");var id=class extends H{constructor(i,e){super(i),this.f=e,this.i=0}next(i){this.f(i)?(this.sink.next(this.i++),this.complete()):++this.i}},EC=j(id,"findIndex"),rd=class extends H{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},gC=j(rd,"first"),sd=class extends H{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i)}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},TC=j(sd,"last"),od=class extends H{constructor(i,e){super(i),this.predicate=e,this.index=0}next(i){this.predicate(i,this.index++)?this.result=!0:(this.result=!1,this.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},SC=j(od,"every");var ad=class extends H{constructor(i,e,t){super(i),this.f=e,typeof t=="undefined"?this.next=s=>{this.acc=s,this.resetNext(),this.sink.next(this.acc)}:this.acc=t}next(i){this.sink.next(this.acc=this.f(this.acc,i))}},RC=j(ad,"scan"),cd=class extends H{constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},yC=j(cd,"pairwise"),dd=class extends H{constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},Lu=j(dd,"map");var Fr=class extends H{constructor(i,e,t){super(i),this.data=e,this.context=t}next(i){let e=this.context.combineResults;e?this.sink.next(e(this.data,i)):this.sink.next(i)}tryComplete(){this.context.resetComplete(),this.dispose()}},Hr=class extends H{constructor(i,e,t){super(i),this.makeSource=e,this.combineResults=t,this.index=0}subInner(i,e){let t=this.currentSink=new e(this.sink,i,this);this.complete=this.tryComplete,t.complete=t.tryComplete,t.subscribe(this.makeSource(i,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},$n=class extends Fr{},Fn=class extends Hr{next(i){this.subInner(i,$n),this.next=e=>{this.currentSink.dispose(),this.subInner(e,$n)}}},yf=j(Fn,"switchMap");function Jn(r){return(i,e)=>r(()=>i,e)}var Pu=Jn(j(Fn,"switchMapTo")),ld=class extends Fr{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},Hn=class extends Hr{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(i){this.next2(i),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),ld),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},bC=j(Hn,"concatMap"),NC=Jn(j(Hn,"concatMapTo")),ud=class extends Fr{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Gn=class extends Hr{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,ud),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},vC=j(Gn,"mergeMap"),DC=Jn(j(Gn,"mergeMapTo")),hd=class extends Fr{dispose(){this.context.resetNext(),super.dispose()}},Wn=class extends Hr{next(i){this.next=se,this.subInner(i,hd)}},OC=j(Wn,"exhaustMap"),MC=Jn(j(Wn,"exhaustMapTo")),md=class extends H{constructor(i,e){super(i),this.f=e,this.groups=new Map}next(i){let e=this.f(i),t=this.groups.get(e);typeof t=="undefined"&&(t=Fc(),t.key=e,this.groups.set(e,t),super.next(t)),t.next(i)}complete(){this.groups.forEach(i=>i.complete()),super.complete()}error(i){this.groups.forEach(e=>e.error(i)),super.error(i)}},kC=j(md,"groupBy"),pd=class extends H{constructor(){super(...arguments),this.start=new Date}next(i){this.sink.next({value:i,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},LC=j(pd,"timeInterval"),fd=class extends H{constructor(i,e){super(i),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(i){this.buffer.push(i)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},PC=j(fd,"bufferTime"),_d=class extends H{constructor(i,e){super(i),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(i){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:t,data:s}=e;super.next(s),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(t))}},i)}next(i){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:i})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},xC=j(_d,"delay"),Ed=class extends H{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},wC=j(Ed,"catchError");var jn=(r=se,i=se,e=se)=>t=>new Vn(t,r,i,e),gd=class extends H{constructor(i,e){super(i),e instanceof Function?this.next=t=>{e(t),i.next(t)}:(e.next&&(this.next=t=>{e.next(t),i.next(t)}),e.complete&&(this.complete=()=>{e.complete(),i.complete()}),e.error&&(this.error=t=>{e.error(t),i.error(t)}))}},BC=j(gd,"tap"),Td=class extends H{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new Un(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},$C=j(Td,"timeout");var bf=$r(Ou(250),Lu(()=>performance.now()),Bn());var xu=r=>i=>{let e=performance.now();$r(bf,ku(t=>t-e<r),Mu(1))(i)};var Nf=[0,1,1,1,0,0,1,0],so=class extends Ye{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));l(this,"_intervalId",0);l(this,"_sequence",0);l(this,"checkGLError",!1);e instanceof Ge?this.ctx2d=e.ctx||null:e.available&&(t==null?void 0:t.mirrorUpAndDown)&&this.setTexBuffer(Nf)}start(e){this.log.info(`${this.name} start render ${e} fps`),this._intervalId=Z.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(Z.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof be){let s=this.context.ctx.getError();s&&this.context.destroy(new R({code:S.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${s}`}))}},{fps:this.context.frameRate})}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}update(){if(this._intervalId){this.log.info(`${this.name} use requestVideoFrameCallback`),Z.clearTask(this._intervalId),this._intervalId=0;let e=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",e))};document.addEventListener("visibilitychange",e)}this.requestFrame(this._sequence++)}removeInput(e){super.removeInput(e),Z.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}},Gr=class extends so{constructor(e,t){super(e,t);l(this,"_videoTrack");l(this,"_muteOb");l(this,"_closedOb",ro(this,"closed"));l(this,"_subscription");l(this,"_canvasContainer");Number(Ci)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=ro(this._videoTrack,"mute"),$r(ro(this._videoTrack,"ended"),nd(this._closedOb),jn(()=>{this.context.destroy(new R({code:S.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=$r(this._muteOb,nd(this._closedOb),Pu(xu(5e3)),jn(()=>{var e;!((e=this._videoTrack)!=null&&e.muted)||this.context.destroy(new R({code:S.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var e;(e=this._subscription)==null||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info(`${this.name} put canvas to body`),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,t;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack,(t=this._canvasContainer)==null||t.remove()}},qn=class extends Gr{render(i){var e;return!!((e=this.input)!=null&&e.requestFrame(i))}};var Xn=class extends Gr{constructor(e,t,s){super(e,{name:"smallDestination",logger:s});this.resolution=t}resize(e,t){let s,o=e*t,n=this.resolution.width*this.resolution.height;this.log.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),o>n?s=o/n:(this.log.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${t} small: ${this.resolution.width} * ${this.resolution.height}`),s=o/(160*120)),super.resize(e/Math.sqrt(s),t/Math.sqrt(s))}};var oo=class extends Ye{constructor(e,t){super(e,N({name:"imageSource"},t));l(this,"_lastImage");l(this,"_totalFrames",0);l(this,"_autoResize",!1);this._autoResize=(t==null?void 0:t.autoResize)!==!1}_render(e,t){let{width:s,height:o}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(Qi()&&!document.hidden&&n.requestVideoFrameCallback((a,c)=>{document.hidden||(this._totalFrames=c.presentedFrames,this.update())}),{videoWidth:s,videoHeight:o}=n,!s||!o)return!1;n.width=s,n.height=o}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if({width:s,height:o}=n,n!==this._lastImage)this._lastImage=n;else if(s===this.width&&o===this.height)return!1}else(n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas)&&({width:s,height:o}=n,this._lastImage=n);if(!this._autoResize)return!0;if(this.width===s&&this.height===o&&this.totalFrames){if(t){this.useTexture();let a=this.context.ctx;a.texSubImage2D(a.TEXTURE_2D,0,0,0,a.RGBA,a.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();let a=this.context.ctx;a.texImage2D(a.TEXTURE_2D,0,a.RGBA,a.RGBA,a.UNSIGNED_BYTE,n)}this.resize(s,o)}return!0}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},no=class extends oo{constructor(e,t,s){super(e,s);this._player=t;this.name="videoPlayerSource"}get image(){return this._player.element}},Wr=class extends no{constructor(i,e,t){super(i,new je({id:t.name,track:e,muted:!0,container:null,objectFit:"contain",log:t.logger}),t),this.name="videoTrackSource",this._player.play()}replaceTrack(i){this._player.setTrack(i),this._player.play()}close(){super.close(),this._player.stop()}};var Df=`
43
+ `,Yi=class{constructor(i){l(this,"_volume",0);l(this,"_log");l(this,"_scriptProcessorNode",null);l(this,"_audioWorkletNode",null);l(this,"_interval",200);l(this,"ready",this.preload());let{log:e}=i;this._log=e,T.on(E.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){return Yi.workletReady||(Yi.workletReady=zi(Yi.audioContext,URL.createObjectURL(new Blob([Qp],{type:"application/javascript"})))),Yi.workletReady.then(()=>this.initAudioWorklet()).catch(()=>this.initScriptProcessor())}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Yi.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{this._volume=e.data.volume||0,!i&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),i=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(i){Y.logFailedEvent({userId:this._log.userId,eventType:Ue.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=qe("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{let e=i.inputBuffer.getChannelData(0),t=0;for(let s=0;s<e.length;++s)t+=e[s]*e[s];this._volume=Math.sqrt(t/e.length)||0}}catch(i){this._log.error(`volumeMeter init script processor error: ${i}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,T.off(E.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}},Ks=Yi;l(Ks,"audioContext",qe("volume-meter")),l(Ks,"workletReady");var yn=class extends St{constructor(e){super();l(this,"_volumeMeter");this._volumeMeter=new Ks(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return f(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),s=new Float32Array(t>>2);e.copyTo(s,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:s},[s.buffer]),e.close()}}};var _u=Ie(Oe(),1);var pu=r=>i=>i.deviceId===r;var Zs=class{constructor(i,e="Input"){l(this,"kind");l(this,"type");l(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(s=>s.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&Vr(this.devices[0])){this.devices=t;return}e&&(t.forEach(s=>{if(s.deviceId&&!this.devices.find(pu(s.deviceId))){let o=`${this.kind}${this.type}Added`;A.warn(`${o}: ${JSON.stringify(s)}`),e.emit(o,s)}}),this.devices.forEach(s=>{if(s.deviceId&&!t.find(pu(s.deviceId))){let o=`${this.kind}${this.type}Removed`;A.warn(`${o}: ${JSON.stringify(s)}`),e.emit(o,s)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},yc=class extends _u.EventEmitter{constructor(){super();l(this,"audioInputs",new Zs(h.AUDIO));l(this,"videoInputs",new Zs(h.VIDEO));l(this,"audioOutputs",new Zs(h.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||Z.run(Gi,()=>{this.update()},{delay:1e4}))}init(){bn().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return f(this,arguments,function*(e=0){let t=yield bn(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}},Se=ds||ur?null:new yc;function Vr(r){return r.deviceId===r.groupId&&r.groupId===""}function bn(){return f(this,arguments,function*(r=0){if(di()||!pn())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(r!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{Vr(t)&&(t.kind===h.AUDIO_INPUT?e.audio=!0:t.kind===h.VIDEO_INPUT&&(e.video=!0))}),r===2&&(e.audio=!1),r===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e)}catch(s){A.debug("capture before getDevices failed: ",s)}i=yield navigator.mediaDevices.enumerateDevices(),t==null||t.getTracks().forEach(s=>s.stop())}}return i.map((e,t)=>{let s={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${t}`};return e.deviceId.length>0&&bc.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(s.getCapabilities=()=>e.getCapabilities()),s})})}function Fe(r=!1){return Se.update(r?1:0).then(i=>i.audioInputs.devices)}function Xe(r=!1){return Se.update(r?2:0).then(i=>i.videoInputs.devices)}var fu=!1;function Eu(){return f(this,null,function*(){try{fu||(fu=!0,A.info(`speakers:${(yield Mi()).map(r=>` ${r.deviceId.slice(0,8)}: ${r.label}`)}`))}catch(r){}})}function Mi(r=!1){return f(this,null,function*(){return Se.update(r?1:0).then(i=>i.audioOutputs.devices)})}var bc=new Set;function gu(r){if(r instanceof CanvasCaptureMediaStreamTrack||!(r instanceof MediaStreamTrack))return!1;let i=r.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let t=`${((r==null?void 0:r.getSettings())||{}).deviceId}_${h.VIDEO_INPUT}`;return!!bc.has(t)}function Tu(r){if(r instanceof CanvasCaptureMediaStreamTrack||!(r instanceof MediaStreamTrack))return!1;let i=r.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("\u9EA6\u514B\u98CE"))return!0;let t=`${((r==null?void 0:r.getSettings())||{}).deviceId}_${h.AUDIO_INPUT}`;return!!bc.has(t)}function Nc(r,i){return f(this,null,function*(){let t=(yield Fe()).find(s=>s.deviceId===Hi);return(t==null?void 0:t.groupId)===r&&t.label===i})}function Su(o){return f(this,arguments,function*({newDeviceId:r,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:s}){return r!==i?!1:s===h.AUDIO&&r===Hi?yield Nc(e,t):!0})}var Nn,vc=class extends Ys{constructor(e){super();this.log=e;l(this,"volumeMeter");l(this,"volumeDestination");l(this,"analyser",new Cn);this.volumeMeter=new yn({log:this.log}),this.volumeDestination=new St,this.volumeMeter.pipeTo(this.volumeDestination)}destory(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},Ur=class extends Bt{constructor(e){super(e,h.AUDIO);l(this,"_outputDeviceId");l(this,"_volume",1);l(this,"_destination",qe("player").createMediaStreamDestination());l(this,"pipeline");l(this,"volumeMeterMode","worklet");this.pipeline=new vc(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(){if((Ri==="15.2"||Ri==="15.3"||Ri==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let t=Nn||new Audio;t.setAttribute("autoplay","autoplay"),t.srcObject=this.getMediaStream(),t.muted=this.muted,this.element=t,t===Nn&&(Nn=void 0),this.bindElementEvents()}play(){return f(this,null,function*(){if(!!this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?this.pipeline.volumeMeter.init():this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(qe("player").createAnalyser()),this.setVolume(this._volume),Eu(),Ae(Ur.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destory(),super.stop(e)}setSinkId(e){return f(this,null,function*(){var t,s;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(s=(t=this.element).setSinkId)==null?void 0:s.call(t,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){!this.element||(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}},vn=class extends Ur{constructor(i){super(i),this.pipeline.source.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination)}setTrack(i){var e;this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(Me.MEDIA_TRACK_CHANGED,i),i?(this.bindTrackEvents(),this.pipeline.source.channelCount=((e=i.getSettings())==null?void 0:e.channelCount)||1,this.pipeline.replaceSource(i),!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([i]))):this.pipeline.source.deleteNode())}setSourceNode(i){!i||this.pipeline.source.node===i||(this.pipeline.replaceSource(i),i instanceof MediaStreamAudioSourceNode?this.pipeline.destination.setNode(this._destination):this.pipeline.destination.deleteNode(),this.element&&(this.element.srcObject=this.getMediaStream(),this.element.play().catch(()=>{}),this.setVolume(this._volume)))}setVolume(i){this._volume=i,this.element&&(this.element.volume=i)}},Dn=class extends Ur{constructor(e){super(e);l(this,"_sourceElement");this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination))}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,s,o;((s=(t=this.element)==null?void 0:t.error)==null?void 0:s.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(Me.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=((o=e.getSettings())==null?void 0:o.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`)):e<=1?(this.element?this._log.info(`set element volume: ${e}`):this._log.info("set element volume: no element"),this.element&&(this.element.volume=e)):(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),_e(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(e=0){this.pipeline.destory();let t=this._sourceElement||this.element;t&&yr&&(Nn=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var Ki=class extends F{constructor({userId:e,sdkAppId:t,mediaType:s,room:o,PlayerClass:n=s===1?Dn:je}){var a;super();l(this,"id",Us());l(this,"userId","");l(this,"isRemote");l(this,"mediaType");l(this,"room");l(this,"user");l(this,"_log");l(this,"_inputTrack");l(this,"_outputTrack");l(this,"isPlayCalled");l(this,"container",null);l(this,"player");l(this,"subVideoPlayerMap");l(this,"muted",!1);l(this,"abortCtrl");l(this,"objectFit","cover");l(this,"mirror");l(this,"isScreen",!1);l(this,"manager");l(this,"trackSettings");this.userId=e||"",this.mediaType=s,this._log=A.createLogger({id:`${this.kind[0]}t`,userId:(a=o||this.room)==null?void 0:a.userId,remoteUserId:this instanceof Qe?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof Qe}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(Me.PLAYER_STATE_CHANGED,c=>{T.emit(E.PLAYER_STATE_CHANGED,N({track:this},c)),this.emit("player-state-changed",c)}),this.kind===h.VIDEO&&(this.player.on(Me.LOADED_DATA,()=>{T.emit(E.VIDEO_LOADED_DATA,{track:this})}),this.player.on(Me.MEDIA_TRACK_CHANGED,c=>{var d;(d=this.subVideoPlayerMap)==null||d.forEach(u=>u.setTrack(c))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(Me.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||A}get kind(){return this.mediaType===1?h.AUDIO:h.VIDEO}get strMediaType(){return this.mediaType===4?h.VIDEO:this.mediaType===2?h.SCREEN:h.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}get isMediaTrackActive(){return this.mediaTrack?!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled:!1}play(e,t){return f(this,null,function*(){let s=fe(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(t)}`),t&&!g(t.muted)&&this.setPlayerMute(t.muted),t&&!g(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof je&&(this.player.setObjectFit(this.objectFit),this.container!==s&&s&&(this.container=s,this.player.setContainer(s)),fe(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t)));return}if(t&&!g(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===h.VIDEO)&&this.setPlayerMute(!0),t&&!g(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof je&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,s&&(this.container=s,this.player instanceof je&&this.player.setContainer(s)),T.emit(E.PLAY_TRACK_START,{track:this}),!this._outputTrack){this.log.info("play has not mediaTrack, abort");return}this._log.info(`play with options: ${JSON.stringify(t)}`);try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(),fe(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(o){throw this.handleAutoPlayFailed(),this.emit("error",o),o}})}setMirror(e,t){if(this.isScreen||this.kind!==h.VIDEO||g(e)||e===this.mirror)return;this.mirror=e;let s=this.player;t&&(s=t);let o=this.manager;if(le(this.mirror)){s.setViewMirror(this.mirror),o&&(o.mirror=!1);return}switch(this.mirror){case"view":{o&&(o.mirror=!1),s.setViewMirror(!0);break}case"publish":{o&&(o.mirror=!0),s.setViewMirror(!0);break}case"both":o&&(o.mirror=!0),s.setViewMirror(!1)}}playSubContainer(e,t){return f(this,null,function*(){if(!this._outputTrack||this.kind===h.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((o,n)=>{var a;e.find(c=>n===c)||(o.stop(),(a=this.subVideoPlayerMap)==null||a.delete(n))});for(let[o,n]of e.entries()){let a=this.subVideoPlayerMap.get(n);a?t&&(g(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new je({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${o+1}`})}))}let s=[...this.subVideoPlayerMap.values()];for(let o of s)o.setViewMirror(this.player.mirror),yield o.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(){!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(gt(this)?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(e=>{e.stop()}),this.container=null)}resume(){return f(this,null,function*(){var e;!this.isPlayCalled||(yield(e=this.player)==null?void 0:e.resume())})}close(){this.log.info("close"),this.isPlayCalled&&this.stop()}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),T.emit(e?E.TRACK_MUTED:E.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(e){ke(e,e).add(h.MUTE,this.onTrackMuted).add(h.UNMUTE,this.onTrackUnmuted).add(h.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===h.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){_e(e)}setInputMediaStreamTrack(e){var s;let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.trackSettings=(s=e.getSettings)==null?void 0:s.call(e),e.enabled=!this.muted,t&&this.uninstallTrackEvent(t),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,t||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var s;let t=this._outputTrack;e!==t&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(s=e.getSettings)==null?void 0:s.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(()=>this.handleAutoPlayFailed()),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(gt(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(){if(this.room&&this.room.enableAutoPlayDialog)new lu;else{let e=()=>{this.resume().then(()=>{document.removeEventListener("click",e,!0)})};document.addEventListener("click",e,!0)}}getVideoFrame(){return this.player instanceof je?this.player.getVideoFrame():""}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};b([ue([],F.INIT,{sync:!0})],Ki.prototype,"close",1);var zp=Object.prototype.hasOwnProperty,{toString:nS}=Object.prototype;function Yp(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(Je(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(zp.call(r,i))return!1;return!0}}return!1}var Ft=Yp;var Kp=function(r){return f(this,null,function*(){let i=ef(r);A.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],s=["label","deviceId"];i.audio&&(e=yield Fe(),A.info(`microphones: ${Et(e,{keysToInclude:s})}`)),i.video&&(t=yield Xe(),A.info(`cameras: ${Et(t,{keysToInclude:s})}`));try{let o=yield navigator.mediaDevices.getUserMedia(i);return _c&&o.getTracks().forEach(n=>{A.info(`${n.kind} capabilities: ${Et(n.getCapabilities(),{keysToInclude:$o})}`)}),o}catch(o){let{message:n}=o;throw o.name==="NotFoundError"&&(r.video&&t&&t.length===0&&(n=x({key:L.CAMERA_NOT_FOUND})),r.audio&&e&&e.length===0&&(n=x({key:L.MICROPHONE_NOT_FOUND}))),new R({code:S.INITIALIZE_FAILED,name:o.name,message:n,constraint:o.constraint})}})},Zp=Ot({retryFunction:Kp,settings:{retries:3,timeout:500},onError:({error:r,retry:i,reject:e,retryFuncArgs:t,retriedCount:s})=>{let o=s+1;r.name==="NotReadableError"||r.name==="OverconstrainedError"?(o===1?(t[0].video&&(t[0].maxResolution=!1,(!$e||t[0].width*t[0].height<=1920*1080)&&t[0].frameRate&&(t[0].frameRate=t[0].frameRate>10?10:5)),t[0].retryWhenExactFailed&&t[0].useExactDeviceId&&(t[0].useExactDeviceId=!1)):o===2?t[0].useDeviceIdOnly=!0:o===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(r),t[0].microphoneId&&Iu(t[0].microphoneId,!1),t[0].cameraId&&Iu(t[0].cameraId,!0)},onRetrying:r=>{A.warn(`getUserMedia NotReadableError observed, retrying [${r}/3]`)},onRetryFailed:r=>{Y.logFailedEvent({eventType:Ue.GET_USER_MEDIA_RETRY,error:r})},onRetrySuccess:r=>{Y.logSuccessEvent({eventType:Ue.GET_USER_MEDIA_RETRY}),Y.uploadEvent({log:`stat-${Ue.GET_USER_MEDIA_RETRY}-success-${r}`})}});function Iu(r,i){return f(this,null,function*(){let t=(i?yield Xe():yield Fe()).find(s=>s.deviceId===r);t&&te(t.getCapabilities)&&A.warn(Et(t.getCapabilities(),{keysToInclude:$o}))})}function ef(r){return{audio:tf(r),video:rf(r)}}function tf(r){if(!r.audio)return!1;if(r.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:r.sampleRate};return!Ft(r.microphoneId)&&(i.deviceId=r.useExactDeviceId?{exact:r.microphoneId}:r.microphoneId,r.useDeviceIdOnly)?i:(ee(r.channelCount)&&(i.channelCount=r.channelCount),le(r.echoCancellation)&&!r.echoCancellation&&(i.echoCancellation=!1),le(r.noiseSuppression)&&!r.noiseSuppression&&(i.noiseSuppression=!1),le(r.autoGainControl)&&!r.autoGainControl&&(i.autoGainControl=!1),Ft(i)?!0:i)}function rf(r){if(!r.video)return!1;if(r.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=r,e={};return r.cameraId?e.deviceId=r.useExactDeviceId?{exact:r.cameraId}:r.cameraId:r.facingMode&&(e.facingMode=r.facingMode),r.useDeviceIdOnly&&!Ft(e)?e:(r.width&&(e.width={ideal:r.width},i&&!re&&(e.width.max=r.width)),r.height&&(e.height={ideal:r.height},i&&!re&&(e.height.max=r.height)),re&&mt&&r.width&&r.height&&r.width*r.height<352*288&&(e.width=r.width,e.height=r.height),r.frameRate&&(e.frameRate=r.frameRate),Ft(e)?!0:e)}var Au=Zp;function On(r){return J((i,e)=>function(...t){return f(this,null,function*(){return yield r.apply(this,t),i.apply(this,t)})})}function It(r){return J((i,e)=>function(...t){return f(this,null,function*(){let s=yield i.apply(this,t);return yield r.call(this,...t),s})})}function J(r){return function(i,e,t){return t.value=r(t.value,e),t}}var Cu=(()=>{let r=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&A.info(`visibility change: ${document.visibilityState}`),!r&&(document.addEventListener("visibilitychange",()=>{A.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),r=!0)}})();var sf=0,Mn=class{constructor(){this.log=A.createLogger({id:`fq${++sf}`});this.isRunning=!1;this.queue=[]}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(i,e=!1){var o,n;let t=N({},i),s=new Promise((a,c)=>{t.resolve=a,t.reject=c});return t.promise=s,e?this.length<=1?this.queue.push(t):(n=(o=this.lastQueueItem)==null?void 0:o.promise)==null||n.then(t.resolve,t.reject):this.queue.push(t),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),s}shift(){let i=this.queue.shift();return this.log.debug(`shift ${this.length}`),i}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:i,args:e,context:t,resolve:s,reject:o}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(s,o).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},to=new WeakMap,kn=new WeakMap;function Ht(r=!1){return function(i,e,t){let s=t.value;return t.value=function(...o){let n=to.get(this)||new Mn;return to.set(this,n),n.push({fn:s,args:o,context:this},r)},t}}function Ru(r){return function(i,e,t){let s=t.value;return t.value=function(...o){let n=to.get(this);if(n){let a=n.queue.filter((c,d)=>{if(d===0)return!0;let u=!0;return c.args.forEach(m=>{o.find(p=>p===m)||(u=!1)}),u?(c.reject(new R({code:S.API_CALL_ABORTED,message:r})),!1):!0});n.queue=a}return s.apply(this,o)},t}}function Ln(r){return function(i,e,t){let s=t.value;return t.value=function(...o){var a,c,d;let n=[];return(c=(a=to.get(this))==null?void 0:a.queue)==null||c.forEach(u=>n.push(u)),(d=kn.get(this))==null||d.forEach(u=>u==null?void 0:u.queue.forEach(m=>n.push(m))),n.forEach(u=>{u.reject(new R({code:S.API_CALL_ABORTED,message:r}))}),to.delete(this),kn.delete(this),s.apply(this,o)},t}}function ui(r){return function(i,e,t){let s=t.value,o=n=>r(...n);return t.value=function(...n){let a=kn.get(this)||new Map,c=a.get(o(n))||new Mn;return a.set(o(n),c),kn.set(this,a),c.push({fn:s,args:n,context:this})},t}}var Dc=class extends Ki{constructor(e,t){super({mediaType:e,PlayerClass:t});l(this,"isRemote",!1);l(this,"deviceId");l(this,"groupId","");l(this,"label","");l(this,"_isRecapturing",!1);l(this,"_lastRecaptureTime",0);l(this,"_onMuteTimeoutId",-1);l(this,"_encodeCheckTimeoutId",-1);l(this,"profile")}get enableEncodeFrame(){return!1}get isPublished(){return this.state==="publish"}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){ke(e,e).add(h.MUTE,this.onTrackMuted).add(h.UNMUTE,this.onTrackUnmuted).add(h.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===h.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){_e(e)}setStateToCapture(){}capture(e){return f(this,null,function*(){var t;try{let s=w();T.emit(E.LOCAL_TRACK_CAPTURE_START,{track:this});let o;e.customSource?(o=new MediaStream,o.addTrack(e.customSource)):((t=this.mediaTrack)==null||t.stop(),o=yield Au(e));let n=o.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),T.emit(E.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:w()-s}),o}catch(s){throw T.emit(E.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:s}),this.log.error(`getUserMedia error observed ${s}`),s}})}setInputMediaStreamTrack(e){return this.state===F.INIT&&this.setStateToCapture(),super.setInputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.isPublished)return(t=this.room)==null?void 0:t.replaceTrack(this)}publish(e,t){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),t}unpublish(){this.room&&this.room.localTracks.delete(this),T.emit(E.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return f(this,null,function*(){if(this.mediaTrack&&xt){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:s}=this.mediaTrack;(yield Su({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=s,t&&(this.groupId=t),bn().then(n=>{let a=n.find(c=>c.deviceId===e);a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.mediaTrack||this.kind===h.AUDIO&&!Tu(this.mediaTrack)||this.kind===h.VIDEO&&!gu(this.mediaTrack)||this._isRecapturing||e&&mt&&$e)}onTrackMuted(){if(super.onTrackMuted(),Cu(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<pr){setTimeout(()=>this.onTrackMuted(),pr);return}this._onMuteTimeoutId=setTimeout(()=>f(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((Be||pe)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return f(this,null,function*(){if(Ae(Dc.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<pr){setTimeout(()=>this.onTrackEnded(),pr);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return f(this,null,function*(){var s;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),(s=this._inputTrack)==null||s.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let t={useExactDeviceId:!0};if(e==="user"||e==="environment")t.facingMode=e;else{let o;(this.kind==="audio"?yield Fe():yield Xe()).find(a=>a.deviceId===e)&&(o=e),t.deviceId=o}return this.capture(t).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),T.emit(E.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(o=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${o.message}`),this.emit("5",o),T.emit(E.LOCAL_TRACK_RECAPTURE,{track:this,error:o})})})}getRecoverCaptureDeviceId(){return f(this,null,function*(){let e=this instanceof he;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let s=(io.get(t)||0)+1;if(io.set(t,s),s>=3){let o=e?(yield Xe()).find(n=>!io.has(n.deviceId)):(yield Fe()).find(n=>!io.has(n.deviceId));o&&(this.log.warn(`${t} capture fail ${s} times, change new ${o.deviceId}`),t=o.deviceId)}}return t})}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),(e=this.manager)==null||e.removeInput(this)}},Qe=Dc;b([ue(F.INIT,"capture",{ignoreError:!0,sync:!0})],Qe.prototype,"setStateToCapture",1),b([Ht()],Qe.prototype,"capture",1),b([ue("capture","publish",{ignoreError:!0,success(){this.room.localTracks.add(this),T.emit(E.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this._encodeCheckTimeoutId=setTimeout(()=>{if(this.isPublished&&this.isMediaTrackActive){let r=this.kind===h.AUDIO,i=this.stat.bytesSent>0;v[i?"addSuccessEvent":"addFailedEvent"]({key:r?503700:513702}),i||(v.addEnum({key:r?503701:513703,value:Ds()}),Y.uploadEvent({log:`stat-encode-failed-${this.kind}-${Ji()||ri()}`,userId:this.userId}),this.log.warn("encode failed"),this.emit("6",this))}},5e3)},fail(r){let i="error",e=r.cause;e.message.includes("timeout")?i="timeout":e.code===S.API_CALL_ABORTED&&(i="api-call"),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:i,error:e})}})],Qe.prototype,"publish",1),b([J(r=>function(){return f(this,null,function*(){let i=this.state==="publish"?"started":"starting";r.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:i,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),ue([],"capture",{sync:!0})],Qe.prototype,"unpublish",1);var io=new Map;T.on(E.SWITCH_DEVICE_SUCCESS,r=>{r.track.deviceId&&io.delete(r.track.deviceId)});var Le=class extends Qe{constructor(e){super(1,vn);l(this,"mediaType",1);l(this,"volume",0);l(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});l(this,"playerMuted",!0);l(this,"pipeline");l(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});this.manager=e,this.pipeline=new wr(e),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}get playerMediaTrack(){return this.mediaTrack}setInputMediaStreamTrack(e){return f(this,null,function*(){yield Ae(Le.prototype,this,"setInputMediaStreamTrack").call(this,e);let t=this.trackSettings||{};v.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),v.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),v.addEnum({key:502700,value:0});let{sampleRate:s,channelCount:o}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:s,channelCount:o})}`),this.pipeline.source.channelCount=o||1,this.pipeline.replaceSource(e),this.updatePlayingState(!!e)})}capture({deviceId:e,customSource:t,useExactDeviceId:s=!0}){return super.capture({video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:s,customSource:t})}switchDevice(e){return f(this,null,function*(){if(!!this.mediaTrack){if(this.deviceId===e)if(e===Hi){if(yield Nc(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),this.room&&(yield this.room.replaceTrack(this)),T.emit(E.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(t){throw this.log.error(`switch microphone failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}}})}listenDeviceChange(){Se&&!Se.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&Se.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current microphone is lost: ${JSON.stringify(e)}`),ce(this.userId,{eventId:2003,param1:6,streamType:1});let t=yield Fe();t[0]?this.recapture(t[0].deviceId):Se.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(o){return f(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:s}){let n=!1;!g(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,n=!0),!g(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,n=!0),!g(s)&&s!==this.profile.autoGainControl&&(this.profile.autoGainControl=s,n=!0),n&&this.deviceId&&(yield this.recapture(this.deviceId))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&v.addEnum({key:502700,value:2}),this.resetPlayerSource()}enableTrackANS(e){if(!this._inputTrack)return;let t=this._inputTrack.getConstraints();return t.noiseSuppression=e,this._inputTrack.applyConstraints(t).catch(s=>this._log.warn(`${e?"enable":"disable"} ANS failed `,s))}addDenoiser(e){var t;if(ft<=92&&((t=this.trackSettings)==null?void 0:t.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}v.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.resetPlayerSource(),this.enableTrackANS(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.resetPlayerSource(),this.enableTrackANS(!0))}resetPlayerSource(){this.player.setSourceNode(this.pipeline.gain.node||this.pipeline.denoiser.node||this.pipeline.source.node)}close(){this.pipeline.remove(),Se.off("audioInputAdded",this.handleMicrophoneAdded,this),Se.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return f(this,null,function*(){try{yield Ae(Le.prototype,this,"recapture").call(this,e)}catch(t){let s=(yield Fe()).find(o=>o.deviceId!==e);if(s)yield Ae(Le.prototype,this,"recapture").call(this,s.deviceId);else throw t}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduce((t,s)=>s?s({frame:t}):t,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}};var hi=class{constructor(i,e=!1){this.dataView=i;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-2,t=[],s=0;for(let n=i;n<=e;n++){let a=this.dataView.getInt8(n);switch(a){case 0:case 1:case 2:case 3:s===2&&(t.push(3),s=0),a==0?s++:s=0,t.push(a);break;default:s=0,t.push(a);break}}t.push(this.dataView.getInt8(this.dataView.byteLength-1));let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=o}removePreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,t=[],s=0;for(let n=i;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:s++,t.push(this.dataView.getInt8(n));break;case 3:s!==2&&t.push(this.dataView.getInt8(n)),s=0;break;default:t.push(this.dataView.getInt8(n)),s=0;break}let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=o}get isSEI(){return this.dataView.getUint8(4)===6}get seiPayloadStartIndex(){let i=6;for(let e=6;e<this.dataView.buffer.byteLength&&(i++,this.dataView.getUint8(e)===255);e++);return i}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let i=0,e=6;for(let o=6;o<this.dataView.buffer.byteLength;o++){let n=this.dataView.getUint8(o);if(e++,n===255)i+=255;else{i+=n;break}}let t=new ArrayBuffer(i),s=new DataView(t);for(let o=0;o<t.byteLength;o++,e++)s.setInt8(o,this.dataView.getInt8(e));return s}};var Pn=class{constructor(){l(this,"_seiMessageList",[]);l(this,"_smallSeiMessageList",[]);l(this,"_seiPayloadType",243)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),s=e%255,o=[];o.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)o.push(255);o.push(s);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new hi(new DataView(new Uint8Array(o).buffer),!0)}sendSEI(i,e){e!=null&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(i),e!=null&&e.small&&this._smallSeiMessageList.push(i)}getNaluCount(i){let e=0,t=0,s=new DataView(i);for(let o=0;o<i.byteLength;o++)switch(s.getUint8(o)){case 0:e++;break;case 1:(e===2||e===3)&&t++,e=0;break;default:e=0;break}return t}encode(i,e){let t=e?this._smallSeiMessageList:this._seiMessageList;if(t.length>0&&i.data.byteLength>0){let s=this.getNaluCount(i.data),o=9-s;if(o<=0)return 0;let n=t.splice(0,o).reverse().map(this.encodeSEINalu.bind(this)),a=n.reduce((p,_)=>p+_.dataView.byteLength,0),c=new ArrayBuffer(a+i.data.byteLength),d=new DataView(c),u=new DataView(i.data),m=0;for(let p=0;p<n.length;p++)for(let _=0;_<n[p].dataView.byteLength;_++)d.setInt8(m++,n[p].dataView.getInt8(_));for(let p=0;p<i.data.byteLength;p++)d.setInt8(m++,u.getInt8(p));return i.data=c,n.length}return 0}};var he=class extends Qe{constructor(e,t=4){super(t,je);l(this,"profile",{width:640,height:480,frameRate:15,bitrate:500});l(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0});l(this,"small");l(this,"isNeedToSetBandwidth");l(this,"muteImage");l(this,"manager");l(this,"_seiCodec",new Pn);this.manager=e;let s=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),this.setProfile(P(N({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",s),this.on("publish",s),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!xt||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}setMute(e){return f(this,null,function*(){var t,s,o;if(z(e)){if(this.muteImage===e)return;yield(t=this.manager)==null?void 0:t.deleteWatermark("mute"),yield(s=this.manager)==null?void 0:s.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e}),this.muteImage=e,Ae(he.prototype,this,"setMute").call(this,!1)}else yield(o=this.manager)==null?void 0:o.deleteWatermark("mute"),this.muteImage=void 0,Ae(he.prototype,this,"setMute").call(this,e)})}capture({deviceId:e,facingMode:t,useExactDeviceId:s=!0,customSource:o,retryWhenExactFailed:n=!0}){return super.capture({audio:!1,video:!0,facingMode:t||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:s,retryWhenExactFailed:n,customSource:o})}setProfile(e){let t=N({},e),s=t.width>t.height;t.width*t.height<=160*120&&pe&&pt&&(this.log.warn(`resolution is ${t.width}*${t.height}, fallback to 240*180`),t.width=s?240:180,t.height=s?180:240,t.bitrate=Math.max(t.bitrate,150)),t.width*t.height>1280*720&&ja&&(t.width=s?1280:720,t.height=s?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(t):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(P(N({},this.profile),{width:1920,height:1080})))}applyProfile(){var s;if(!this.mediaTrack)return;let e=this.settings;if(e.height!==this.profile.height||e.width!==this.profile.width||e.frameRate!==this.profile.frameRate)return(s=this.mediaTrack)==null?void 0:s.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}).then(()=>{if(this.manager&&this.manager.changeInput(this),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth)return this.isNeedToSetBandwidth=!1,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:h.VIDEO,videoType:h.BIG})})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return xt&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e}get scaleResolutionDownBy(){let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:tc()&&this.profile.width>this.profile.height&&e.height>e.width?Math.max(e.width/this.profile.height,e.height/this.profile.width,1):Math.max(e.width/this.profile.width,e.height/this.profile.height,1)}isAllowed2k4k(e){var t;return!this.room||!this.room.scheduleResult||this.isScreen||e.height*e.width<2560*1440?!0:((t=this.room.scheduleResult.trtcAutoConf)==null?void 0:t["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return f(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e))return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),T.emit(E.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(t){throw this.log.error(`switch camera failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}})}listenDeviceChange(){Se&&!Se.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&Se.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current camera is lost: ${JSON.stringify(e)}`),ce(this.userId,{eventId:2003,param1:7,streamType:2});let t=yield Xe();t[0]?this.recapture(t[0].deviceId):Se.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return f(this,null,function*(){this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}encodeFrame(e,t){if(!this.manager)return e;let s=t?8:this.mediaType;return this.manager.encodePipeline.reduce((o,n)=>n?n({frame:o,mediaType:s}):o,e)}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}play(e,t){return f(this,null,function*(){return g(this.mirror)&&!this.isScreen&&this.setMirror("view"),Ae(he.prototype,this,"play").call(this,e,t)})}close(){Se.off("videoInputAdded",this.handleCameraAdded,this),Se.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return f(this,null,function*(){try{yield Ae(he.prototype,this,"recapture").call(this,e)}catch(t){let s=(yield Xe()).find(o=>o.deviceId!==e);if(s)yield Ae(he.prototype,this,"recapture").call(this,s.deviceId);else throw t}})}};var vu=Us();if(navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:vu,exposeOrigin:!0,permittedOrigins:["*"]})}catch(r){}var df=function(r){return f(this,null,function*(){let i=null,e=hf(r);A.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);r.systemAudio&&t.getAudioTracks().length===0&&(Rr&&ft<74||$e||re)&&A.warn("Your browser not support capture system audio");let s=t.getVideoTracks()[0];if(s){if(r.frameRate)try{yield s.applyConstraints({frameRate:{min:r.frameRate,ideal:r.frameRate},width:r.width,height:r.height})}catch(o){A.warn(`screen applyConstraints failed: ${o}`)}r.captureElement&&(yield lf(s,r.captureElement))}if(r.audio){let o=uf(r);A.info(`getUserMedia with constraints: ${JSON.stringify(o)}`),i=yield navigator.mediaDevices.getUserMedia(o),t.addTrack(i.getAudioTracks()[0])}return t})};function lf(r,i){return f(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&te(r.cropTo))try{if(!(((e=r.getCaptureHandle())==null?void 0:e.handle)===vu))return;let s=yield CropTarget.fromElement(i);yield r.cropTo(s)}catch(t){A.warn(`cropTo target failed ${t}`)}})}function uf(r){let i={echoCancellation:r.echoCancellation,autoGainControl:r.autoGainControl,noiseSuppression:r.noiseSuppression,sampleRate:r.sampleRate,channelCount:r.channelCount};return g(r.microphoneId)||(i.deviceId=r.microphoneId),{audio:i,video:!1}}function hf(r){let i={preferCurrentTab:r.preferDisplaySurface==="current-tab"||!!r.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:$e?{max:r.width}:{ideal:r.width,max:r.width},height:$e?{max:r.height}:{ideal:r.height,max:r.height},frameRate:r.frameRate,displaySurface:r.preferDisplaySurface||"monitor"};if(i.video=e,r.systemAudio){let{echoCancellation:t=!0,noiseSuppression:s=!1,autoGainControl:o=!1}=r;i.audio={echoCancellation:t,noiseSuppression:s,autoGainControl:o,sampleRate:48e3}}return i}var Du=df;var ze=class extends he{constructor(e){super(e,2);l(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});l(this,"objectFit","contain");l(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(u){return f(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:s,noiseSuppression:o,audioTrack:n,videoTrack:a,captureElement:c,preferDisplaySurface:d}){try{let m;return a||n?(m=new MediaStream,a&&m.addTrack(a),n&&m.addTrack(n)):m=yield Du({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:s,noiseSuppression:o,captureElement:c,preferDisplaySurface:d}),yield this.setInputMediaStreamTrack(m.getVideoTracks()[0]),m}catch(m){throw this.log.error(`getDisplayMedia error observed ${m}`),m instanceof R?m:new R({code:S.INITIALIZE_FAILED,name:m.name,message:m.message})}})}switchDevice(e){return f(this,null,function*(){throw new Error("Method not implemented.")})}};var Gt=class extends Le{constructor(i){super(i),this._log.id=`s-${this._log.id}`}};var mf="registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});",Oc;function Mc(r){return f(this,null,function*(){let i=qe("dump");Oc||(Oc=zi(i,URL.createObjectURL(new Blob([mf],{type:"application/javascript"})))),yield Oc;let e=new AudioWorkletNode(i,"dumper",{numberOfInputs:r.length,numberOfOutputs:0});return r.forEach((t,s)=>t.connect(e,0,s)),new ReadableStream({start(t){e.port.onmessage=s=>{t.enqueue(s.data)}},cancel(){r.forEach(t=>t.disconnect(e)),e.port.close()}})})}var xn=class extends Rn{constructor(e){super();this.room=e;l(this,"_localAudioTrack");l(this,"_localScreenAudioTrack");l(this,"log",A.createLogger({id:"am"}));l(this,"denoiser");l(this,"encodePipeline",[]);l(this,"decodePipeline",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}dump(e){var u,m;if(!this._localAudioTrack)return;let t=[],s=[];(u=this._localAudioPipline)!=null&&u.source.node&&(t.push(this._localAudioPipline.source.node),s.push("mic")),(m=this._localAudioPipline)!=null&&m.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),s.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),s.push("mix")),this.log.info(`dump audio track ${s}, duration: ${e}`);let o=new AbortController,n=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),o.abort("timeout")},e*1e3),c=()=>{for(let p=0;p<s.length;p++){let _=URL.createObjectURL(new Blob(n[p])),C=document.createElement("a");C.href=_,C.download=`${s[p]}.pcm`,C.style.display="none",document.body.appendChild(C),C.click(),URL.revokeObjectURL(_),C.remove()}clearTimeout(a),o.abort("download")},d=Mc(t).then(p=>p.pipeTo(new WritableStream({write(_){_.forEach((C,y)=>n[y]=n[y]?n[y].concat(C[0]):[C[0]])}}),o).catch(_=>c));return{then:d.then.bind(d),download:c}}getPCM(e){var n;if(g(WritableStream)){this.log.warn("getPCM failed: browser not support WritableStream");return}if(!((n=this._localAudioPipline)!=null&&n.source.node)){this.log.warn("getPCM failed: no local audio track");return}let t=new Float32Array(1920),s=0,o=new AbortController;return Mc([this._localAudioPipline.source.node]).then(a=>a.pipeTo(new WritableStream({write(c){!c[0][0]||(t.set(c[0][0],s),s+=c[0][0].length,s>=1920&&(s=0,e(t),t=new Float32Array(1920)))}}),o).catch(c=>this.log.error(`stop getPCM reason:${c}`))),o}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return this._localAudioTrack!==null}changeInput(e){if(e instanceof Gt)this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();else if(e instanceof Le)this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();else if(e instanceof mi)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixOnChange(){var e,t;(e=this._localAudioTrack)==null||e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null||t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)}removeInput(e){e instanceof Gt?delete this._localScreenAudioTrack:e instanceof Le?delete this._localAudioTrack:e instanceof mi}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}removeDenoiser(e){var t;delete this.denoiser,(t=this._localAudioTrack)==null||t.removeDenoiser(e)}destroy(){this.close()}addEncodeProcessor({processor:e,type:t}){this.encodePipeline.includes(e)||(this.encodePipeline[t]=e)}addDecodeProcessor({processor:e,type:t}){this.decodePipeline.includes(e)||(this.decodePipeline[t]=e)}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};function wn(r=30,i=2){return J((e,t)=>function(...s){return new Promise((o,n)=>{let a=setTimeout(()=>{let c=new R({code:S.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${r}s`});A.warn(c),i===2?n(c):i===1&&o()},r*1e3);e.apply(this,s).then(o,n).finally(()=>{clearTimeout(a)})})})}var kc=class extends Ki{constructor(e,t,s){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:s,room:e});this.room=e;this.user=t;l(this,"tinyId");l(this,"isRemote",!0);l(this,"jitterBufferDelay",0);l(this,"_decodeCheckTimeoutId",-1);this.tinyId=t.tinyId}setMute(e){this.hasFlag&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.hasFlag&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===kc.STATE_SUBSCRIBE}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.hasFlag||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} hasFlag: ${this.hasFlag} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.updatePlayingState(this.hasFlag)}onTrackMuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackMuted()}onTrackUnmuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackUnmuted()}onTrackEnded(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackEnded()}},rt=kc;l(rt,"STATE_SUBSCRIBE","subscribe"),b([wn(5,1)],rt.prototype,"waitHasMediaTrack",1),b([ue(F.INIT,rt.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),T.emit(E.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0),this._decodeCheckTimeoutId=setTimeout(()=>{if(this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived>0){let r=this.kind===h.AUDIO,i=this.player.isPlaying||(r?this.getAudioLevel()>0:this.stat.framesDecoded>0);v[i?"addSuccessEvent":"addFailedEvent"]({key:r?504700:514702}),i||(v.addEnum({key:r?504701:514703,value:Ds()}),Y.uploadEvent({log:`stat-decode-failed-${this.kind}-${Ji()||ri()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===h.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`))}},5e3)},ignoreError:!0})],rt.prototype,"subscribe",1),b([ue(rt.STATE_SUBSCRIBE,F.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),T.emit(E.REMOTE_TRACK_UNSUBSCRIBED,{track:this}),clearTimeout(this._decodeCheckTimeoutId)}})],rt.prototype,"unsubscribe",1);var mi=class extends rt{constructor(e,t){super(e,t,1);l(this,"volume",0);l(this,"mediaType",1);l(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});l(this,"audioDecoder");this.manager=e.audioManager}onPlayerError(e){if(this.enableDecodeFrame){this._log.warn("use audio decoder"),this.room.enableInsertableStreams();let t=new AudioDecoder({error:s=>this._log.error(s),output:s=>{this.player.write(s)}});t.configure({codec:"opus",sampleRate:48e3,numberOfChannels:1}),this._log.info(`audioDecoder state:${t.state}`),this.audioDecoder=t}}get enableDecodeFrame(){var e,t;return this.manager?this.manager.decodePipeline.some(s=>s)||((t=(e=this.player.element)==null?void 0:e.error)==null?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&gn().AudioDecoder&&Tt:!1}decodeFrame(e){var s;if(!this.manager)return e;let t=this.manager.decodePipeline.reduce((o,n)=>n?n({frame:o}):o,e);return((s=this.audioDecoder)==null?void 0:s.state)==="configured"&&this.audioDecoder.decode(new EncodedAudioChunk({data:t.data,timestamp:t.timestamp,type:"key"})),t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get hasFlag(){return this.user.muteState.hasAudio}isFlagChanged(e){let t=e.hasAudio&&!e.audioMuted;return this.hasFlag||(this.volume=0),this.hasFlag!==t}};var ff=[-1,-1,1,-1,-1,1,1,1],_f=[0,0,1,0,0,1,1,1],Ye=class extends F{constructor(e,t){super();this.context=e;l(this,"name");l(this,"input");l(this,"output");l(this,"texture");l(this,"ctx2d",null);l(this,"fbo");l(this,"width",0);l(this,"height",0);l(this,"x",0);l(this,"y",0);l(this,"program");l(this,"vertexShader");l(this,"fragmentShader");l(this,"totalFrames",0);l(this,"dropFrames",0);l(this,"matchInputSize",!0);l(this,"texCoordBuffer");l(this,"positionBuffer");l(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});l(this,"cost",0);l(this,"_canvas",null);l(this,"_image");l(this,"log");if(this.context.on("disconnect",this.close,this),this.name=t.name,this.log=t.logger,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof Ge){if(e.ctx&&t.create2d){let s=document.createElement("canvas"),o=typeof s.transferControlToOffscreen=="function"?s.transferControlToOffscreen():s;o.width=this.width,o.height=this.height,this.ctx2d=o.getContext("2d"),this._image=o,this._canvas=o}return}try{let s=e.ctx;this.texCoordBuffer=this.createBuffer(_f),this.positionBuffer=this.createBuffer(ff),t.createTexture!==!1&&(this.texture=s.createTexture(),this.useTexture(),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.pixelStorei(s.PACK_ALIGNMENT,1),s.pixelStorei(s.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=s.createFramebuffer(),this.useBufferFrame(),this.useTexture(),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,this.width,this.height,0,s.RGBA,s.UNSIGNED_BYTE,null),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(s.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(s.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(s){this.context.destroy(new R({code:S.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${s.message||s}`}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,s=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),s}connect(e,...t){return e.addInput(this,...t),this.output=e,e}addInput(e,...t){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();if(this.context instanceof be&&this.render(e)||this.context instanceof Ge&&this.render2d(e))this.totalFrames++;else return!1;return this.cost=Date.now()-t,!0}render2d(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?this.draw2d(this.input.image,0,0,this.width,this.height):!1}update(){var e;(e=this.output)==null||e.update()}disconnect(...e){var t;(t=this.output)==null||t.removeInput(this,...e),delete this.output}removeInput(e,...t){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),(e=this.output)==null||e.removeInput(this),delete this.output,(t=this.input)==null||t.disconnect(),this.context instanceof be){let s=this.context.ctx;s.deleteBuffer(this.texCoordBuffer),s.deleteBuffer(this.positionBuffer),this.fbo&&s.deleteFramebuffer(this.fbo),this.texture&&s.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&s.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&s.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&s.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let t=this.context.ctx;e.forEach((s,o)=>{s&&(t.activeTexture(t.TEXTURE0+o),t.bindTexture(t.TEXTURE_2D,s))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,s=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,s),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),s}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let s=this.context.ctx;s.bindBuffer(s.ARRAY_BUFFER,e),s.bufferData(s.ARRAY_BUFFER,new Float32Array(t),s.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((s,o)=>{t.enableVertexAttribArray(o),t.bindBuffer(t.ARRAY_BUFFER,s),t.vertexAttribPointer(o,2,t.FLOAT,!1,0,0)})}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(!(this.width===e&&this.height===t)){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let s=this.context.ctx;s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,s.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let s=this.context.ctx;s.drawArrays(s.TRIANGLE_STRIP,0,4)}draw2d(e,t,s,o,n){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,t,s):this.ctx2d.drawImage(e,t,s,o,n),!0):!1}getInfo(){var m;let{totalFrames:e,x:t,y:s,width:o,height:n,name:a,cost:c}=this,d=Date.now(),u=(e-this.lastInfo.totalFrames)/((d-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:s,width:o,height:n,timestamp:d,fps:u,name:a,cost:c},N({parent:(m=this.input)==null?void 0:m.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,s=t.createTexture();return this.useTextures(s),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),s}};b([ue(F.INIT,"connected",{sync:!0})],Ye.prototype,"connect",1),b([ue("connected",F.INIT,{ignoreError:!0,sync:!0})],Ye.prototype,"disconnect",1),b([ue([],"closed",{sync:!0})],Ye.prototype,"close",1);function se(...r){}var Ef=r=>r();function xc(){this.dispose()}var gf=()=>typeof __FASTRX_DEVTOOLS__!="undefined",Tf=1,Wt=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new Pc(i,this,this.streamId++);return Ee.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},Br=class{constructor(){this.defers=new Set,this.disposed=!1}next(i){}complete(){this.dispose()}error(i){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=se,this.error=se,this.next=se,this.dispose=se,this.subscribe=se,this.doDefer()}subscribe(i){return i instanceof Wt?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(Ef),this.defers.clear()}defer(i){this.defers.add(i)}removeDefer(i){this.defers.delete(i)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},H=class extends Br{constructor(i){super(),this.sink=i,i.defer(this.bindDispose)}next(i){this.sink.next(i)}complete(){this.sink.complete()}error(i){this.sink.error(i)}},Vn=class extends Br{constructor(i,e=se,t=se,s=se){if(super(),this._next=e,this._error=t,this._complete=s,this.then=se,i instanceof Wt){let o={toString:()=>"subscribe",id:0,source:i};this.defer(()=>{Ee.defer(o,0)}),Ee.create(o),Ee.pipe(o),this.sourceId=o.id,this.subscribe(i),Ee.subscribe({id:o.id,end:!0}),e==se?this._next=n=>Ee.next(o,0,n):this.next=n=>{Ee.next(o,0,n),e(n)},s==se?this._complete=()=>Ee.complete(o,0):this.complete=()=>{this.dispose(),Ee.complete(o,0),s()},t==se?this._error=n=>Ee.complete(o,0,n):this.error=n=>{this.dispose(),Ee.complete(o,0,n),t()}}else this.subscribe(i)}next(i){this._next(i)}complete(){this.dispose(),this._complete()}error(i){this.dispose(),this._error(i)}};function $r(r,...i){return i.reduce((e,t)=>t(e),r)}function st(r,i,e){if(gf()){let t=Object.defineProperties(Object.setPrototypeOf(r,Wt.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:i,writable:!0,configurable:!0},args:{value:e,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});Ee.create(t);for(let s=0;s<e.length;s++){let o=e[s];typeof o=="function"&&o instanceof Wt&&Ee.addSource(t,o)}return t}return r}function j(r,i){return function(...e){return t=>{if(t instanceof Wt){let s=st(o=>{let n=new r(o,...e);n.sourceId=s.id,n.subscribe(t)},i,arguments);return s.source=t,Ee.pipe(s),s}else return s=>t(new r(s,...e))}}}function Li(r,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:r,payload:i}})}var Pc=class extends H{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{Ee.defer(this.source,this.id)})}next(i){Ee.next(this.source,this.id,i),this.sink.next(i)}complete(){Ee.complete(this.source,this.id),this.sink.complete()}error(i){Ee.complete(this.source,this.id,i),this.sink.error(i)}},Ee={addSource(r,i){Li("addSource",{id:r.id,name:r.toString(),source:{id:i.id,name:i.toString()}})},next(r,i,e){Li("next",{id:r.id,streamId:i,data:e&&e.toString()})},subscribe({id:r,end:i},e){Li("subscribe",{id:r,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(r,i,e){Li("complete",{id:r.id,streamId:i,err:e?e.toString():null})},defer(r,i){Li("defer",{id:r.id,streamId:i})},pipe(r){Li("pipe",{name:r.toString(),id:r.id,source:{id:r.source.id,name:r.source.toString()}})},update(r){Li("update",{id:r.id,name:r.toString()})},create(r){r.id||(r.id=Tf++),Li("create",{name:r.toString(),id:r.id})}},Un=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var wc=class extends Br{constructor(i){super(),this.source=i,this.sinks=new Set}add(i){i.defer(()=>this.remove(i)),this.sinks.add(i).size===1&&(this.reset(),this.subscribe(this.source))}remove(i){this.sinks.delete(i),this.sinks.size===0&&this.dispose()}next(i){this.sinks.forEach(e=>e.next(i))}complete(){this.sinks.forEach(i=>i.complete()),this.sinks.clear()}error(i){this.sinks.forEach(e=>e.error(i)),this.sinks.clear()}};function Bn(){return r=>{let i=new wc(r);if(r instanceof Wt){let e=st(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=r,Ee.pipe(e),e}return st(i.add.bind(i),"share",arguments)}}function Sf(...r){return st(i=>{let e=r.length,t=e,s=e,o=new Array(e),n=()=>{--s===0&&i.complete()},a=(c,d)=>{let u=new H(i);u.next=m=>{--t===0?(u.next=p=>{o[d]=p,i.next(o)},u.next(m)):o[d]=m},u.complete=n,u.subscribe(c)};r.forEach(a)},"combineLatest",arguments)}var Vc=class extends H{constructor(i,...e){super(i);let t=new H(this.sink);t.next=s=>this.buffer=s,t.complete=se,t.subscribe(Sf(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},KA=j(Vc,"withLatestFrom"),Uc=class extends H{constructor(i,e,t){super(i),this.bufferSize=e,this.startBufferEvery=t,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(i){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(i)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(i),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(i=>this.sink.next(i)),super.complete()}},ZA=j(Uc,"bufferCount"),Bc=class extends H{constructor(i,e){super(i),this.buffer=[];let t=new H(i);t.next=s=>{i.next(this.buffer),this.buffer=[]},t.complete=se,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},eC=j(Bc,"buffer");function Fc(r){let i=arguments,e=Bn()(st(t=>{e.next=s=>t.next(s),e.complete=()=>t.complete(),e.error=s=>t.error(s),r&&t.subscribe(r)},"subject",i));return e.next=se,e.complete=se,e.error=se,e}function Ou(r){return st(i=>{let e=0,t=setInterval(()=>i.next(e++),r);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}function $c(r,i){return e=>{let t=s=>e.next(s);e.defer(()=>i(t)),r(t)}}function ro(r,i){if("on"in r&&"off"in r)return st($c(e=>r.on(i,e),e=>r.off(i,e)),"fromEvent",arguments);if("addListener"in r&&"removeListener"in r)return st($c(e=>r.addListener(i,e),e=>r.removeListener(i,e)),"fromEvent",arguments);if("addEventListener"in r)return st($c(e=>r.addEventListener(i,e),e=>r.removeEventListener(i,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}var Hc=class extends H{constructor(i,e,t){super(i),this.f=e;let s=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=o=>{this.acc=o,this.complete=s,this.resetNext()}:(this.acc=t,this.complete=s)}next(i){this.acc=this.f(this.acc,i)}},If=j(Hc,"reduce");var Gc=class extends H{constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},Af=j(Gc,"filter"),Wc=class extends H{next(i){}},uC=j(Wc,"ignoreElements"),Jc=class extends H{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&this.complete()}},Mu=j(Jc,"take"),jc=class extends H{constructor(i,e){super(i);let t=new H(i);t.next=()=>i.complete(),t.complete=xc,t.subscribe(e)}},nd=j(jc,"takeUntil"),qc=class extends H{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):this.complete()}},Cf=j(qc,"takeWhile");var Xc=class extends H{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},hC=j(Xc,"skip"),Qc=class extends H{constructor(i,e){super(i),i.next=se;let t=new H(i);t.next=()=>{t.dispose(),i.resetNext()},t.complete=xc,t.subscribe(e)}},mC=j(Qc,"skipUntil"),zc=class extends H{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},ku=j(zc,"skipWhile"),Rf={leading:!0,trailing:!1},Yc=class extends H{constructor(i,e,t){super(i),this.durationSelector=e,this.trailing=t}cacheValue(i){this.last=i,this.disposed&&this.throttle(i)}send(i){this.sink.next(i),this.throttle(i)}throttle(i){this.reset(),this.subscribe(this.durationSelector(i))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},Kc=class extends H{constructor(i,e,t=Rf){super(i),this.durationSelector=e,this.config=t,this._throttle=new Yc(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(i){this._throttle.disposed&&this.config.leading?this._throttle.send(i):this._throttle.cacheValue(i)}complete(){this._throttle.throttle=se,this._throttle.complete(),super.complete()}},pC=j(Kc,"throttle");var Zc=class extends H{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},ed=class extends H{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new Zc(this.sink),this._debounce.dispose()}next(i){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=i,this._debounce.subscribe(this.durationSelector(i))}complete(){this._debounce.complete(),super.complete()}},fC=j(ed,"debounce");var td=class extends H{constructor(i,e,t){super(i),this.count=e,this.defaultValue=t}next(i){this.count--===0&&(this.defaultValue=i,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("not enough elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},_C=j(td,"elementAt");var id=class extends H{constructor(i,e){super(i),this.f=e,this.i=0}next(i){this.f(i)?(this.sink.next(this.i++),this.complete()):++this.i}},EC=j(id,"findIndex"),rd=class extends H{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},gC=j(rd,"first"),sd=class extends H{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i)}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},TC=j(sd,"last"),od=class extends H{constructor(i,e){super(i),this.predicate=e,this.index=0}next(i){this.predicate(i,this.index++)?this.result=!0:(this.result=!1,this.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},SC=j(od,"every");var ad=class extends H{constructor(i,e,t){super(i),this.f=e,typeof t=="undefined"?this.next=s=>{this.acc=s,this.resetNext(),this.sink.next(this.acc)}:this.acc=t}next(i){this.sink.next(this.acc=this.f(this.acc,i))}},RC=j(ad,"scan"),cd=class extends H{constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},yC=j(cd,"pairwise"),dd=class extends H{constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},Lu=j(dd,"map");var Fr=class extends H{constructor(i,e,t){super(i),this.data=e,this.context=t}next(i){let e=this.context.combineResults;e?this.sink.next(e(this.data,i)):this.sink.next(i)}tryComplete(){this.context.resetComplete(),this.dispose()}},Hr=class extends H{constructor(i,e,t){super(i),this.makeSource=e,this.combineResults=t,this.index=0}subInner(i,e){let t=this.currentSink=new e(this.sink,i,this);this.complete=this.tryComplete,t.complete=t.tryComplete,t.subscribe(this.makeSource(i,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},$n=class extends Fr{},Fn=class extends Hr{next(i){this.subInner(i,$n),this.next=e=>{this.currentSink.dispose(),this.subInner(e,$n)}}},yf=j(Fn,"switchMap");function Jn(r){return(i,e)=>r(()=>i,e)}var Pu=Jn(j(Fn,"switchMapTo")),ld=class extends Fr{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},Hn=class extends Hr{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(i){this.next2(i),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),ld),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},bC=j(Hn,"concatMap"),NC=Jn(j(Hn,"concatMapTo")),ud=class extends Fr{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Gn=class extends Hr{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,ud),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},vC=j(Gn,"mergeMap"),DC=Jn(j(Gn,"mergeMapTo")),hd=class extends Fr{dispose(){this.context.resetNext(),super.dispose()}},Wn=class extends Hr{next(i){this.next=se,this.subInner(i,hd)}},OC=j(Wn,"exhaustMap"),MC=Jn(j(Wn,"exhaustMapTo")),md=class extends H{constructor(i,e){super(i),this.f=e,this.groups=new Map}next(i){let e=this.f(i),t=this.groups.get(e);typeof t=="undefined"&&(t=Fc(),t.key=e,this.groups.set(e,t),super.next(t)),t.next(i)}complete(){this.groups.forEach(i=>i.complete()),super.complete()}error(i){this.groups.forEach(e=>e.error(i)),super.error(i)}},kC=j(md,"groupBy"),pd=class extends H{constructor(){super(...arguments),this.start=new Date}next(i){this.sink.next({value:i,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},LC=j(pd,"timeInterval"),fd=class extends H{constructor(i,e){super(i),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(i){this.buffer.push(i)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},PC=j(fd,"bufferTime"),_d=class extends H{constructor(i,e){super(i),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(i){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:t,data:s}=e;super.next(s),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(t))}},i)}next(i){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:i})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},xC=j(_d,"delay"),Ed=class extends H{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},wC=j(Ed,"catchError");var jn=(r=se,i=se,e=se)=>t=>new Vn(t,r,i,e),gd=class extends H{constructor(i,e){super(i),e instanceof Function?this.next=t=>{e(t),i.next(t)}:(e.next&&(this.next=t=>{e.next(t),i.next(t)}),e.complete&&(this.complete=()=>{e.complete(),i.complete()}),e.error&&(this.error=t=>{e.error(t),i.error(t)}))}},BC=j(gd,"tap"),Td=class extends H{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new Un(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},$C=j(Td,"timeout");var bf=$r(Ou(250),Lu(()=>performance.now()),Bn());var xu=r=>i=>{let e=performance.now();$r(bf,ku(t=>t-e<r),Mu(1))(i)};var Nf=[0,1,1,1,0,0,1,0],so=class extends Ye{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));l(this,"_intervalId",0);l(this,"_sequence",0);l(this,"checkGLError",!1);e instanceof Ge?this.ctx2d=e.ctx||null:e.available&&(t==null?void 0:t.mirrorUpAndDown)&&this.setTexBuffer(Nf)}start(e){this.log.info(`${this.name} start render ${e} fps`),this._intervalId=Z.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(Z.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof be){let s=this.context.ctx.getError();s&&this.context.destroy(new R({code:S.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${s}`}))}},{fps:this.context.frameRate})}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}update(){if(this._intervalId){this.log.info(`${this.name} use requestVideoFrameCallback`),Z.clearTask(this._intervalId),this._intervalId=0;let e=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",e))};document.addEventListener("visibilitychange",e)}this.requestFrame(this._sequence++)}removeInput(e){super.removeInput(e),Z.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}},Gr=class extends so{constructor(e,t){super(e,t);l(this,"_videoTrack");l(this,"_muteOb");l(this,"_closedOb",ro(this,"closed"));l(this,"_subscription");l(this,"_canvasContainer");Number(Ci)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=ro(this._videoTrack,"mute"),$r(ro(this._videoTrack,"ended"),nd(this._closedOb),jn(()=>{this.context.destroy(new R({code:S.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=$r(this._muteOb,nd(this._closedOb),Pu(xu(5e3)),jn(()=>{var e;!((e=this._videoTrack)!=null&&e.muted)||this.context.destroy(new R({code:S.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var e;(e=this._subscription)==null||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info(`${this.name} put canvas to body`),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,t;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack,(t=this._canvasContainer)==null||t.remove()}},qn=class extends Gr{render(i){var e;return!!((e=this.input)!=null&&e.requestFrame(i))}};var Xn=class extends Gr{constructor(e,t,s){super(e,{name:"smallDestination",logger:s});this.resolution=t}resize(e,t){let s,o=e*t,n=this.resolution.width*this.resolution.height;this.log.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),o>n?s=o/n:(this.log.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${t} small: ${this.resolution.width} * ${this.resolution.height}`),s=o/(160*120)),super.resize(e/Math.sqrt(s),t/Math.sqrt(s))}};var oo=class extends Ye{constructor(e,t){super(e,N({name:"imageSource"},t));l(this,"_lastImage");l(this,"_totalFrames",0);l(this,"_autoResize",!1);this._autoResize=(t==null?void 0:t.autoResize)!==!1}_render(e,t){let{width:s,height:o}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(Qi()&&!document.hidden&&n.requestVideoFrameCallback((a,c)=>{document.hidden||(this._totalFrames=c.presentedFrames,this.update())}),{videoWidth:s,videoHeight:o}=n,!s||!o)return!1;n.width=s,n.height=o}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if({width:s,height:o}=n,n!==this._lastImage)this._lastImage=n;else if(s===this.width&&o===this.height)return!1}else(n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas)&&({width:s,height:o}=n,this._lastImage=n);if(!this._autoResize)return!0;if(this.width===s&&this.height===o&&this.totalFrames){if(t){this.useTexture();let a=this.context.ctx;a.texSubImage2D(a.TEXTURE_2D,0,0,0,a.RGBA,a.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();let a=this.context.ctx;a.texImage2D(a.TEXTURE_2D,0,a.RGBA,a.RGBA,a.UNSIGNED_BYTE,n)}this.resize(s,o)}return!0}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},no=class extends oo{constructor(e,t,s){super(e,s);this._player=t;this.name="videoPlayerSource"}get image(){return this._player.element}},Wr=class extends no{constructor(i,e,t){super(i,new je({id:t.name,track:e,muted:!0,container:null,objectFit:"contain",log:t.logger}),t),this.name="videoTrackSource",this._player.play()}replaceTrack(i){this._player.setTrack(i),this._player.play()}close(){super.close(),this._player.stop()}};var Df=`
44
44
  // \u9876\u70B9\u7740\u8272\u5668
45
45
  attribute vec4 a_position;
46
46
  attribute vec2 a_texCoord;
@@ -62,7 +62,7 @@ void main() {
62
62
  `)))}else{if(e instanceof tr)return e;o=new tr({code:V.UNKNOWN_ERROR,fnName:t,originError:e})}return o}};function Lf(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 k=tr;var Hu={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}}},Gu={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}}},qr={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(r,i,e){if(z(r)&&!document.getElementById(r))throw new k({code:V.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},Wu={name:"userId",required:!0,type:"string"},Ju={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[ot.AUDIO_PROFILE_STANDARD,ot.AUDIO_PROFILE_STANDARD_STEREO,ot.AUDIO_PROFILE_HIGH,ot.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function lo(r,i){if(!r)throw new k({code:V.INVALID_OPERATION,extraCode:5101,fnName:i})}function ju(r,i,e){if(!r)throw new k({code:V.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}var bb={type:"number",notLessThanZero:!0},Pf={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 k({code:V.INVALID_OPERATION,extraCode:5104,fnName:e});if(r.roomId){if(z(r.roomId))throw new k({code:V.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});if(!(/^[1-9]\d*$/.test(String(r.roomId))&&r.roomId<4294967295))throw new k({code:V.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 k({code:V.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:i}})}else throw new k({code:V.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:qr,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:Hu},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.videoTrack)&&di())throw new k({code:V.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:P(N({},qr),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:Hu}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:Ju},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.audioTrack)&&di())throw new k({code:V.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:Ju}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:qr,publish:{type:"boolean"},option:Gu},validate(r,i,e,t,s){var o;if(!((o=r==null?void 0:r.option)!=null&&o.videoTrack)&&di())throw new k({code:V.ENV_NOT_SUPPORTED,extraCode:5201});if(!$s())throw new k({code:V.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:qr,publish:{type:"boolean"},option:Gu}},muteRemoteAudio:[Wu,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[Wu,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:qr,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){lo(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(ju(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new k({code:V.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:r}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:P(N({},qr),{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){lo(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(ju(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new k({code:V.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:r}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(r,i,e){if(r.userId!=="*"&&g(r.streamType))throw new k({code:V.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(r,i,e){lo(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(!Gs)throw new k({code:V.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new k({code:V.INVALID_OPERATION,fnName:e,extraCode:5108});if(r.byteLength>1e3)throw new k({code:V.INVALID_PARAMETER,extraCode:5018,fnName:e});if(r.byteLength===0)throw new k({code:V.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});lo(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(r,i,e){if(!r&&!this._room.isMainStreamPublished||r&&!this._room.isAuxStreamPublished)throw new k({code:V.INVALID_OPERATION,extraCode:5109,messageParams:{key:i},fnName:e})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(r,i,e,t){if(r.byteLength>1e3)throw new k({code:V.INVALID_PARAMETER,extraCode:5018,fnName:e});if(r.byteLength===0)throw new k({code:V.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(r,i,e){if(lo(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new k({code:V.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}}},Re={TRTC:Pf};var Pe=class extends Error{};function xf(r,i){let e=Dr(r);for(let t=0;t<i.length;t++)ni(e[t],i[t]);return e}function wf(r){this._resolve=Promise.resolve(r)}function Vf(r){this._reject=Promise.reject(r)}var ir=class{constructor(i,e){this.instance=i;this.group=e;this.started=!1;this.ops=[];this.startSame=()=>!0;this.mergeUpdate=xf;let t=ir.instances.get(i);t?t.set(e,this):ir.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=ir.instances.get(i);return t&&t.get(e)||new ir(i,e)}static gets(i,e){let t=ir.instances.get(i),s=[];return t&&t.forEach((o,n)=>{e.test(n)&&s.push(o)}),s}action(i,e,t){let s=a=>{var c;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),a},o=a=>{var c,d;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new Pe("start failed")),(d=this.currentOp)==null||d.action(),a},n={type:i,action:()=>e(...n.args).then(s,o),args:t,resolve:wf,reject:Vf};try{switch(this.state){case 1:if(i===0)throw new Pe("already started");break;case 4:if(i===2)throw new Pe("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(s,o)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new Pe("already start");break;case 3:switch(i.type){case 2:throw new Pe("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Pe("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new Pe("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 Pe("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Pe("start not allowed after update");case 0:throw new Pe("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new Pe("keep start")),new Pe("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}},Jt=ir;Jt.instances=new WeakMap;var Yn=new WeakMap,Kn=(r,i)=>{if(i instanceof Pe){let{stack:e}=i;i=new k({code:V.OPERATION_ABORT,message:`${r} abort: ${i.message}`,fnName:r}),e&&(i.stack+=e.substr(e.indexOf(`
63
63
  `)))}throw i};function Pi(r,i){return J((e,t)=>function(...s){let o=Jt.get(this,typeof r=="string"?r:r.call(this,...s));return o?(i&&(o.startSame=i.bind(this)),o.action(0,e.bind(this),s).catch(Kn.bind(null,t))):e.apply(this,s)})}function rr(r,i){let{merge:e,debounce:t}=i||{};return J((s,o)=>function(...n){let a=Jt.get(this,typeof r=="string"?r:r.call(this,...n));if(!a)return s.apply(this,n);if(e&&(a.mergeUpdate=e.bind(this)),t&&t.isNeedToDebounce.apply(this,n)){let{delay:c,getKey:d}=t;return new Promise((u,m)=>{var C,y;let p=(C=Yn.get(this))==null?void 0:C.get(d(...n));if(p){let{timeoutId:D,resolve:B}=p;clearTimeout(D),B()}let _=setTimeout(()=>{if(a.state===3||a.state===4)return u();a.action(2,s.bind(this),n).catch(Kn.bind(null,o)).then(u,m)},c);Yn.has(this)?(y=Yn.get(this))==null||y.set(d(...n),{timeoutId:_,resolve:u}):Yn.set(this,new Map([[d(...n),{timeoutId:_,resolve:u}]]))})}return a.action(2,s.bind(this),n).catch(Kn.bind(null,o))})}function xi(r){return J((i,e)=>function(...t){let s=typeof r=="function"?r.call(this,...t):r;if(s instanceof RegExp)return Promise.all(Jt.gets(this,s).map(n=>n.action(3,()=>Promise.resolve(),t))).then(()=>i.call(this,...t));let o=Jt.get(this,s);return o?o.action(3,i.bind(this),t).catch(Kn.bind(null,e)):i.apply(this,t)})}var M={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message"},qu=new Set([M.ERROR,M.AUTOPLAY_FAILED,M.KICKED_OUT,M.REMOTE_USER_ENTER,M.REMOTE_USER_EXIT,M.REMOTE_AUDIO_AVAILABLE,M.REMOTE_AUDIO_UNAVAILABLE,M.REMOTE_VIDEO_AVAILABLE,M.REMOTE_VIDEO_UNAVAILABLE,M.CONNECTION_STATE_CHANGED,M.PUBLISH_STATE_CHANGED,M.SCREEN_SHARE_STOPPED,M.DEVICE_CHANGED]);function uo(r){return r==="sub"?"auxiliary":r==="auxiliary"?"sub":"main"}function sr(r){return r===ot.QOS_PREFERENCE_CLEAR?"detail":r===ot.QOS_PREFERENCE_SMOOTH?"motion":""}var Uf=r=>r.startsWith("data:application/octet-stream;base64,"),Bf=r=>r.startsWith("file://"),Zn=class{constructor(){l(this,"_log");this._log=A.createLogger({id:"fd"})}download(i,e){return f(this,null,function*(){let{type:t="blob"}=e||{};try{let s=w(),o;if(te(fetch)?o=yield this.downloadWithFetch(i,t):o=yield this.downloadWithXHR(i,t),!o||!o.data)throw new Error("data is empty");let n=w()-s;return this._log.info(`downloaded: ${i}, return type: ${t}, cost: ${n}ms`),v.addSuccessEvent({key:522700,cost:w()-s}),o.data}catch(s){throw this._log.error(`failed to download: ${i}, error: ${s}`),v.addFailedEvent({key:522700,error:s}),s}})}downloadWithFetch(i,e){return f(this,null,function*(){this._log.info(`download with fetch: ${i}, return type: ${e}`);try{let t=yield fetch(i);if(!t.ok)throw new Error("network response was not ok");let s;return e==="arraybuffer"?s=yield t.arrayBuffer():s=yield t.blob(),{data:s}}catch(t){throw t}})}downloadWithXHR(i,e){return this._log.info(`download with xhr: ${i}, return type: ${e}`),new Promise((t,s)=>{let o=new XMLHttpRequest;o.open("GET",i,!0),o.responseType=e,o.onload=()=>{o.status===200||o.status===0&&o.response?t({data:o.response}):s(new Error("XHR failed"))},o.onerror=s,o.send(null)})}loadWasm(i,e){return f(this,null,function*(){this._log.info(`loadWasm ${i}, importObject: ${JSON.stringify(e)}`);let t=w(),s=null,o=null;if(te(WebAssembly.instantiateStreaming)&&!Uf(i)&&!Bf(i)&&te(fetch))try{let n=fetch(i);s=(yield WebAssembly.instantiateStreaming(n,e)).instance}catch(n){o=n}if(!s)try{let n=yield this.download(i,{type:"arraybuffer"});s=(yield WebAssembly.instantiate(n,e)).instance}catch(n){o=n}if(s){let n=w()-t;return this._log.info(`loadedWasm ${i}, cost: ${n}ms`),v.addSuccessEvent({key:522701,cost:n}),s}throw this._log.error(`failed to loadWasm ${i}, error: ${o}`),v.addFailedEvent({key:522701,error:o}),o})}};b([it({settings:{timeout:0,retries:3},onRetrying(r){this._log.warn(`download retrying: ${r}`)}})],Zn.prototype,"download",1);var Xu=new Zn;function Qu({TRTC:r,room:i,errorModule:e,assetsPath:t}){return{TRTC:r,room:i,assetsPath:t,fileDownloader:Xu,innerEmitter:T,constants:Pa,environment:br,utils:Ve,eventLogger:Y,log:this.room.getLogger(),loggerManager:A,errorModule:e,kvStatManager:v,rtcDectection:wt,trtc:this,clearStarted:(s,o)=>{let n=s.getAlias(),a=Jt.instances.get(this);if(!!a)if(o){let c=a.get(n+o);if(!c)return;c.started=!1}else a.forEach((c,d)=>{d.startsWith(n)&&(c.started=!1)})}}}var zu=(r,i)=>{let{emit:e}=r;return r.emit=(...t)=>{try{return e.apply(r,t)}catch(s){let o=x({key:L.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return A.warn(`${o}
64
64
 
65
- ${s.stack}`),!1}},r};var ea=new WeakMap;function Yu(r,i){return J((e,t)=>function(...s){var a,c;let o=(a=ea.get(this))==null?void 0:a.get(i(...s));o&&o>0&&clearTimeout(o);let n=window.setTimeout(()=>{e.apply(this,s)},r);ea.has(this)?(c=ea.get(this))==null||c.set(i(...s),n):ea.set(this,new Map([[i(...s),n]]))})}var Ku="5.8.4-beta.2";function xe(...r){return J((i,e)=>function(...t){try{ia.call(this,r,t,e,this._name)}catch(s){return Promise.reject(s)}return i.apply(this,t)})}function Cd(...r){return J((i,e)=>function(...t){try{ia.call(this,r,t,e,this._name)}catch(s){throw s}return i.apply(this,t)})}function ia(r,i,e,t){if(fe(r))for(let s=0;s<r.length;s++)ta.call(this,{rule:r[s],value:i[s],key:r[s].name,fnName:e,className:t});else ta.call(this,{rule:r,value:i[0],key:r.name,fnName:e,className:t})}function ta({rule:r,value:i,key:e,fnName:t,className:s}){function o(c){return{code:V.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:r,value:i}}}if(g(i)){if(r.required)throw new k(o(5001));if(g(r.defaultValue)){te(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),te(r.type[d])&&i instanceof r.type[d]&&(c=!0),z(r.type[d])&&ge(i)===r.type[d].toLowerCase()&&(c=!0);if(!c)throw new k({code:V.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:r.type.map(d=>Ps(d)?nn(d):z(d)?d:ge(d))},value:i}})}else if(!g(r.type)&&ge(i)!==r.type)throw new k(o(5002));if(r.allowEmpty===!1){let c=ee(i)&&(i===0||Number.isNaN(i)),d=z(i)&&i.trim()==="";if(c||d)throw new k(o(5003))}if(r.notLessThanZero&&ee(i)&&i<0)throw new k(o(5006));if(!g(r.min)&&ee(i)&&i<r.min)throw new k(o(5007));if(!g(r.max)&&ee(i)&&i>r.max)throw new k(o(5008));if(z(r.instanceOf)){if(!i||i._name!==r.instanceOf)throw new k(o(5004))}else if(te(r.instanceOf)&&!(i instanceof r.instanceOf))throw new k(o(5004));if(Array.isArray(r.values)&&!r.values.includes(i))throw new k(o(5005));let{properties:n}=r;Je(n)&&_t(i)&&Object.keys(n).forEach(c=>{ta.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:s})});let{arrayItem:a}=r;Je(a)&&fe(i)&&i.forEach((c,d)=>{ta.call(this,{rule:a,value:c,key:`${e}[${d}]`,fnName:t,className:s})}),te(r.validate)&&r.validate.call(this,i,e,t,s,this)}function ne(r={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t}=r;return J((s,o)=>function(...n){function a(u,m,p){if(p&&p.includes(u))return"hided";if(e){let _=e(...n);if(n[_.argIndex]===m)return _.value}if(m===n||u in n)return m;try{return m instanceof HTMLElement?`id: ${m.id} type:${ge(m)}`:(JSON.stringify(m),m)}catch(_){return`type:${ge(m)}`}}let c=this._log||A;n.length>0?c.info(`${o}() ${JSON.stringify(n,(u,m)=>a(u,m,["userSig","privateMapKey"]))}`):c.info(`${o}()`);let d=t?t(...n):hn[o];try{let u=s.apply(this,n),m=w();return Ls(u)?u.then(p=>(c.info(`${o}() success ${i.call(this,...n)}`),v.addSuccessEvent({key:d,cost:w()-m}),p)).catch(p=>{throw p=k.convertFrom.call(this,p,o,n.length===1?n[0]:n),c.error(`${o}() failed ${i.call(this,...n)} ${p} params: ${JSON.stringify(n,a)}`),v.addFailedEvent({key:d,error:p}),p}):(v.addSuccessEvent({key:d}),u)}catch(u){throw u=k.convertFrom.call(this,u,o),c.error(`${o}() failed ${u} params: ${JSON.stringify(n,a)}`),v.addFailedEvent({key:d,error:u}),u}})}var ra=r=>J((i,e)=>function(t,s){return f(this,null,function*(){let o=this._plugins.get(t);if(!o)throw this._log.error(`plugin ${String(t)} is not found`),new k({code:V.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(te(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new k({code:V.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return ia.call(this,o.getValidateRule(r),[s],e,"TRTC"),i.call(this,o,s)})});var sa=0,Rd=class{constructor(i,e){l(this,"player");l(this,"publisher");l(this,"mixInput");this.mixInput=new wr(e),i.url?(this.player=new Audio(i.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(i.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(i.track),this.mixInput.connect()}updateSettings(i){!this.player||(g(i.volume)||(this.volume=i.volume),g(i.loop)||(this.loop=i.loop),g(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(!!this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(i){!this.player||i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i)}play(){var i,e;return(i=this.publisher)==null||i.play(),(e=this.player)==null?void 0:e.play()}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function Xr(r,i){if(i&&typeof i!="function")throw new k({code:V.INVALID_PARAMETER,message:`start audioMixer plugin: param ${r} should be a function.`})}var Qr=class{constructor(i){this.core=i;l(this,"log");l(this,"mixedMusicMap",new Map);l(this,"cacheMusicMap",new Map);sa=sa+1,this.log=i.log.createChild({id:`${this.getAlias()}${sa}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${sa}`),this.core=i}getName(){return Qr.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return Qr.startValidateRule;case"update":return Qr.updateValidateRule;case"stop":return Qr.stopValidateRule}}start(i){return f(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 o=this.cacheMusicMap.get(t);o?i.url?o.reset():(o.mixInput.replaceSource(i.track),o.mixInput.connect()):(o=new Rd(i,e.audioManager),this.cacheMusicMap.set(t,o)),o.updateListener(i),o.updateSettings(i),yield o.play(),this.mixedMusicMap.set(t,o),this.log.info(`start mix audio track ${t} success.`),v.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return f(this,null,function*(){let{id:e,operation:t,seekFrom:s,playbackRate:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),g(t)||n.setOperation(t),g(s)||n.seek(s),this.kvUpload(i)})}stop(e){return f(this,arguments,function*({id:i}){var t;this.mixedMusicMap.has(i)&&(this.log.info(`remove music source, music id: ${i}`),(t=this.mixedMusicMap.get(i))==null||t.stop(),this.mixedMusicMap.delete(i)),i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:s,playbackRate:o,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:d,onEnded:u}=i;e&&v.addCount({key:502711}),t&&v.addCount({key:502703}),s&&v.addCount({key:502704}),o&&v.addCount({key:502705}),n&&v.addCount({key:502706}),a&&v.addCount({key:502707}),typeof c!="function"&&v.addCount({key:502709}),typeof u!="function"&&v.addCount({key:502710}),typeof d!="function"&&v.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>this.stop({id:e}))}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}},wi=Qr;l(wi,"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],o=["mp3","ogg","wav","flac"],n=s.split(".").pop(),a=o.indexOf(n)>=0,c=s.startsWith("blob"),d=s.startsWith("data");if(!(a||c||d))throw new k({code:V.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new k({code:V.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});Xr("onTimeUpdate",i.onTimeUpdate),Xr("onEnded",i.onEnded),Xr("onDurationChange",i.onDurationChange)}}),l(wi,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(i,e,t){Xr("onTimeUpdate",i.onTimeUpdate),Xr("onEnded",i.onEnded),Xr("onDurationChange",i.onDurationChange)}}),l(wi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),l(wi,"Name","AudioMixer");var Ff=r=>(r=Number(r),r>0&&r<14e8),oa=0,yd,zr=class{constructor(i){this.core=i;l(this,"log");l(this,"audioContext",qe("denoiser"));l(this,"workletNode");oa=oa+1,this.log=i.log.createChild({id:`${this.getAlias()}${oa}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${oa}`),i.assetsPath&&this.preload(`${i.assetsPath}/denoiser-wasm.js`)}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,s,o){if(!i.room.audioManager.hasAudioTrack)throw new k({code:V.INVALID_OPERATION,extraCode:5106,fnName:s})}}}preload(i){return yd||(yd=this.doPreload(i)),yd}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield zi(this.audioContext,t)}finally{URL.revokeObjectURL(t)}})}getName(){return zr.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return zr.startValidateRule(this.core);case"update":return zr.updateValidateRule;case"stop":return zr.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;if(yield this.preload(`${i.assetsPath}/denoiser-wasm.js`),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:s,sign:o,status:n,message:a}=yield Gf(P(N({},i),{timestamp:t}));if(!s)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${s}. Message: ${a}`),new k({code:V.INVALID_PARAMETER,message:a});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:t,sign:o,status:n}}),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 f(this,null,function*(){})}stop(){return f(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(){}},or=zr;l(or,"updateValidateRule",{type:"object"}),l(or,"stopValidateRule",{type:"object"}),l(or,"Name","AIDenoiser");var Zu={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};function Hf(r){let i;return Ff(r)?i=Zu.MAIN_OVERSEA:i=Zu.MAIN,i}function Gf(s){return f(this,arguments,function*({sdkAppId:r,userId:i,userSig:e,timestamp:t}){let n=`https://${Hf(r)}/api/v1/audioAiAuth?sdkAppId=${r}&userId=${i}&userSig=${e}&timestamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:d,sign:u,status:m}}=yield a.json();if(m==="1")return{auth:!0,sign:u,status:m,message:d};let p="Init RTCAIDenoiser failed.",_="";switch(c){case 1:_="Please check your params.";break;case 2:_="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:_="Server is invalid. Please contact our engineer. ";break;case 4:_="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:_="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:_="Your version is not supported.";break}return{auth:!1,status:m,message:d?`${p} Reason: ${d}. ${_}`:`${p}, ${_}`}})}var eh=Ie(Oe(),1);var bd=class extends eh.EventEmitter{constructor(){super();this.state="nominal";this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return f(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!pe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){Y.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,s=e[e.length-1];this.state=s.state,(this.stateNum>3||t>3)&&A.info(`${s.source}: ${s.state}`),this.emit("state-changed",{type:s.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){Y.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},Wf=new bd,Nd=Wf;function vd([r,i]){let e=i.byteLength,t=parseInt(String(e/255),10),s=e%255,o=[];o.push(0,0,0,1,6,r);for(let a=0;a<t;a++)o.push(255);o.push(s);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new hi(new DataView(new Uint8Array(o).buffer),!0)}function Dd(r){return r.type==="empty"||r.data.byteLength===0}function Od(r){return r.getInt32(0)===1&&r.getInt8(4)===6}function Md(r){let i=0,e=0,t=new DataView(r);for(let s=0;s<r.byteLength;s++)switch(t.getUint8(s)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function kd({frame:r,seiMessageList:i}){if(!i||i.length===0||r.data.byteLength===0)return r;let e=Md(r.data),t=9-e;if(t<=0)return r;let s=i.splice(0,t).reverse().map(vd),o=s.reduce((u,m)=>u+m.dataView.byteLength,0),n=new ArrayBuffer(o+r.data.byteLength),a=new DataView(n),c=new DataView(r.data),d=0;for(let u=0;u<s.length;u++)for(let m=0;m<s[u].dataView.byteLength;m++)a.setInt8(d++,s[u].dataView.getInt8(m));for(let u=0;u<r.data.byteLength;u++)a.setInt8(d++,c.getInt8(u));return r.data=n,r}function Ld({frame:r,onSEI:i}){try{let e=new DataView(r.data);if(Dd(r)||!Od(e))return r;let t=[],s=0,o=-1,n=-1;for(let a=0;a<r.data.byteLength;a++){let c=e.getUint8(a);if(c===0)s++;else if(c===1){if(s===2||s===3){let d=a-s;if(o===-1?o=d:n===-1&&(n=d,t.push(new hi(new DataView(e.buffer.slice(o,n)))),o=d,n=-1),!(e.getUint8(a+1)===6)){r.data=e.buffer.slice(d);break}}s=0}else s=0}i==null||i(t.reverse())}catch(e){}return r}var Pd=0,xd=class{constructor(i){this.core=i;l(this,"log");l(this,"_seiMessageList",[]);l(this,"_smallSeiMessageList",[]);l(this,"_subStreamSeiMessageList",[]);Pd++,this.log=i.log.createChild({id:`${this.getAlias()}${Pd}`}),this.log.info(`[sei] created id=${this.getAlias()}${Pd}`),this.core=i,this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode({frame:i,mediaType:e}){try{let t=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList;return kd({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return Ld({frame:i,onSEI:t=>{t.forEach(s=>{this.core.trtc.emit(M.SEI_MESSAGE,{seiPayloadType:s.seiPayloadType,data:s.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:Tt?this.encode:kd,type:1}),this.core.room.videoManager.addDecodeProcessor({processor:Tt?this.decode:Ld,type:1})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:1}),this.core.room.videoManager.removeDecodeProcessor({type:1})}update({buffer:i,options:e}){var o;let t=[e.seiPayloadType,i],s=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),s&&this._smallSeiMessageList.push(t)),(o=this.core.room.scriptTransformWorker)==null||o.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:s})}getName(){return xd.Name}getAlias(){return"sei"}getGroup(){return"sei"}},Yr=xd;l(Yr,"autoStart",!0),l(Yr,"Name","SEI");var th=0,na=new Set,Ne=null;Aa(Ku);var Jf={RtcError:k,ErrorCode:V,ErrorCodeDictionary:Ct},jt=class extends ih.EventEmitter{constructor(e,t){super();l(this,"_room");l(this,"_eventListened",new Set);l(this,"_localVideoTrack",null);l(this,"_localAudioTrack",null);l(this,"_localScreenTrack",null);l(this,"_localScreenAudioTrack",null);l(this,"_localVideoConfig",null);l(this,"_localScreenConfig",null);l(this,"_localAudioConfig",null);l(this,"_remoteVideoConfigMap",new Map);l(this,"_remoteAudioConfigMap",new Map);l(this,"_remoteAudioMuteMap",new Map);l(this,"_mediaTrackMap",new WeakMap);l(this,"_log",A.createLogger({id:`t${++th}`}));l(this,"_plugins",new Map);l(this,"_networkQuality",null);l(this,"_speakerId");l(this,"_getPCMAbortCtrl");this._room=new e(N({logger:this._log,frameWorkType:jt.frameWorkType},t)),this._log.debug(`TRTC.create() ${JSON.stringify(t,(s,o)=>s==="plugins"?o.map(n=>n.Name):o)}`),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(wi,t.assetsPath),this._use(or,t.assetsPath),t.enableSEI&&Gs&&this._use(Yr),this._room.on("audio-volume",s=>{!s.find(o=>o.userId==="")&&this._localAudioTrack&&s.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),this.emit(M.AUDIO_VOLUME,{result:s.sort((o,n)=>n.volume-o.volume)})}),this._room.videoManager.on("error",s=>{this._log.error(new k({code:V.OPERATION_FAILED,extraCode:5504,message:s.message,originError:s}))}),this._listenEvents(),this._initActiveSpeaker(),zu(this,"trtc")}static create(e){}static _create(e,t){Bu();let s=new jt(e,t||{});return na.add(s),s}get room(){return this._room}_listenEvents(){ke(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(M.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit(M.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{this._exitRoom().then(()=>{this.emit(M.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().then(()=>{this.emit(M.ERROR,k.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(M.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let t=P(N({},e),{uplinkRTT:Math.min(e.uplinkRTT,fs),downlinkRTT:Math.min(e.downlinkRTT,fs)});this.emit(M.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{ke(s,s).add("player-state-changed",o=>{let n=P(N({},o),{userId:e.userId});s.kind===h.VIDEO&&(n.streamType=uo(s.streamType)),this.emit(s.kind===h.AUDIO?M.AUDIO_PLAY_STATE_CHANGED:M.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",o=>{o.getCode()===S.PLAY_NOT_ALLOWED&&this.emit(M.AUTOPLAY_FAILED,{userId:s.userId})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{_e(s)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:s}=t,o=e.audioAvailable,n=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"}`),o!==a&&(this.emit(a?M.REMOTE_AUDIO_AVAILABLE:M.REMOTE_AUDIO_UNAVAILABLE,{userId:s}),a?this._onAudioAvailable({userId:s}):this._onAudioUnavailable({userId:s,muteState:t})),n!==c&&(this.emit(c?M.REMOTE_VIDEO_AVAILABLE:M.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?M.REMOTE_VIDEO_AVAILABLE:M.REMOTE_VIDEO_UNAVAILABLE,{userId:s,streamType:"sub"}),t.hasAuxiliary?this._onVideoAvailable({userId:s,streamType:"sub"}):this._onVideoUnavailable({userId:s,streamType:"sub"}))}).add("sei-message",e=>{this.emit(M.SEI_MESSAGE,P(N({},e),{streamType:uo(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(M.ERROR,new k({code:V.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var o,n,a,c,d,u,m;let t={2:"big",3:"small",7:"sub"},s={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((o=e.msg_down_stream_info[0])==null?void 0:o.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,fs),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:(((u=e.msg_up_stream_info.msg_audio_status)==null?void 0:u.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((m=e.msg_up_stream_info.msg_audio_status)==null?void 0:m.uint32_audio_level)||0)/dt},video:e.msg_up_stream_info.msg_video_status.filter(p=>t[p.uint32_video_stream_type]).map(p=>({bitrate:(p.uint32_video_codec_bitrate||0)/1e3,width:p.uint32_video_width,height:p.uint32_video_height,frameRate:p.uint32_video_enc_fps,videoType:t[p.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(p=>({userId:p.msg_user_info.str_identifier,audio:{bitrate:(p.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(p.msg_audio_status.uint32_audio_level||0)/dt},video:p.msg_video_status.map(_=>({bitrate:(_.uint32_video_codec_bitrate||0)/1e3,width:_.uint32_video_width,height:_.uint32_video_height,frameRate:_.uint32_video_dec_fps,videoType:t[_.uint32_video_stream_type]}))}))};this.emit(M.STATISTICS,s)}).add("custom-message",e=>{this.emit(M.CUSTOM_MESSAGE,e)}),ke(this,Se).add("audioInputAdded",e=>{this.emit(M.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(M.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(M.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(M.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>f(this,null,function*(){if(this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Ne&&Ne.deviceId===ps){let t=(yield Mi()).find(s=>s.deviceId===ps);t&&Ne.groupId!==t.groupId&&(Ne=t,this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>f(this,null,function*(){this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield Mi())[0];t&&Ne&&(Ne.deviceId===e.deviceId||Ne.deviceId===ps&&Ne.groupId!==t.groupId)&&(Ne=t,this.emit(M.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 o=new e(Qu.call(this,{TRTC:jt,room:this._room,errorModule:Jf,assetsPath:t}));this._plugins.set(e.Name,o),e.autoStart&&(this.startPlugin(e.Name),this._log.info("auto start plugin",e.Name))}enterRoom(e){return f(this,null,function*(){var c,d;let{scene:t="rtc",enableAutoPlayDialog:s=!0,autoReceiveAudio:o=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!z(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=o,this._room.autoReceiveVideo=n,le(e.preferHW)&&(this._room.preferHW=e.preferHW);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,jt.frameWorkType),this._checkTrackToPublish(),Nd.start()})}exitRoom(){return f(this,null,function*(){return yield this._exitRoom()})}switchRole(e,t){return f(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),t!=null&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){_e(this),this.removeAllListeners(),this._room.destroy(),na.delete(this),na.size===0&&Nd.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)})}startLocalAudio(){return f(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:o}=e,n=new Le(this._room.audioManager),a={},c={muted:!0};o&&(g(o.microphoneId)?g(o.audioTrack)||(a.customSource=o.audioTrack):a.deviceId=o.microphoneId,o&&ee(o.captureVolume)&&n.setCaptureVolume(o.captureVolume),g(o.profile)||(z(o.profile)?Po[o.profile]&&n.setProfile(Po[o.profile]):n.setProfile(o.profile)),ee(o.earMonitorVolume)&&(c.muted=!(o.earMonitorVolume>0),c.volume=o.earMonitorVolume),g(o.echoCancellation)||(n.profile.echoCancellation=o.echoCancellation),g(o.noiseSuppression)||(n.profile.noiseSuppression=o.noiseSuppression),g(o.autoGainControl)||(n.profile.autoGainControl=o.autoGainControl)),n.on("5",d=>{this.emit(M.ERROR,new k({code:V.DEVICE_ERROR,extraCode:5309,messageParams:{error:d}}))}),n.on("2",d=>{this.emit(M.DEVICE_CHANGED,{type:"microphone",action:"active",device:d})}),n.on("4",d=>{let u;d.error&&(u=k.convertFrom(d.error)),this.emit(M.PUBLISH_STATE_CHANGED,P(N({},d),{error:u}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),g(s)||n.setMute(s),ke(n,n).add("player-state-changed",d=>{this.emit(M.AUDIO_PLAY_STATE_CHANGED,P(N({},d),{userId:""}))}),this.listeners(M.AUDIO_FRAME).length>0&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(d=>{this.emit(jt.EVENT.AUDIO_FRAME,{data:d})})),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=P(N({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:n})})}updateLocalAudio(e){return f(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:s,option:o}=e,n={};o&&(o.microphoneId?yield this._localAudioTrack.switchDevice(o.microphoneId):g(o.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(o.audioTrack)),g(o.captureVolume)||this._localAudioTrack.setCaptureVolume(o.captureVolume),g(o.earMonitorVolume)||(n.muted=!(o.earMonitorVolume>0),n.volume=o.earMonitorVolume),yield this._localAudioTrack.update3A(o)),this._room.isJoined&&!g(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),g(s)||this._localAudioTrack.setMute(s),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),ni(this._localAudioConfig,e)})}stopLocalAudio(){return f(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),_e(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("stopLocalAudio"),delete this._getPCMAbortCtrl))})}startLocalVideo(){return f(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:o,option:n}=e,a=new he(this._room.videoManager),c={},d={};if(n&&(n.cameraId?c.deviceId=n.cameraId:g(n.useFrontCamera)?g(n.videoTrack)||(c.customSource=n.videoTrack):c.facingMode=n.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT,g(n.profile)||(z(n.profile)?Ze[n.profile]&&a.setProfile(Ze[n.profile]):a.setProfile(n.profile)),g(n.fillMode)||(d.objectFit=n.fillMode),g(n.mirror)||(d.mirror=n.mirror),g(n.small)||(Fs()?z(n.small)?a.small=Ze[n.small]:n.small===!0?a.small=Ze["120p"]:a.small=n.small:this._log.warn("small stream is not supported"))),a.on("5",u=>{this.emit(M.ERROR,new k({code:V.DEVICE_ERROR,extraCode:5308,messageParams:{error:u}}))}),a.on("2",u=>{this.emit(M.DEVICE_CHANGED,{type:"camera",action:"active",device:u})}),a.on("4",u=>{let m;u.error&&(m=k.convertFrom(u.error)),this.emit(M.PUBLISH_STATE_CHANGED,P(N({},u),{error:m}))}),this._listenOutputTrackChanged(a),yield a.capture(c),g(o)||(yield a.setMute(o)),a.mediaTrack){if(n!=null&&n.qosPreference){let u=sr(n.qosPreference);a.mediaTrack.contentHint=u}else n!=null&&n.videoTrack||(a.mediaTrack.contentHint=sr(ot.QOS_PREFERENCE_SMOOTH));a.outMediaTrack&&(a.outMediaTrack.contentHint=a.mediaTrack.contentHint)}ke(a,a).add("player-state-changed",u=>{this.emit(M.VIDEO_PLAY_STATE_CHANGED,P(N({},u),{userId:"",streamType:"main"}))}),s&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localVideoTrack=a,this._localVideoConfig=P(N({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:a})})}updateLocalVideo(e){return f(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:s,mute:o,option:n}=e,a={};if(n){if(g(n.profile)||(z(n.profile)?Ze[n.profile]&&this._localVideoTrack.setProfile(Ze[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&g(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):g(n.useFrontCamera)?g(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT),g(n.fillMode)||(a.objectFit=n.fillMode),g(n.mirror)||(a.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack){let c=sr(n.qosPreference);this._localVideoTrack.mediaTrack.contentHint=c,this._localVideoTrack.outMediaTrack&&(this._localVideoTrack.outMediaTrack.contentHint=c)}if(n.small){let c=!this._localVideoTrack.small;Fs()?(n.small===!0?this._localVideoTrack.small=Ze["120p"]:z(n.small)?this._localVideoTrack.small=Ze[n.small]:this._localVideoTrack.small=n.small,this._room.videoManager.update(),c&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else n.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1))}this._room.isJoined&&!g(s)&&(s&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!s&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),g(o)||(yield this._localVideoTrack.setMute(o)),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),ni(this._localVideoConfig,e)})}stopLocalVideo(){return f(this,null,function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),_e(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return f(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:o}=e,n=new ze(this._room.videoManager);n.on("4",m=>{let p;m.error&&(p=k.convertFrom(m.error)),this.emit(M.PUBLISH_STATE_CHANGED,P(N({},m),{error:p}))}),this._listenOutputTrackChanged(n);let a=null,c={},d={};o&&(g(o.profile)||(z(o.profile)?xo[o.profile]&&n.setProfile(xo[o.profile]):n.setProfile(o.profile)),o.systemAudio&&(c.systemAudio=!0,c.echoCancellation=o.echoCancellation,c.noiseSuppression=o.noiseSuppression,c.autoGainControl=o.autoGainControl),g(o.fillMode)||(d.objectFit=o.fillMode),o.videoTrack&&(c.videoTrack=o.videoTrack),o.audioTrack&&(c.audioTrack=o.audioTrack),o.captureElement&&(c.captureElement=o.captureElement),o.preferDisplaySurface&&(c.preferDisplaySurface=o.preferDisplaySurface));let u=yield n.capture(c);if(o!=null&&o.qosPreference){let m=sr(o.qosPreference);n.mediaTrack.contentHint=m}else o!=null&&o.videoTrack||(n.mediaTrack.contentHint=sr(ot.QOS_PREFERENCE_CLEAR));if(n.mediaTrack.addEventListener(h.ENDED,()=>{this._stopScreenShare(),this.emit(M.SCREEN_SHARE_STOPPED)}),u.getAudioTracks()[0]&&(a=new Gt(this._room.audioManager),a.setInputMediaStreamTrack(u.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),ke(n,n).add("player-state-changed",m=>{this.emit(M.VIDEO_PLAY_STATE_CHANGED,P(N({},m),{userId:"",streamType:"sub"}))}),s&&this._room.isJoined){let m=[n];a&&m.push(a),this._room.publish(...m).catch(()=>{})}this._localScreenTrack=n,this._localScreenAudioTrack=a,this._localScreenConfig=P(N({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:n})})}updateScreenShare(e){return f(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:s,option:o}=e,n={};if(o&&(g(o.fillMode)||(n.objectFit=o.fillMode),o.qosPreference)){let a=sr(o.qosPreference);this._localScreenTrack.mediaTrack.contentHint=a}this._room.isJoined&&!g(s)&&(s&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!s&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:t,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),ni(this._localScreenConfig,e)})}stopScreenShare(){return f(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return f(this,null,function*(){let{view:t,userId:s,streamType:o,option:n}=e,a=`${s}_${o}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${s}, streamType:${o}`);return}let c=this._room.remotePublishedUserMap.get(s);if(!c)return;let d={},u=o==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;this._listenOutputTrackChanged(u),n&&(g(n.fillMode)||(d.objectFit=n.fillMode),g(n.mirror)||(d.mirror=n.mirror),d.canvasRender=n.canvasRender,o==="main"&&!g(n.small)&&(c.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,u.user))),yield this._room.subscribe(u),yield this._updateVideoPlayOption({view:t,playOption:d,track:u}),this._emitTrackEvent(u),this._remoteVideoConfigMap.set(a,{config:e}),n&&!g(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:u,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return f(this,null,function*(){var D,B;let{view:t,userId:s,streamType:o,option:n}=e,a=`${s}_${o}`,c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(s))return;let d={};n&&(g(n.fillMode)||(d.objectFit=n.fillMode),g(n.mirror)||(d.mirror=n.mirror));let u=null,m=this._room.remotePublishedUserMap.get(s);if(o==="main"&&(m==null?void 0:m.muteState.hasVideo)&&(u=m.remoteVideoTrack),o==="sub"&&(m==null?void 0:m.muteState.hasAuxiliary)&&(u=m.remoteAuxiliaryTrack),!u)return;let{config:p}=c;o==="main"&&n&&!g(n.small)&&this._room.changeType(n.small,u.user),yield this._updateVideoPlayOption({view:t,playOption:d,track:u,prevConfig:p}),ni(p,e);let _=g(n==null?void 0:n.receiveWhenViewVisible)?(D=p.option)==null?void 0:D.receiveWhenViewVisible:n.receiveWhenViewVisible,C=g(t)?p.view:t,y=g(n==null?void 0:n.viewRoot)?(B=p.option)==null?void 0:B.viewRoot:n.viewRoot;this._observeView({remoteTrack:u,view:C,receiveWhenViewVisible:_,viewRoot:y})})}stopRemoteVideo(e){return f(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return f(this,null,function*(){let s=[],o=this._room.remotePublishedUserMap.get(e.userId);if(o){let{muteState:a,remoteVideoTrack:c,remoteAuxiliaryTrack:d}=o;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 n=this._remoteVideoConfigMap.get(`${e.userId}_${e.streamType}`);n&&n.observer&&n.observer.disconnect(),this._remoteVideoConfigMap.delete(`${e.userId}_${e.streamType}`)})}muteRemoteAudio(e,t){return f(this,null,function*(){if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let s=[...this._room.remotePublishedUserMap.values()];for(let o of s)o.muteState.hasAudio&&!this._remoteAudioConfigMap.has(o.userId)&&(yield this._startRemoteAudio({userId:o.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 o of s)this._updateAudioPlayOption({playOption:{volume:t},track:o.remoteAudioTrack})}else if(e){let s=this._room.remotePublishedUserMap.get(e);s&&this._updateAudioPlayOption({playOption:{volume:t},track:s.remoteAudioTrack})}}startPlugin(e,t){return f(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return f(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return f(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,s){return this.listeners(e).includes(t)?this:(this._log.debug("on",e),super.on(e,t,s),this._eventListened.add(e),e===jt.EVENT.AUDIO_FRAME&&!this._getPCMAbortCtrl&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(o=>{this.emit(jt.EVENT.AUDIO_FRAME,{data:o})})),this)}emit(e,...t){try{qu.has(e)&&this._log.debug(`emit ${e} ${JSON.stringify(t)}`)}catch(s){}return super.emit(e,...t)}off(e,t,s){var o,n;return this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners(),(o=this._getPCMAbortCtrl)==null||o.abort("off"),delete this._getPCMAbortCtrl):(super.off(e,t,s),e===jt.EVENT.AUDIO_FRAME&&((n=this._getPCMAbortCtrl)==null||n.abort("off"),delete this._getPCMAbortCtrl)),this}getAudioTrack(e={userId:"",streamType:"main"}){let t,s=null,o="main",n=!1;if(z(e)?t=e:(t=e.userId,n=e.processed===!0,e.streamType&&(o=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);a&&(s=a.remoteAudioTrack)}else s=o==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return s?n&&s.outMediaTrack&&s.outMediaTrack!==s.mediaTrack?s.outMediaTrack.clone():s.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:s="main",processed:o=!1}=e,n=null;if(t==="")s==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),s==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(t);a&&(n=s==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?o&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:t,streamType:s="main"}=e;if(t){let o=this._room.remotePublishedUserMap.get(t);if(s==="main"&&(o==null?void 0:o.muteState.hasVideo))return o.remoteVideoTrack.getVideoFrame();if(s==="sub"&&(o==null?void 0:o.muteState.hasAuxiliary))return o.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(o=>o.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return f(this,null,function*(){(yield Mi()).forEach(s=>{s.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:s}),Ne=s)}),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return f(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 o=this._room.remotePublishedUserMap.get(t);if(!o)return;let n={};s&&(g(s.volume)||(n.volume=s.volume));let a=o.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:n,track:a})}catch(c){throw this._remoteAudioConfigMap.delete(t),c}this._emitTrackEvent(a)})}_stopRemoteAudio(e,t=!0){return f(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(n){return f(this,arguments,function*({view:e,playOption:t,track:s,prevConfig:o}){if(s.setMirror(t.mirror),g(e)&&o&&o.view&&!Za(t)){let a=ws(o.view);a.length>0&&(yield s.play(a,t))}if(!g(e)){let a=ws(e);a.length>0?yield s.play(a,t):s.stop()}})}_updateAudioPlayOption(o){return f(this,arguments,function*({playOption:e={},track:t,prevConfig:s}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}g(e.muted)||t.setPlayerMute(e.muted),g(e.volume)||t.setAudioVolume(e.volume/100)})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,t=!0){let s=e.isRemote?e.userId:"";!e.outMediaTrack||t&&this._mediaTrackMap.get(e.outMediaTrack)===s||(this._mediaTrackMap.set(e.outMediaTrack,s),this.emit(M.TRACK,{userId:s,streamType:uo(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var t,s,o;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),(o=this._localScreenConfig)!=null&&o.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:o}){if(g(t))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${uo(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||fe(t)&&t.length===0||!s){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let d=n.visibleViewMap||new Map,u=-1;(!a||a.root!==o)&&(a==null||a.disconnect(),d.clear(),a=new IntersectionObserver(p=>{p.forEach(_=>{d.set(_.target,_.isIntersecting)}),clearTimeout(u),u=window.setTimeout(()=>{[...d.values()].find(C=>C)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:o}));let m=new Set(ws(t));d.forEach((p,_)=>{m.has(_)||(a.unobserve(_),d.delete(_))}),m.forEach(p=>{d.set(p,!0),a.observe(p)}),a.takeRecords().forEach(p=>{d.set(p.target,p.isIntersecting)}),n.visibleViewMap=d,n.observer=a}_exitRoom(){return f(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=>{_e(e.remoteAudioTrack),_e(e.remoteVideoTrack),_e(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return f(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),_e(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_initActiveSpeaker(){return f(this,null,function*(){if(Ne&&!Vr(Ne))this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:Ne});else{let e=yield Mi();if(e[0]&&!Vr(e[0]))Ne=e[0],this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let t=({track:s})=>{s.kind==="audio"&&(!Ne||Vr(Ne))&&(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 o=t==="main"?s.remoteVideoTrack:s.remoteAuxiliaryTrack;this._room.subscribe(o).then(()=>{this._emitTrackEvent(o)}).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){var o;let s=this._plugins.get("SEI");s&&(s.update({buffer:e,options:P(N({seiPayloadType:243},t),{small:!!((o=this._localVideoTrack)!=null&&o.small)})}),v.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,s;(s=(t=this._room).sendCustomMessage)==null||s.call(t,e),v.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){A.setLogLevel(e),g(t)||(t?A.enableUploadLog():A.disableUploadLog())}static isSupported(){return _n()}static getCameraList(e=!0){return Xe(e)}static getMicrophoneList(e=!0){return Fe(e)}static getSpeakerList(e=!0){return Mi(e)}static setCurrentSpeaker(e){return f(this,null,function*(){(yield Mi()).forEach(s=>{s.deviceId===e&&(na.forEach(o=>{o._setCurrentSpeaker(e),o.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:s})}),Ne=s)})})}static _addKVStat({type:e,key:t,value:s,base:o,useUV:n,version:a}){switch(a&&(qi.version=a),e){case"count":qi.addCount({key:t,useUV:n});break;case"enum":qi.addEnum({key:t,value:s,useUV:n});break;case"number":qi.addNumber({key:t,value:s,split:o});break}}},X=jt;l(X,"_loggerManager",A),l(X,"EVENT",M),l(X,"ERROR_CODE",V),l(X,"TYPE",ot),l(X,"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"}})})],X.prototype,"use",1),b([xe(Re.TRTC.enterRoom),Pi("room",([r],[i])=>(r.roomId||r.strRoomId)===(i.roomId||i.strRoomId)&&r.userId===i.userId&&r.sdkAppId===i.sdkAppId),J(r=>function(i){return this._log.setUserId(i.userId),this._log.setSdkAppId(i.sdkAppId),r.call(this,i)}),ne()],X.prototype,"enterRoom",1),b([ne()],X.prototype,"exitRoom",1),b([xe(Re.TRTC.switchRole),rr("room",{merge:(r,i)=>i}),ne()],X.prototype,"switchRole",1),b([ne()],X.prototype,"destroy",1),b([xe(Re.TRTC.startLocalAudio),Pi("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()],X.prototype,"startLocalAudio",1),b([xe(Re.TRTC.updateLocalAudio),rr("audio",{debounce:{delay:200,getKey:()=>`${th}-localAudio`,isNeedToDebounce:r=>{var i;return!g((i=r.option)==null?void 0:i.captureVolume)}}}),ne()],X.prototype,"updateLocalAudio",1),b([xi("audio"),ne()],X.prototype,"stopLocalAudio",1),b([xe(Re.TRTC.startLocalVideo),Pi("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()],X.prototype,"startLocalVideo",1),b([xe(Re.TRTC.updateLocalVideo),rr("video"),ne()],X.prototype,"updateLocalVideo",1),b([xi("video"),ne()],X.prototype,"stopLocalVideo",1),b([xe(Re.TRTC.startScreenShare),Pi("screen",()=>!0),ne()],X.prototype,"startScreenShare",1),b([xe(Re.TRTC.updateScreenShare),rr("screen"),ne()],X.prototype,"updateScreenShare",1),b([ne()],X.prototype,"stopScreenShare",1),b([xe(Re.TRTC.startRemoteVideo),Pi(r=>`v${r.userId}${r.streamType}`,()=>!0),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],X.prototype,"startRemoteVideo",1),b([xe(Re.TRTC.updateRemoteVideo),rr(r=>`v${r.userId}${r.streamType}`),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],X.prototype,"updateRemoteVideo",1),b([xe(Re.TRTC.stopRemoteVideo),J(r=>function(i){return f(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}`})],X.prototype,"stopRemoteVideo",1),b([xi(r=>`v${r.userId}${r.streamType}`)],X.prototype,"_stopRemoteVideo",1),b([xe(...Re.TRTC.muteRemoteAudio),ne({getRemoteId:r=>r})],X.prototype,"muteRemoteAudio",1),b([Cd(...Re.TRTC.setRemoteAudioVolume),Yu(200,r=>r),ne({getRemoteId:r=>r})],X.prototype,"setRemoteAudioVolume",1),b([ra("start"),It(r=>{var i;return(i=r.afterStart)==null?void 0:i.call(r)}),Pi((r,i)=>r.disableRandomCall?null:r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>dc[r.getName()]})],X.prototype,"startPlugin",1),b([ra("update"),rr((r,i)=>r.disableRandomCall?null:r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>lc[r.getName()]})],X.prototype,"updatePlugin",1),b([ra("stop"),xi((r,i)=>{if(r.disableRandomCall)return null;let e=r.getGroup(i),t=r.getAlias();return e==="*"?new RegExp(`${t}.*`):t+e}),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>uc[r.getName()]})],X.prototype,"stopPlugin",1),b([Cd(...Re.TRTC.enableAudioVolumeEvaluation)],X.prototype,"enableAudioVolumeEvaluation",1),b([ne()],X.prototype,"getVideoSnapshot",1),b([ne()],X.prototype,"_setCurrentSpeaker",1),b([Pi(r=>`a${r.userId}`,()=>!0)],X.prototype,"_startRemoteAudio",1),b([J(r=>function(i){return f(this,null,function*(){return i.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(e=>this._stopRemoteAudio(P(N({},i),{userId:e.userId})).catch(()=>{}))):r.call(this,i)})}),xi(r=>`a${r.userId}`)],X.prototype,"_stopRemoteAudio",1),b([xi("room")],X.prototype,"_exitRoom",1),b([xi("screen")],X.prototype,"_stopScreenShare",1),b([xe(...Re.TRTC.sendSEIMessage),Sd({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...r)=>r[0].byteLength})],X.prototype,"sendSEIMessage",1),b([xe(Re.TRTC.sendCustomMessage),Sd({timesInSecond:30,maxSizeInSecond:8e3,getSize:r=>r.data.byteLength})],X.prototype,"sendCustomMessage",1),b([xe(Re.TRTC.create)],X,"_create",1);var ho=X;var wd=class{constructor(){this._set=new Set;T.on(E.LEAVE_SUCCESS,this.delete,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,s){return`${t}_${e}_${i}_${s}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:s}){return s.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,s.useStringRoomId))}};function jf(){return f(this,null,function*(){let r,i;try{let m=yield Fe();r=m&&m.length}catch(m){}try{let m=yield Xe();i=m&&m.length}catch(m){}let e={microphone:r,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:s,isH264DecodeSupported:o,isVp8DecodeSupported:n}=this.checkSystemResult.detail,a=wt.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:t,h264Decode:o,vp8Encode:s,vp8Decode:n},d={browser:a.browser,os:a.os,trtc:c,devices:e},u={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};Y.uploadEvent({log:`trtcstats-${JSON.stringify(d)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(d)}`),Y.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(u)}`,userId:this.userId})})}function rh(){return J(r=>{let i=new wd;return function(e,t,s){return f(this,null,function*(){let o=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 R({code:S.INVALID_OPERATION,message:x({key:L.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new R({code:S.INVALID_OPERATION,message:x({key:L.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:o}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${o} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),T.emit(E.JOIN_START,{room:this,roomId:o,params:e});let n=Ve.getEnv();n||(n=zt.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(wo.OLD_CLOUD_LADDER)?n=zt.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(wo.WEBRTC)&&(n=zt.WEBRTC))),Y.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),wt.checkSystemRequirementsInternal().then(a=>{this.checkSystemResult=a,jf.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Ve.getEnv()&&(yield this.schedule(e,s));let a=yield r.call(this,e,t,s);return this.roomId=o,this._joinedTimestamp=Ve.performanceNow(),T.emit(E.JOIN_SUCCESS,{room:this}),s===30&&!e.component&&Y.uploadEvent({log:`stat-conv-${Number(ti)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw i.delete({room:this,roomId:o}),T.emit(E.JOIN_FAILED,{room:this,error:a}),a}})}})}var sh=()=>J(r=>function(...i){return f(this,null,function*(){T.emit(E.LEAVE_START,{room:this}),yield r.call(this),T.emit(E.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function oh(){return J(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var ah=Ie(Oe());var me={SETUP_SUCCESS:"1",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4",SETUP_FAILED:"5",DISCONNECTED:"6"};var qt={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},nh=[qt.UPDATE_REMOTE_MUTE_STAT,qt.UPLINK_NETWORK_STATS,qt.USER_LIST_RES,qt.MUTE_RESULT,qt.SERVER_FIRST_PACKAGE_RECEIVED],U={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 aa=new Set;function ch(r){let i=[...aa.values()].find(e=>e.room.userId===r&&!e.room.isJoined);return i||null}var Kr=class extends ah.default{constructor(e){var s,o;super();l(this,"room");l(this,"url");l(this,"backupUrl");l(this,"race");l(this,"destroyed",!1);l(this,"_socketInUse");l(this,"_socket");l(this,"_backupSocket");l(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0});l(this,"_currentState","DISCONNECTED");l(this,"_isReconnecting",!1);l(this,"_seq",0);l(this,"_log");l(this,"_lastMessageTime",-1);l(this,"_connnectStartTime",-1);l(this,"_stopConnectRetry");l(this,"bytesSent",0);l(this,"bytesReceived",0);l(this,"keepAlive",!1);l(this,"signalDomainWhenUnifiedProxy");l(this,"stopKeepAliveTimeout");l(this,"rtt",0);this.room=e.room,this.race=g(e.race)?!0:e.race,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy,(((o=(s=this.room.scheduleResult)==null?void 0:s.config)==null?void 0:o.keepAliveClient)||0)-aa.size>0&&this.room.enableSPC&&(this.keepAlive=!0,aa.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.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`),this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get sdkAppId(){return this.room.sdkAppId}get userId(){return this.room.userId}get userSig(){return this.room.userSig}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return f(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=w();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 Ms(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?h.BACKUP:h.MAIN),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:s}){let o=new WebSocket(e);this.bindSocket(o),s?this._socket=o:this._backupSocket=o;let n=-1;return new Promise((a,c)=>{o.onclose=c,o.onerror=c,o.onopen=()=>a(o),t&&(n=setTimeout(()=>{this.unbindAndCloseSocket(s?h.MAIN:h.BACKUP),c(new R({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{o.onclose=null,o.onerror=null,o.onopen=null,clearTimeout(n)})}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){if(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()}this.room.isJoining&&this.emit(me.SETUP_FAILED,new R({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"}))}}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(me.SETUP_FAILED,new R({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=an(e.data);let t=JSON.parse(e.data),{cmd:s,data:o}=t,n=Object.values(qt),c=Object.keys(qt)[n.indexOf(s)],d=U[c]||s;switch(nh.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),d&&this._log.info(`Received event: [ ${d} ]`)),s){case qt.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=o.clientIp,this._signalInfo.signalIp=o.signalInnerIp,o.svrTime&&hl(o.svrTime),this._log.info("ChannelSetup Success"),v.addSuccessEvent({key:521701,cost:w()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(me.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let u=new R({code:S.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:x({key:L.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),v.addFailedEvent({key:521701,error:u}),this.emit(me.SETUP_FAILED,u)}break}case qt.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=o.relayOuterIp,this._signalInfo.relayInnerIp=o.relayInnerIp,this._signalInfo.relayPort=o.relayPort,this._signalInfo.tinyId=t.tinyId,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(d,{data:t});break}default:this.emit(String(d),{data:t});break}}reGetSignalChannelUrl(){return f(this,null,function*(){try{if(!this.room.joinParams)return;kt(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}reconnect(){return f(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:o,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:W.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:o,relayOuterIp:s,relayPort:n},responseCommand:U.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),v.addSuccessEvent({key:521702,cost:w()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(v.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},o=JSON.stringify(s);return this._socketInUse.send(o),this.bytesSent+=an(o),s.seq}}sendWaitForResponse({command:e,data:t,timeout:s=5e3,responseCommand:o,commandDesc:n,enableLog:a=!0}){return new Promise((c,d)=>{let u=setTimeout(()=>{this.off(o,p);let C=new R({code:S.API_CALL_TIMEOUT,message:x({key:L.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(C),d(C)},s),m=Date.now(),p=C=>{C.data.seq===_&&(clearTimeout(u),this.off(o,p),c(C),e===W.GET_USER_LIST&&(this.rtt=Date.now()-m))};this.on(o,p);let _=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:s,retries:o=0,retryTimeout:n=0}=e;return Ot({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${s} when connected`),this.once(me.CONNECTED,a))},onRetrying:a=>{this._log.warn(`${t||s} timeout observed, retrying [${a}/${o}]`)},settings:{retries:o,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),aa.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`),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(U.JOIN_ROOM_RESULT,t)},e*1e3);let t=s=>{s.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(U.JOIN_ROOM_RESULT,t))};this.on(U.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(me.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(me.CONNECTED):e==="DISCONNECTED"&&this.emit(me.DISCONNECTED))}};b([it({settings:{retries:1/0,timeout:2e3},onError(r,i){!this.room.isDestroyed&&!this.destroyed&&i()},onRetrying(r,i){this._log.warn(`retrying to connect ${r}`),r>=3&&r%3===0&&this.reGetSignalChannelUrl(),i&&(this._stopConnectRetry=i,(this.room.isDestroyed||this.destroyed)&&i())}})],Kr.prototype,"connect",1);var dh=Ie(Oe());var Vd=0,Ud=!1,ca=new Set,Xf=r=>Vd>2&&!Ud&&ca.size===0&&r,Bd=!1,Ke=class{constructor(i){l(this,"userId");l(this,"tinyId");l(this,"_sdpSemantics");l(this,"_isUplink");l(this,"_room");l(this,"_log");l(this,"_signalChannel");l(this,"_isErrorObserved",!1);l(this,"_waitForPeerConnectionConnectedPromise");l(this,"_waitForPeerConnectionConnectedPromiseReject",null);l(this,"_peerConnection",null);l(this,"_emitter",new dh.default);l(this,"_currentState","DISCONNECTED");l(this,"_isReconnecting",!1);l(this,"_reconnectionCount",0);l(this,"_reconnectionTimer",-1);l(this,"_isFirstConnection",!0);l(this,"_prevTime",-1);l(this,"_localAddress");l(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}beforeConnect(){this._prevTime<0&&(this._prevTime=w())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,v.addSuccessEvent({key:521705,cost:Math.min(w()-this._prevTime,30*1e3)})):this._isReconnecting&&v.addSuccessEvent({key:521706,cost:w()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,v.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&v.addFailedEvent({key:521706,error:i}),i}}initialize(){let i={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(),ca.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 R({code:S.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return at;let i=null;if(this._isUplink){if(!Di()||this._peerConnection.getSenders().length===0)return at;i=this._peerConnection.getSenders()[0].transport}else{if(!Xi()||this._peerConnection.getReceivers().length===0)return at;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:at}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===oe.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===oe.FAILED||i.target.connectionState===oe.CLOSED){let s=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,o=new R({message:s,code:S.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",o)}(i.target.connectionState===oe.CONNECTED||i.target.connectionState===oe.COMPLETED)&&(this.logSelectedCandidate(),Y.logSuccessEvent({userId:this._room.userId,eventType:Ue.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(Vd=0,Ud=!1,Bd=!0,ca.add(this)):ca.delete(this),T.emit(E.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:i,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:i}),this._currentState=i,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return f(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(vi(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(n),o(),i())},s=({room:a})=>{a===this._room&&(clearTimeout(n),o(),e(new R({code:S.API_CALL_ABORTED,message:x({key:L.CONNECTION_ABORTED,data:"leave room"})})))},o=()=>{T.off(E.LEAVE_SUCCESS,s,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{o();let a=new R({code:S.API_CALL_TIMEOUT,message:"connection timeout"});Vd+=1,Xf(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Ud=!0,this._emitter.emit("firewall-restriction")),e(a)},ms);T.on(E.LEAVE_SUCCESS,s,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(me.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Yt()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new R({code:this._isUplink?S.UPLINK_RECONNECTION_FAILED:S.DOWNLINK_RECONNECTION_FAILED,message:x({key:this._isUplink?L.UPLINK_RECONNECTION_FAILED:L.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(me.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 Gd=Ie(Hd());var de=function(r){return Gd.default.parse(r)},We=function(r){return Gd.default.write(r)},Eh=function(r){let i=de(r);return i.media.forEach(e=>{e.type===h.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),We(i)};function gh(r){let i=de(r);return i.media.forEach(e=>{var t,s;if(e.type===h.VIDEO){let o=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&o.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let d=c.match(/apt=(\d+)/);d&&d[1]&&o.has(Number(d[1]))&&o.add(a)});let n=({payload:a})=>!o.has(a);e.rtp=e.rtp.filter(n),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=(s=e.payloads)==null?void 0:s.split(" ").filter(a=>!o.has(Number(a))).join(" ")}}),We(i)}function da(r){return Object.keys(r).filter(i=>r[i])}var Jd=class extends Ke{constructor(e){super(P(N({},e),{isUplink:!1}));l(this,"_flag",0);l(this,"role","anchor");l(this,"remoteAudioTrack");l(this,"remoteVideoTrack");l(this,"remoteAuxiliaryTrack");l(this,"ssrc",{audio:0,video:0,auxiliary:0});l(this,"_isSDPExchanging",!1);this.flag=e.flag,this.remoteAudioTrack=e.remoteAudioTrack||new mi(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new At(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Jr(this._room,this)}get videoCodec(){var t,s;let e=(s=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:s.sdp;return e?e.includes("H264")?"h264":"vp8":"h264"}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return Ni(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,s,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.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 o,n;let t=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),s}onTrack(e){let t=e.streams[0],{track:s}=e,o=t.id===hs?h.MAIN:h.AUXILIARY;this._log.debug(`ontrack ${o} ${s.kind}`);let n=h.AUDIO;s.kind===h.VIDEO&&(n=o===h.MAIN?h.VIDEO:h.AUXILIARY);let a=this.remoteAudioTrack;n===h.VIDEO?a=this.remoteVideoTrack:n===h.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(s)}addRRTRLine(e){let t=e.split(`\r
65
+ ${s.stack}`),!1}},r};var ea=new WeakMap;function Yu(r,i){return J((e,t)=>function(...s){var a,c;let o=(a=ea.get(this))==null?void 0:a.get(i(...s));o&&o>0&&clearTimeout(o);let n=window.setTimeout(()=>{e.apply(this,s)},r);ea.has(this)?(c=ea.get(this))==null||c.set(i(...s),n):ea.set(this,new Map([[i(...s),n]]))})}var Ku="5.8.4-beta.4";function xe(...r){return J((i,e)=>function(...t){try{ia.call(this,r,t,e,this._name)}catch(s){return Promise.reject(s)}return i.apply(this,t)})}function Cd(...r){return J((i,e)=>function(...t){try{ia.call(this,r,t,e,this._name)}catch(s){throw s}return i.apply(this,t)})}function ia(r,i,e,t){if(fe(r))for(let s=0;s<r.length;s++)ta.call(this,{rule:r[s],value:i[s],key:r[s].name,fnName:e,className:t});else ta.call(this,{rule:r,value:i[0],key:r.name,fnName:e,className:t})}function ta({rule:r,value:i,key:e,fnName:t,className:s}){function o(c){return{code:V.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:r,value:i}}}if(g(i)){if(r.required)throw new k(o(5001));if(g(r.defaultValue)){te(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),te(r.type[d])&&i instanceof r.type[d]&&(c=!0),z(r.type[d])&&ge(i)===r.type[d].toLowerCase()&&(c=!0);if(!c)throw new k({code:V.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:r.type.map(d=>Ps(d)?nn(d):z(d)?d:ge(d))},value:i}})}else if(!g(r.type)&&ge(i)!==r.type)throw new k(o(5002));if(r.allowEmpty===!1){let c=ee(i)&&(i===0||Number.isNaN(i)),d=z(i)&&i.trim()==="";if(c||d)throw new k(o(5003))}if(r.notLessThanZero&&ee(i)&&i<0)throw new k(o(5006));if(!g(r.min)&&ee(i)&&i<r.min)throw new k(o(5007));if(!g(r.max)&&ee(i)&&i>r.max)throw new k(o(5008));if(z(r.instanceOf)){if(!i||i._name!==r.instanceOf)throw new k(o(5004))}else if(te(r.instanceOf)&&!(i instanceof r.instanceOf))throw new k(o(5004));if(Array.isArray(r.values)&&!r.values.includes(i))throw new k(o(5005));let{properties:n}=r;Je(n)&&_t(i)&&Object.keys(n).forEach(c=>{ta.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:s})});let{arrayItem:a}=r;Je(a)&&fe(i)&&i.forEach((c,d)=>{ta.call(this,{rule:a,value:c,key:`${e}[${d}]`,fnName:t,className:s})}),te(r.validate)&&r.validate.call(this,i,e,t,s,this)}function ne(r={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t}=r;return J((s,o)=>function(...n){function a(u,m,p){if(p&&p.includes(u))return"hided";if(e){let _=e(...n);if(n[_.argIndex]===m)return _.value}if(m===n||u in n)return m;try{return m instanceof HTMLElement?`id: ${m.id} type:${ge(m)}`:(JSON.stringify(m),m)}catch(_){return`type:${ge(m)}`}}let c=this._log||A;n.length>0?c.info(`${o}() ${JSON.stringify(n,(u,m)=>a(u,m,["userSig","privateMapKey"]))}`):c.info(`${o}()`);let d=t?t(...n):hn[o];try{let u=s.apply(this,n),m=w();return Ls(u)?u.then(p=>(c.info(`${o}() success ${i.call(this,...n)}`),v.addSuccessEvent({key:d,cost:w()-m}),p)).catch(p=>{throw p=k.convertFrom.call(this,p,o,n.length===1?n[0]:n),c.error(`${o}() failed ${i.call(this,...n)} ${p} params: ${JSON.stringify(n,a)}`),v.addFailedEvent({key:d,error:p}),p}):(v.addSuccessEvent({key:d}),u)}catch(u){throw u=k.convertFrom.call(this,u,o),c.error(`${o}() failed ${u} params: ${JSON.stringify(n,a)}`),v.addFailedEvent({key:d,error:u}),u}})}var ra=r=>J((i,e)=>function(t,s){return f(this,null,function*(){let o=this._plugins.get(t);if(!o)throw this._log.error(`plugin ${String(t)} is not found`),new k({code:V.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(te(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new k({code:V.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return ia.call(this,o.getValidateRule(r),[s],e,"TRTC"),i.call(this,o,s)})});var sa=0,Rd=class{constructor(i,e){l(this,"player");l(this,"publisher");l(this,"mixInput");this.mixInput=new wr(e),i.url?(this.player=new Audio(i.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(i.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(i.track),this.mixInput.connect()}updateSettings(i){!this.player||(g(i.volume)||(this.volume=i.volume),g(i.loop)||(this.loop=i.loop),g(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(!!this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(i){!this.player||i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i)}play(){var i,e;return(i=this.publisher)==null||i.play(),(e=this.player)==null?void 0:e.play()}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function Xr(r,i){if(i&&typeof i!="function")throw new k({code:V.INVALID_PARAMETER,message:`start audioMixer plugin: param ${r} should be a function.`})}var Qr=class{constructor(i){this.core=i;l(this,"log");l(this,"mixedMusicMap",new Map);l(this,"cacheMusicMap",new Map);sa=sa+1,this.log=i.log.createChild({id:`${this.getAlias()}${sa}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${sa}`),this.core=i}getName(){return Qr.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return Qr.startValidateRule;case"update":return Qr.updateValidateRule;case"stop":return Qr.stopValidateRule}}start(i){return f(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 o=this.cacheMusicMap.get(t);o?i.url?o.reset():(o.mixInput.replaceSource(i.track),o.mixInput.connect()):(o=new Rd(i,e.audioManager),this.cacheMusicMap.set(t,o)),o.updateListener(i),o.updateSettings(i),yield o.play(),this.mixedMusicMap.set(t,o),this.log.info(`start mix audio track ${t} success.`),v.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return f(this,null,function*(){let{id:e,operation:t,seekFrom:s,playbackRate:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),g(t)||n.setOperation(t),g(s)||n.seek(s),this.kvUpload(i)})}stop(e){return f(this,arguments,function*({id:i}){var t;this.mixedMusicMap.has(i)&&(this.log.info(`remove music source, music id: ${i}`),(t=this.mixedMusicMap.get(i))==null||t.stop(),this.mixedMusicMap.delete(i)),i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:s,playbackRate:o,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:d,onEnded:u}=i;e&&v.addCount({key:502711}),t&&v.addCount({key:502703}),s&&v.addCount({key:502704}),o&&v.addCount({key:502705}),n&&v.addCount({key:502706}),a&&v.addCount({key:502707}),typeof c!="function"&&v.addCount({key:502709}),typeof u!="function"&&v.addCount({key:502710}),typeof d!="function"&&v.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>this.stop({id:e}))}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}},wi=Qr;l(wi,"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],o=["mp3","ogg","wav","flac"],n=s.split(".").pop(),a=o.indexOf(n)>=0,c=s.startsWith("blob"),d=s.startsWith("data");if(!(a||c||d))throw new k({code:V.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new k({code:V.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});Xr("onTimeUpdate",i.onTimeUpdate),Xr("onEnded",i.onEnded),Xr("onDurationChange",i.onDurationChange)}}),l(wi,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(i,e,t){Xr("onTimeUpdate",i.onTimeUpdate),Xr("onEnded",i.onEnded),Xr("onDurationChange",i.onDurationChange)}}),l(wi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),l(wi,"Name","AudioMixer");var Ff=r=>(r=Number(r),r>0&&r<14e8),oa=0,yd,zr=class{constructor(i){this.core=i;l(this,"log");l(this,"audioContext",qe("denoiser"));l(this,"workletNode");oa=oa+1,this.log=i.log.createChild({id:`${this.getAlias()}${oa}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${oa}`),i.assetsPath&&this.preload(`${i.assetsPath}/denoiser-wasm.js`)}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,s,o){if(!i.room.audioManager.hasAudioTrack)throw new k({code:V.INVALID_OPERATION,extraCode:5106,fnName:s})}}}preload(i){return yd||(yd=this.doPreload(i)),yd}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield zi(this.audioContext,t)}finally{URL.revokeObjectURL(t)}})}getName(){return zr.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return zr.startValidateRule(this.core);case"update":return zr.updateValidateRule;case"stop":return zr.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;if(yield this.preload(`${i.assetsPath}/denoiser-wasm.js`),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:s,sign:o,status:n,message:a}=yield Gf(P(N({},i),{timestamp:t}));if(!s)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${s}. Message: ${a}`),new k({code:V.INVALID_PARAMETER,message:a});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:t,sign:o,status:n}}),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 f(this,null,function*(){})}stop(){return f(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(){}},or=zr;l(or,"updateValidateRule",{type:"object"}),l(or,"stopValidateRule",{type:"object"}),l(or,"Name","AIDenoiser");var Zu={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};function Hf(r){let i;return Ff(r)?i=Zu.MAIN_OVERSEA:i=Zu.MAIN,i}function Gf(s){return f(this,arguments,function*({sdkAppId:r,userId:i,userSig:e,timestamp:t}){let n=`https://${Hf(r)}/api/v1/audioAiAuth?sdkAppId=${r}&userId=${i}&userSig=${e}&timestamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:d,sign:u,status:m}}=yield a.json();if(m==="1")return{auth:!0,sign:u,status:m,message:d};let p="Init RTCAIDenoiser failed.",_="";switch(c){case 1:_="Please check your params.";break;case 2:_="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:_="Server is invalid. Please contact our engineer. ";break;case 4:_="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:_="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:_="Your version is not supported.";break}return{auth:!1,status:m,message:d?`${p} Reason: ${d}. ${_}`:`${p}, ${_}`}})}var eh=Ie(Oe(),1);var bd=class extends eh.EventEmitter{constructor(){super();this.state="nominal";this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return f(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!pe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){Y.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,s=e[e.length-1];this.state=s.state,(this.stateNum>3||t>3)&&A.info(`${s.source}: ${s.state}`),this.emit("state-changed",{type:s.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){Y.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},Wf=new bd,Nd=Wf;function vd([r,i]){let e=i.byteLength,t=parseInt(String(e/255),10),s=e%255,o=[];o.push(0,0,0,1,6,r);for(let a=0;a<t;a++)o.push(255);o.push(s);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new hi(new DataView(new Uint8Array(o).buffer),!0)}function Dd(r){return r.type==="empty"||r.data.byteLength===0}function Od(r){return r.getInt32(0)===1&&r.getInt8(4)===6}function Md(r){let i=0,e=0,t=new DataView(r);for(let s=0;s<r.byteLength;s++)switch(t.getUint8(s)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function kd({frame:r,seiMessageList:i}){if(!i||i.length===0||r.data.byteLength===0)return r;let e=Md(r.data),t=9-e;if(t<=0)return r;let s=i.splice(0,t).reverse().map(vd),o=s.reduce((u,m)=>u+m.dataView.byteLength,0),n=new ArrayBuffer(o+r.data.byteLength),a=new DataView(n),c=new DataView(r.data),d=0;for(let u=0;u<s.length;u++)for(let m=0;m<s[u].dataView.byteLength;m++)a.setInt8(d++,s[u].dataView.getInt8(m));for(let u=0;u<r.data.byteLength;u++)a.setInt8(d++,c.getInt8(u));return r.data=n,r}function Ld({frame:r,onSEI:i}){try{let e=new DataView(r.data);if(Dd(r)||!Od(e))return r;let t=[],s=0,o=-1,n=-1;for(let a=0;a<r.data.byteLength;a++){let c=e.getUint8(a);if(c===0)s++;else if(c===1){if(s===2||s===3){let d=a-s;if(o===-1?o=d:n===-1&&(n=d,t.push(new hi(new DataView(e.buffer.slice(o,n)))),o=d,n=-1),!(e.getUint8(a+1)===6)){r.data=e.buffer.slice(d);break}}s=0}else s=0}i==null||i(t.reverse())}catch(e){}return r}var Pd=0,xd=class{constructor(i){this.core=i;l(this,"log");l(this,"_seiMessageList",[]);l(this,"_smallSeiMessageList",[]);l(this,"_subStreamSeiMessageList",[]);Pd++,this.log=i.log.createChild({id:`${this.getAlias()}${Pd}`}),this.log.info(`[sei] created id=${this.getAlias()}${Pd}`),this.core=i,this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode({frame:i,mediaType:e}){try{let t=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList;return kd({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return Ld({frame:i,onSEI:t=>{t.forEach(s=>{this.core.trtc.emit(M.SEI_MESSAGE,{seiPayloadType:s.seiPayloadType,data:s.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:Tt?this.encode:kd,type:1}),this.core.room.videoManager.addDecodeProcessor({processor:Tt?this.decode:Ld,type:1})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:1}),this.core.room.videoManager.removeDecodeProcessor({type:1})}update({buffer:i,options:e}){var o;let t=[e.seiPayloadType,i],s=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),s&&this._smallSeiMessageList.push(t)),(o=this.core.room.scriptTransformWorker)==null||o.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:s})}getName(){return xd.Name}getAlias(){return"sei"}getGroup(){return"sei"}},Yr=xd;l(Yr,"autoStart",!0),l(Yr,"Name","SEI");var th=0,na=new Set,Ne=null;Aa(Ku);var Jf={RtcError:k,ErrorCode:V,ErrorCodeDictionary:Ct},jt=class extends ih.EventEmitter{constructor(e,t){super();l(this,"_room");l(this,"_eventListened",new Set);l(this,"_localVideoTrack",null);l(this,"_localAudioTrack",null);l(this,"_localScreenTrack",null);l(this,"_localScreenAudioTrack",null);l(this,"_localVideoConfig",null);l(this,"_localScreenConfig",null);l(this,"_localAudioConfig",null);l(this,"_remoteVideoConfigMap",new Map);l(this,"_remoteAudioConfigMap",new Map);l(this,"_remoteAudioMuteMap",new Map);l(this,"_mediaTrackMap",new WeakMap);l(this,"_log",A.createLogger({id:`t${++th}`}));l(this,"_plugins",new Map);l(this,"_networkQuality",null);l(this,"_speakerId");l(this,"_getPCMAbortCtrl");this._room=new e(N({logger:this._log,frameWorkType:jt.frameWorkType},t)),this._log.debug(`TRTC.create() ${JSON.stringify(t,(s,o)=>s==="plugins"?o.map(n=>n.Name):o)}`),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(wi,t.assetsPath),this._use(or,t.assetsPath),t.enableSEI&&Gs&&this._use(Yr),this._room.on("audio-volume",s=>{!s.find(o=>o.userId==="")&&this._localAudioTrack&&s.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),this.emit(M.AUDIO_VOLUME,{result:s.sort((o,n)=>n.volume-o.volume)})}),this._room.videoManager.on("error",s=>{this._log.error(new k({code:V.OPERATION_FAILED,extraCode:5504,message:s.message,originError:s}))}),this._listenEvents(),this._initActiveSpeaker(),zu(this,"trtc")}static create(e){}static _create(e,t){Bu();let s=new jt(e,t||{});return na.add(s),s}get room(){return this._room}_listenEvents(){ke(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(M.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit(M.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{this._exitRoom().then(()=>{this.emit(M.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().then(()=>{this.emit(M.ERROR,k.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(M.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let t=P(N({},e),{uplinkRTT:Math.min(e.uplinkRTT,fs),downlinkRTT:Math.min(e.downlinkRTT,fs)});this.emit(M.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{ke(s,s).add("player-state-changed",o=>{let n=P(N({},o),{userId:e.userId});s.kind===h.VIDEO&&(n.streamType=uo(s.streamType)),this.emit(s.kind===h.AUDIO?M.AUDIO_PLAY_STATE_CHANGED:M.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",o=>{o.getCode()===S.PLAY_NOT_ALLOWED&&this.emit(M.AUTOPLAY_FAILED,{userId:s.userId})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{_e(s)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:s}=t,o=e.audioAvailable,n=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"}`),o!==a&&(this.emit(a?M.REMOTE_AUDIO_AVAILABLE:M.REMOTE_AUDIO_UNAVAILABLE,{userId:s}),a?this._onAudioAvailable({userId:s}):this._onAudioUnavailable({userId:s,muteState:t})),n!==c&&(this.emit(c?M.REMOTE_VIDEO_AVAILABLE:M.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?M.REMOTE_VIDEO_AVAILABLE:M.REMOTE_VIDEO_UNAVAILABLE,{userId:s,streamType:"sub"}),t.hasAuxiliary?this._onVideoAvailable({userId:s,streamType:"sub"}):this._onVideoUnavailable({userId:s,streamType:"sub"}))}).add("sei-message",e=>{this.emit(M.SEI_MESSAGE,P(N({},e),{streamType:uo(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(M.ERROR,new k({code:V.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var o,n,a,c,d,u,m;let t={2:"big",3:"small",7:"sub"},s={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((o=e.msg_down_stream_info[0])==null?void 0:o.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,fs),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:(((u=e.msg_up_stream_info.msg_audio_status)==null?void 0:u.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((m=e.msg_up_stream_info.msg_audio_status)==null?void 0:m.uint32_audio_level)||0)/dt},video:e.msg_up_stream_info.msg_video_status.filter(p=>t[p.uint32_video_stream_type]).map(p=>({bitrate:(p.uint32_video_codec_bitrate||0)/1e3,width:p.uint32_video_width,height:p.uint32_video_height,frameRate:p.uint32_video_enc_fps,videoType:t[p.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(p=>({userId:p.msg_user_info.str_identifier,audio:{bitrate:(p.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(p.msg_audio_status.uint32_audio_level||0)/dt},video:p.msg_video_status.map(_=>({bitrate:(_.uint32_video_codec_bitrate||0)/1e3,width:_.uint32_video_width,height:_.uint32_video_height,frameRate:_.uint32_video_dec_fps,videoType:t[_.uint32_video_stream_type]}))}))};this.emit(M.STATISTICS,s)}).add("custom-message",e=>{this.emit(M.CUSTOM_MESSAGE,e)}),ke(this,Se).add("audioInputAdded",e=>{this.emit(M.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(M.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(M.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(M.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>f(this,null,function*(){if(this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Ne&&Ne.deviceId===ps){let t=(yield Mi()).find(s=>s.deviceId===ps);t&&Ne.groupId!==t.groupId&&(Ne=t,this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>f(this,null,function*(){this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield Mi())[0];t&&Ne&&(Ne.deviceId===e.deviceId||Ne.deviceId===ps&&Ne.groupId!==t.groupId)&&(Ne=t,this.emit(M.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 o=new e(Qu.call(this,{TRTC:jt,room:this._room,errorModule:Jf,assetsPath:t}));this._plugins.set(e.Name,o),e.autoStart&&(this.startPlugin(e.Name),this._log.info("auto start plugin",e.Name))}enterRoom(e){return f(this,null,function*(){var c,d;let{scene:t="rtc",enableAutoPlayDialog:s=!0,autoReceiveAudio:o=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!z(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=o,this._room.autoReceiveVideo=n,le(e.preferHW)&&(this._room.preferHW=e.preferHW);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,jt.frameWorkType),this._checkTrackToPublish(),Nd.start()})}exitRoom(){return f(this,null,function*(){return yield this._exitRoom()})}switchRole(e,t){return f(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),t!=null&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){_e(this),this.removeAllListeners(),this._room.destroy(),na.delete(this),na.size===0&&Nd.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)})}startLocalAudio(){return f(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:o}=e,n=new Le(this._room.audioManager),a={},c={muted:!0};o&&(g(o.microphoneId)?g(o.audioTrack)||(a.customSource=o.audioTrack):a.deviceId=o.microphoneId,o&&ee(o.captureVolume)&&n.setCaptureVolume(o.captureVolume),g(o.profile)||(z(o.profile)?Po[o.profile]&&n.setProfile(Po[o.profile]):n.setProfile(o.profile)),ee(o.earMonitorVolume)&&(c.muted=!(o.earMonitorVolume>0),c.volume=o.earMonitorVolume),g(o.echoCancellation)||(n.profile.echoCancellation=o.echoCancellation),g(o.noiseSuppression)||(n.profile.noiseSuppression=o.noiseSuppression),g(o.autoGainControl)||(n.profile.autoGainControl=o.autoGainControl)),n.on("5",d=>{this.emit(M.ERROR,new k({code:V.DEVICE_ERROR,extraCode:5309,messageParams:{error:d}}))}),n.on("2",d=>{this.emit(M.DEVICE_CHANGED,{type:"microphone",action:"active",device:d})}),n.on("4",d=>{let u;d.error&&(u=k.convertFrom(d.error)),this.emit(M.PUBLISH_STATE_CHANGED,P(N({},d),{error:u}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),g(s)||n.setMute(s),ke(n,n).add("player-state-changed",d=>{this.emit(M.AUDIO_PLAY_STATE_CHANGED,P(N({},d),{userId:""}))}),this.listeners(M.AUDIO_FRAME).length>0&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(d=>{this.emit(jt.EVENT.AUDIO_FRAME,{data:d})})),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=P(N({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:n})})}updateLocalAudio(e){return f(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:s,option:o}=e,n={};o&&(o.microphoneId?yield this._localAudioTrack.switchDevice(o.microphoneId):g(o.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(o.audioTrack)),g(o.captureVolume)||this._localAudioTrack.setCaptureVolume(o.captureVolume),g(o.earMonitorVolume)||(n.muted=!(o.earMonitorVolume>0),n.volume=o.earMonitorVolume),yield this._localAudioTrack.update3A(o)),this._room.isJoined&&!g(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),g(s)||this._localAudioTrack.setMute(s),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),ni(this._localAudioConfig,e)})}stopLocalAudio(){return f(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),_e(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("stopLocalAudio"),delete this._getPCMAbortCtrl))})}startLocalVideo(){return f(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:o,option:n}=e,a=new he(this._room.videoManager),c={},d={};if(n&&(n.cameraId?c.deviceId=n.cameraId:g(n.useFrontCamera)?g(n.videoTrack)||(c.customSource=n.videoTrack):c.facingMode=n.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT,g(n.profile)||(z(n.profile)?Ze[n.profile]&&a.setProfile(Ze[n.profile]):a.setProfile(n.profile)),g(n.fillMode)||(d.objectFit=n.fillMode),g(n.mirror)||(d.mirror=n.mirror),g(n.small)||(Fs()?z(n.small)?a.small=Ze[n.small]:n.small===!0?a.small=Ze["120p"]:a.small=n.small:this._log.warn("small stream is not supported"))),a.on("5",u=>{this.emit(M.ERROR,new k({code:V.DEVICE_ERROR,extraCode:5308,messageParams:{error:u}}))}),a.on("2",u=>{this.emit(M.DEVICE_CHANGED,{type:"camera",action:"active",device:u})}),a.on("4",u=>{let m;u.error&&(m=k.convertFrom(u.error)),this.emit(M.PUBLISH_STATE_CHANGED,P(N({},u),{error:m}))}),this._listenOutputTrackChanged(a),yield a.capture(c),g(o)||(yield a.setMute(o)),a.mediaTrack){if(n!=null&&n.qosPreference){let u=sr(n.qosPreference);a.mediaTrack.contentHint=u}else n!=null&&n.videoTrack||(a.mediaTrack.contentHint=sr(ot.QOS_PREFERENCE_SMOOTH));a.outMediaTrack&&(a.outMediaTrack.contentHint=a.mediaTrack.contentHint)}ke(a,a).add("player-state-changed",u=>{this.emit(M.VIDEO_PLAY_STATE_CHANGED,P(N({},u),{userId:"",streamType:"main"}))}),s&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localVideoTrack=a,this._localVideoConfig=P(N({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:a})})}updateLocalVideo(e){return f(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:s,mute:o,option:n}=e,a={};if(n){if(g(n.profile)||(z(n.profile)?Ze[n.profile]&&this._localVideoTrack.setProfile(Ze[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&g(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):g(n.useFrontCamera)?g(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT),g(n.fillMode)||(a.objectFit=n.fillMode),g(n.mirror)||(a.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack){let c=sr(n.qosPreference);this._localVideoTrack.mediaTrack.contentHint=c,this._localVideoTrack.outMediaTrack&&(this._localVideoTrack.outMediaTrack.contentHint=c)}if(n.small){let c=!this._localVideoTrack.small;Fs()?(n.small===!0?this._localVideoTrack.small=Ze["120p"]:z(n.small)?this._localVideoTrack.small=Ze[n.small]:this._localVideoTrack.small=n.small,this._room.videoManager.update(),c&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else n.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1))}this._room.isJoined&&!g(s)&&(s&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!s&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),g(o)||(yield this._localVideoTrack.setMute(o)),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),ni(this._localVideoConfig,e)})}stopLocalVideo(){return f(this,null,function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),_e(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return f(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:o}=e,n=new ze(this._room.videoManager);n.on("4",m=>{let p;m.error&&(p=k.convertFrom(m.error)),this.emit(M.PUBLISH_STATE_CHANGED,P(N({},m),{error:p}))}),this._listenOutputTrackChanged(n),e.streamType==="main"&&(n.mediaType=4);let a=null,c={},d={};o&&(g(o.profile)||(z(o.profile)?xo[o.profile]&&n.setProfile(xo[o.profile]):n.setProfile(o.profile)),o.systemAudio&&(c.systemAudio=!0,c.echoCancellation=o.echoCancellation,c.noiseSuppression=o.noiseSuppression,c.autoGainControl=o.autoGainControl),g(o.fillMode)||(d.objectFit=o.fillMode),o.videoTrack&&(c.videoTrack=o.videoTrack),o.audioTrack&&(c.audioTrack=o.audioTrack),o.captureElement&&(c.captureElement=o.captureElement),o.preferDisplaySurface&&(c.preferDisplaySurface=o.preferDisplaySurface));let u=yield n.capture(c);if(o!=null&&o.qosPreference){let m=sr(o.qosPreference);n.mediaTrack.contentHint=m}else o!=null&&o.videoTrack||(n.mediaTrack.contentHint=sr(ot.QOS_PREFERENCE_CLEAR));if(n.mediaTrack.addEventListener(h.ENDED,()=>{this._stopScreenShare(),this.emit(M.SCREEN_SHARE_STOPPED)}),u.getAudioTracks()[0]&&(a=new Gt(this._room.audioManager),a.setInputMediaStreamTrack(u.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),ke(n,n).add("player-state-changed",m=>{this.emit(M.VIDEO_PLAY_STATE_CHANGED,P(N({},m),{userId:"",streamType:"sub"}))}),s&&this._room.isJoined){let m=[n];a&&m.push(a),this._room.publish(...m).catch(()=>{})}this._localScreenTrack=n,this._localScreenAudioTrack=a,this._localScreenConfig=P(N({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:n})})}updateScreenShare(e){return f(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:s,option:o}=e,n={};if(o&&(g(o.fillMode)||(n.objectFit=o.fillMode),o.qosPreference)){let a=sr(o.qosPreference);this._localScreenTrack.mediaTrack.contentHint=a}this._room.isJoined&&!g(s)&&(s&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!s&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:t,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),ni(this._localScreenConfig,e)})}stopScreenShare(){return f(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return f(this,null,function*(){let{view:t,userId:s,streamType:o,option:n}=e,a=`${s}_${o}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${s}, streamType:${o}`);return}let c=this._room.remotePublishedUserMap.get(s);if(!c)return;let d={},u=o==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;this._listenOutputTrackChanged(u),n&&(g(n.fillMode)||(d.objectFit=n.fillMode),g(n.mirror)||(d.mirror=n.mirror),d.canvasRender=n.canvasRender,o==="main"&&!g(n.small)&&(c.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,u.user))),yield this._room.subscribe(u),yield this._updateVideoPlayOption({view:t,playOption:d,track:u}),this._emitTrackEvent(u),this._remoteVideoConfigMap.set(a,{config:e}),n&&!g(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:u,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return f(this,null,function*(){var D,B;let{view:t,userId:s,streamType:o,option:n}=e,a=`${s}_${o}`,c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(s))return;let d={};n&&(g(n.fillMode)||(d.objectFit=n.fillMode),g(n.mirror)||(d.mirror=n.mirror));let u=null,m=this._room.remotePublishedUserMap.get(s);if(o==="main"&&(m==null?void 0:m.muteState.hasVideo)&&(u=m.remoteVideoTrack),o==="sub"&&(m==null?void 0:m.muteState.hasAuxiliary)&&(u=m.remoteAuxiliaryTrack),!u)return;let{config:p}=c;o==="main"&&n&&!g(n.small)&&this._room.changeType(n.small,u.user),yield this._updateVideoPlayOption({view:t,playOption:d,track:u,prevConfig:p}),ni(p,e);let _=g(n==null?void 0:n.receiveWhenViewVisible)?(D=p.option)==null?void 0:D.receiveWhenViewVisible:n.receiveWhenViewVisible,C=g(t)?p.view:t,y=g(n==null?void 0:n.viewRoot)?(B=p.option)==null?void 0:B.viewRoot:n.viewRoot;this._observeView({remoteTrack:u,view:C,receiveWhenViewVisible:_,viewRoot:y})})}stopRemoteVideo(e){return f(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return f(this,null,function*(){let s=[],o=this._room.remotePublishedUserMap.get(e.userId);if(o){let{muteState:a,remoteVideoTrack:c,remoteAuxiliaryTrack:d}=o;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 n=this._remoteVideoConfigMap.get(`${e.userId}_${e.streamType}`);n&&n.observer&&n.observer.disconnect(),this._remoteVideoConfigMap.delete(`${e.userId}_${e.streamType}`)})}muteRemoteAudio(e,t){return f(this,null,function*(){if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let s=[...this._room.remotePublishedUserMap.values()];for(let o of s)o.muteState.hasAudio&&!this._remoteAudioConfigMap.has(o.userId)&&(yield this._startRemoteAudio({userId:o.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 o of s)this._updateAudioPlayOption({playOption:{volume:t},track:o.remoteAudioTrack})}else if(e){let s=this._room.remotePublishedUserMap.get(e);s&&this._updateAudioPlayOption({playOption:{volume:t},track:s.remoteAudioTrack})}}startPlugin(e,t){return f(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return f(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return f(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,s){return this.listeners(e).includes(t)?this:(this._log.debug("on",e),super.on(e,t,s),this._eventListened.add(e),e===jt.EVENT.AUDIO_FRAME&&!this._getPCMAbortCtrl&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(o=>{this.emit(jt.EVENT.AUDIO_FRAME,{data:o})})),this)}emit(e,...t){try{qu.has(e)&&this._log.debug(`emit ${e} ${JSON.stringify(t)}`)}catch(s){}return super.emit(e,...t)}off(e,t,s){var o,n;return this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners(),(o=this._getPCMAbortCtrl)==null||o.abort("off"),delete this._getPCMAbortCtrl):(super.off(e,t,s),e===jt.EVENT.AUDIO_FRAME&&((n=this._getPCMAbortCtrl)==null||n.abort("off"),delete this._getPCMAbortCtrl)),this}getAudioTrack(e={userId:"",streamType:"main"}){let t,s=null,o="main",n=!1;if(z(e)?t=e:(t=e.userId,n=e.processed===!0,e.streamType&&(o=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);a&&(s=a.remoteAudioTrack)}else s=o==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return s?n&&s.outMediaTrack&&s.outMediaTrack!==s.mediaTrack?s.outMediaTrack.clone():s.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:s="main",processed:o=!1}=e,n=null;if(t==="")s==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),s==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(t);a&&(n=s==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?o&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:t,streamType:s="main"}=e;if(t){let o=this._room.remotePublishedUserMap.get(t);if(s==="main"&&(o==null?void 0:o.muteState.hasVideo))return o.remoteVideoTrack.getVideoFrame();if(s==="sub"&&(o==null?void 0:o.muteState.hasAuxiliary))return o.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(o=>o.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return f(this,null,function*(){(yield Mi()).forEach(s=>{s.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:s}),Ne=s)}),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return f(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 o=this._room.remotePublishedUserMap.get(t);if(!o)return;let n={};s&&(g(s.volume)||(n.volume=s.volume));let a=o.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:n,track:a})}catch(c){throw this._remoteAudioConfigMap.delete(t),c}this._emitTrackEvent(a)})}_stopRemoteAudio(e,t=!0){return f(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(n){return f(this,arguments,function*({view:e,playOption:t,track:s,prevConfig:o}){if(s.setMirror(t.mirror),g(e)&&o&&o.view&&!Za(t)){let a=ws(o.view);a.length>0&&(yield s.play(a,t))}if(!g(e)){let a=ws(e);a.length>0?yield s.play(a,t):s.stop()}})}_updateAudioPlayOption(o){return f(this,arguments,function*({playOption:e={},track:t,prevConfig:s}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}g(e.muted)||t.setPlayerMute(e.muted),g(e.volume)||t.setAudioVolume(e.volume/100)})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,t=!0){let s=e.isRemote?e.userId:"";!e.outMediaTrack||t&&this._mediaTrackMap.get(e.outMediaTrack)===s||(this._mediaTrackMap.set(e.outMediaTrack,s),this.emit(M.TRACK,{userId:s,streamType:uo(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var t,s,o;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),(o=this._localScreenConfig)!=null&&o.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:o}){if(g(t))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${uo(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||fe(t)&&t.length===0||!s){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let d=n.visibleViewMap||new Map,u=-1;(!a||a.root!==o)&&(a==null||a.disconnect(),d.clear(),a=new IntersectionObserver(p=>{p.forEach(_=>{d.set(_.target,_.isIntersecting)}),clearTimeout(u),u=window.setTimeout(()=>{[...d.values()].find(C=>C)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:o}));let m=new Set(ws(t));d.forEach((p,_)=>{m.has(_)||(a.unobserve(_),d.delete(_))}),m.forEach(p=>{d.set(p,!0),a.observe(p)}),a.takeRecords().forEach(p=>{d.set(p.target,p.isIntersecting)}),n.visibleViewMap=d,n.observer=a}_exitRoom(){return f(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=>{_e(e.remoteAudioTrack),_e(e.remoteVideoTrack),_e(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return f(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),_e(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_initActiveSpeaker(){return f(this,null,function*(){if(Ne&&!Vr(Ne))this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:Ne});else{let e=yield Mi();if(e[0]&&!Vr(e[0]))Ne=e[0],this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let t=({track:s})=>{s.kind==="audio"&&(!Ne||Vr(Ne))&&(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 o=t==="main"?s.remoteVideoTrack:s.remoteAuxiliaryTrack;this._room.subscribe(o).then(()=>{this._emitTrackEvent(o)}).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){var o;let s=this._plugins.get("SEI");s&&(s.update({buffer:e,options:P(N({seiPayloadType:243},t),{small:!!((o=this._localVideoTrack)!=null&&o.small)})}),v.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,s;(s=(t=this._room).sendCustomMessage)==null||s.call(t,e),v.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){A.setLogLevel(e),g(t)||(t?A.enableUploadLog():A.disableUploadLog())}static isSupported(){return _n()}static getCameraList(e=!0){return Xe(e)}static getMicrophoneList(e=!0){return Fe(e)}static getSpeakerList(e=!0){return Mi(e)}static setCurrentSpeaker(e){return f(this,null,function*(){(yield Mi()).forEach(s=>{s.deviceId===e&&(na.forEach(o=>{o._setCurrentSpeaker(e),o.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:s})}),Ne=s)})})}static _addKVStat({type:e,key:t,value:s,base:o,useUV:n,version:a}){switch(a&&(qi.version=a),e){case"count":qi.addCount({key:t,useUV:n});break;case"enum":qi.addEnum({key:t,value:s,useUV:n});break;case"number":qi.addNumber({key:t,value:s,split:o});break}}},X=jt;l(X,"_loggerManager",A),l(X,"EVENT",M),l(X,"ERROR_CODE",V),l(X,"TYPE",ot),l(X,"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"}})})],X.prototype,"use",1),b([xe(Re.TRTC.enterRoom),Pi("room",([r],[i])=>(r.roomId||r.strRoomId)===(i.roomId||i.strRoomId)&&r.userId===i.userId&&r.sdkAppId===i.sdkAppId),J(r=>function(i){return this._log.setUserId(i.userId),this._log.setSdkAppId(i.sdkAppId),r.call(this,i)}),ne()],X.prototype,"enterRoom",1),b([ne()],X.prototype,"exitRoom",1),b([xe(Re.TRTC.switchRole),rr("room",{merge:(r,i)=>i}),ne()],X.prototype,"switchRole",1),b([ne()],X.prototype,"destroy",1),b([xe(Re.TRTC.startLocalAudio),Pi("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()],X.prototype,"startLocalAudio",1),b([xe(Re.TRTC.updateLocalAudio),rr("audio",{debounce:{delay:200,getKey:()=>`${th}-localAudio`,isNeedToDebounce:r=>{var i;return!g((i=r.option)==null?void 0:i.captureVolume)}}}),ne()],X.prototype,"updateLocalAudio",1),b([xi("audio"),ne()],X.prototype,"stopLocalAudio",1),b([xe(Re.TRTC.startLocalVideo),Pi("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()],X.prototype,"startLocalVideo",1),b([xe(Re.TRTC.updateLocalVideo),rr("video"),ne()],X.prototype,"updateLocalVideo",1),b([xi("video"),ne()],X.prototype,"stopLocalVideo",1),b([xe(Re.TRTC.startScreenShare),Pi("screen",()=>!0),ne()],X.prototype,"startScreenShare",1),b([xe(Re.TRTC.updateScreenShare),rr("screen"),ne()],X.prototype,"updateScreenShare",1),b([ne()],X.prototype,"stopScreenShare",1),b([xe(Re.TRTC.startRemoteVideo),Pi(r=>`v${r.userId}${r.streamType}`,()=>!0),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],X.prototype,"startRemoteVideo",1),b([xe(Re.TRTC.updateRemoteVideo),rr(r=>`v${r.userId}${r.streamType}`),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],X.prototype,"updateRemoteVideo",1),b([xe(Re.TRTC.stopRemoteVideo),J(r=>function(i){return f(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}`})],X.prototype,"stopRemoteVideo",1),b([xi(r=>`v${r.userId}${r.streamType}`)],X.prototype,"_stopRemoteVideo",1),b([xe(...Re.TRTC.muteRemoteAudio),ne({getRemoteId:r=>r})],X.prototype,"muteRemoteAudio",1),b([Cd(...Re.TRTC.setRemoteAudioVolume),Yu(200,r=>r),ne({getRemoteId:r=>r})],X.prototype,"setRemoteAudioVolume",1),b([ra("start"),It(r=>{var i;return(i=r.afterStart)==null?void 0:i.call(r)}),Pi((r,i)=>r.disableRandomCall?null:r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>dc[r.getName()]})],X.prototype,"startPlugin",1),b([ra("update"),rr((r,i)=>r.disableRandomCall?null:r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>lc[r.getName()]})],X.prototype,"updatePlugin",1),b([ra("stop"),xi((r,i)=>{if(r.disableRandomCall)return null;let e=r.getGroup(i),t=r.getAlias();return e==="*"?new RegExp(`${t}.*`):t+e}),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>uc[r.getName()]})],X.prototype,"stopPlugin",1),b([Cd(...Re.TRTC.enableAudioVolumeEvaluation)],X.prototype,"enableAudioVolumeEvaluation",1),b([ne()],X.prototype,"getVideoSnapshot",1),b([ne()],X.prototype,"_setCurrentSpeaker",1),b([Pi(r=>`a${r.userId}`,()=>!0)],X.prototype,"_startRemoteAudio",1),b([J(r=>function(i){return f(this,null,function*(){return i.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(e=>this._stopRemoteAudio(P(N({},i),{userId:e.userId})).catch(()=>{}))):r.call(this,i)})}),xi(r=>`a${r.userId}`)],X.prototype,"_stopRemoteAudio",1),b([xi("room")],X.prototype,"_exitRoom",1),b([xi("screen")],X.prototype,"_stopScreenShare",1),b([xe(...Re.TRTC.sendSEIMessage),Sd({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...r)=>r[0].byteLength})],X.prototype,"sendSEIMessage",1),b([xe(Re.TRTC.sendCustomMessage),Sd({timesInSecond:30,maxSizeInSecond:8e3,getSize:r=>r.data.byteLength})],X.prototype,"sendCustomMessage",1),b([xe(Re.TRTC.create)],X,"_create",1);var ho=X;var wd=class{constructor(){this._set=new Set;T.on(E.LEAVE_SUCCESS,this.delete,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,s){return`${t}_${e}_${i}_${s}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:s}){return s.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,s.useStringRoomId))}};function jf(){return f(this,null,function*(){let r,i;try{let m=yield Fe();r=m&&m.length}catch(m){}try{let m=yield Xe();i=m&&m.length}catch(m){}let e={microphone:r,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:s,isH264DecodeSupported:o,isVp8DecodeSupported:n}=this.checkSystemResult.detail,a=wt.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:t,h264Decode:o,vp8Encode:s,vp8Decode:n},d={browser:a.browser,os:a.os,trtc:c,devices:e},u={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};Y.uploadEvent({log:`trtcstats-${JSON.stringify(d)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(d)}`),Y.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(u)}`,userId:this.userId})})}function rh(){return J(r=>{let i=new wd;return function(e,t,s){return f(this,null,function*(){let o=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 R({code:S.INVALID_OPERATION,message:x({key:L.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new R({code:S.INVALID_OPERATION,message:x({key:L.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:o}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${o} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),T.emit(E.JOIN_START,{room:this,roomId:o,params:e});let n=Ve.getEnv();n||(n=zt.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(wo.OLD_CLOUD_LADDER)?n=zt.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(wo.WEBRTC)&&(n=zt.WEBRTC))),Y.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),wt.checkSystemRequirementsInternal().then(a=>{this.checkSystemResult=a,jf.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Ve.getEnv()&&(yield this.schedule(e,s));let a=yield r.call(this,e,t,s);return this.roomId=o,this._joinedTimestamp=Ve.performanceNow(),T.emit(E.JOIN_SUCCESS,{room:this}),s===30&&!e.component&&Y.uploadEvent({log:`stat-conv-${Number(ti)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw i.delete({room:this,roomId:o}),T.emit(E.JOIN_FAILED,{room:this,error:a}),a}})}})}var sh=()=>J(r=>function(...i){return f(this,null,function*(){T.emit(E.LEAVE_START,{room:this}),yield r.call(this),T.emit(E.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function oh(){return J(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var ah=Ie(Oe());var me={SETUP_SUCCESS:"1",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4",SETUP_FAILED:"5",DISCONNECTED:"6"};var qt={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},nh=[qt.UPDATE_REMOTE_MUTE_STAT,qt.UPLINK_NETWORK_STATS,qt.USER_LIST_RES,qt.MUTE_RESULT,qt.SERVER_FIRST_PACKAGE_RECEIVED],U={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 aa=new Set;function ch(r){let i=[...aa.values()].find(e=>e.room.userId===r&&!e.room.isJoined);return i||null}var Kr=class extends ah.default{constructor(e){var s,o;super();l(this,"room");l(this,"url");l(this,"backupUrl");l(this,"race");l(this,"destroyed",!1);l(this,"_socketInUse");l(this,"_socket");l(this,"_backupSocket");l(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0});l(this,"_currentState","DISCONNECTED");l(this,"_isReconnecting",!1);l(this,"_seq",0);l(this,"_log");l(this,"_lastMessageTime",-1);l(this,"_connnectStartTime",-1);l(this,"_stopConnectRetry");l(this,"bytesSent",0);l(this,"bytesReceived",0);l(this,"keepAlive",!1);l(this,"signalDomainWhenUnifiedProxy");l(this,"stopKeepAliveTimeout");l(this,"rtt",0);this.room=e.room,this.race=g(e.race)?!0:e.race,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy,(((o=(s=this.room.scheduleResult)==null?void 0:s.config)==null?void 0:o.keepAliveClient)||0)-aa.size>0&&this.room.enableSPC&&(this.keepAlive=!0,aa.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.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`),this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get sdkAppId(){return this.room.sdkAppId}get userId(){return this.room.userId}get userSig(){return this.room.userSig}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return f(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=w();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 Ms(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?h.BACKUP:h.MAIN),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:s}){let o=new WebSocket(e);this.bindSocket(o),s?this._socket=o:this._backupSocket=o;let n=-1;return new Promise((a,c)=>{o.onclose=c,o.onerror=c,o.onopen=()=>a(o),t&&(n=setTimeout(()=>{this.unbindAndCloseSocket(s?h.MAIN:h.BACKUP),c(new R({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{o.onclose=null,o.onerror=null,o.onopen=null,clearTimeout(n)})}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){if(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()}this.room.isJoining&&this.emit(me.SETUP_FAILED,new R({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"}))}}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(me.SETUP_FAILED,new R({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=an(e.data);let t=JSON.parse(e.data),{cmd:s,data:o}=t,n=Object.values(qt),c=Object.keys(qt)[n.indexOf(s)],d=U[c]||s;switch(nh.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),d&&this._log.info(`Received event: [ ${d} ]`)),s){case qt.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=o.clientIp,this._signalInfo.signalIp=o.signalInnerIp,o.svrTime&&hl(o.svrTime),this._log.info("ChannelSetup Success"),v.addSuccessEvent({key:521701,cost:w()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(me.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let u=new R({code:S.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:x({key:L.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),v.addFailedEvent({key:521701,error:u}),this.emit(me.SETUP_FAILED,u)}break}case qt.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=o.relayOuterIp,this._signalInfo.relayInnerIp=o.relayInnerIp,this._signalInfo.relayPort=o.relayPort,this._signalInfo.tinyId=t.tinyId,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(d,{data:t});break}default:this.emit(String(d),{data:t});break}}reGetSignalChannelUrl(){return f(this,null,function*(){try{if(!this.room.joinParams)return;kt(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}reconnect(){return f(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:o,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:W.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:o,relayOuterIp:s,relayPort:n},responseCommand:U.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),v.addSuccessEvent({key:521702,cost:w()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(v.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},o=JSON.stringify(s);return this._socketInUse.send(o),this.bytesSent+=an(o),s.seq}}sendWaitForResponse({command:e,data:t,timeout:s=5e3,responseCommand:o,commandDesc:n,enableLog:a=!0}){return new Promise((c,d)=>{let u=setTimeout(()=>{this.off(o,p);let C=new R({code:S.API_CALL_TIMEOUT,message:x({key:L.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(C),d(C)},s),m=Date.now(),p=C=>{C.data.seq===_&&(clearTimeout(u),this.off(o,p),c(C),e===W.GET_USER_LIST&&(this.rtt=Date.now()-m))};this.on(o,p);let _=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:s,retries:o=0,retryTimeout:n=0}=e;return Ot({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${s} when connected`),this.once(me.CONNECTED,a))},onRetrying:a=>{this._log.warn(`${t||s} timeout observed, retrying [${a}/${o}]`)},settings:{retries:o,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),aa.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`),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(U.JOIN_ROOM_RESULT,t)},e*1e3);let t=s=>{s.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(U.JOIN_ROOM_RESULT,t))};this.on(U.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(me.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(me.CONNECTED):e==="DISCONNECTED"&&this.emit(me.DISCONNECTED))}};b([it({settings:{retries:1/0,timeout:2e3},onError(r,i){!this.room.isDestroyed&&!this.destroyed&&i()},onRetrying(r,i){this._log.warn(`retrying to connect ${r}`),r>=3&&r%3===0&&this.reGetSignalChannelUrl(),i&&(this._stopConnectRetry=i,(this.room.isDestroyed||this.destroyed)&&i())}})],Kr.prototype,"connect",1);var dh=Ie(Oe());var Vd=0,Ud=!1,ca=new Set,Xf=r=>Vd>2&&!Ud&&ca.size===0&&r,Bd=!1,Ke=class{constructor(i){l(this,"userId");l(this,"tinyId");l(this,"_sdpSemantics");l(this,"_isUplink");l(this,"_room");l(this,"_log");l(this,"_signalChannel");l(this,"_isErrorObserved",!1);l(this,"_waitForPeerConnectionConnectedPromise");l(this,"_waitForPeerConnectionConnectedPromiseReject",null);l(this,"_peerConnection",null);l(this,"_emitter",new dh.default);l(this,"_currentState","DISCONNECTED");l(this,"_isReconnecting",!1);l(this,"_reconnectionCount",0);l(this,"_reconnectionTimer",-1);l(this,"_isFirstConnection",!0);l(this,"_prevTime",-1);l(this,"_localAddress");l(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}beforeConnect(){this._prevTime<0&&(this._prevTime=w())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,v.addSuccessEvent({key:521705,cost:Math.min(w()-this._prevTime,30*1e3)})):this._isReconnecting&&v.addSuccessEvent({key:521706,cost:w()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,v.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&v.addFailedEvent({key:521706,error:i}),i}}initialize(){let i={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(),ca.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 R({code:S.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return at;let i=null;if(this._isUplink){if(!Di()||this._peerConnection.getSenders().length===0)return at;i=this._peerConnection.getSenders()[0].transport}else{if(!Xi()||this._peerConnection.getReceivers().length===0)return at;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:at}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===oe.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===oe.FAILED||i.target.connectionState===oe.CLOSED){let s=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,o=new R({message:s,code:S.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",o)}(i.target.connectionState===oe.CONNECTED||i.target.connectionState===oe.COMPLETED)&&(this.logSelectedCandidate(),Y.logSuccessEvent({userId:this._room.userId,eventType:Ue.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(Vd=0,Ud=!1,Bd=!0,ca.add(this)):ca.delete(this),T.emit(E.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:i,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:i}),this._currentState=i,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return f(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(vi(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(n),o(),i())},s=({room:a})=>{a===this._room&&(clearTimeout(n),o(),e(new R({code:S.API_CALL_ABORTED,message:x({key:L.CONNECTION_ABORTED,data:"leave room"})})))},o=()=>{T.off(E.LEAVE_SUCCESS,s,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{o();let a=new R({code:S.API_CALL_TIMEOUT,message:"connection timeout"});Vd+=1,Xf(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Ud=!0,this._emitter.emit("firewall-restriction")),e(a)},ms);T.on(E.LEAVE_SUCCESS,s,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(me.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Yt()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new R({code:this._isUplink?S.UPLINK_RECONNECTION_FAILED:S.DOWNLINK_RECONNECTION_FAILED,message:x({key:this._isUplink?L.UPLINK_RECONNECTION_FAILED:L.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(me.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 Gd=Ie(Hd());var de=function(r){return Gd.default.parse(r)},We=function(r){return Gd.default.write(r)},Eh=function(r){let i=de(r);return i.media.forEach(e=>{e.type===h.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),We(i)};function gh(r){let i=de(r);return i.media.forEach(e=>{var t,s;if(e.type===h.VIDEO){let o=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&o.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let d=c.match(/apt=(\d+)/);d&&d[1]&&o.has(Number(d[1]))&&o.add(a)});let n=({payload:a})=>!o.has(a);e.rtp=e.rtp.filter(n),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=(s=e.payloads)==null?void 0:s.split(" ").filter(a=>!o.has(Number(a))).join(" ")}}),We(i)}function da(r){return Object.keys(r).filter(i=>r[i])}var Jd=class extends Ke{constructor(e){super(P(N({},e),{isUplink:!1}));l(this,"_flag",0);l(this,"role","anchor");l(this,"remoteAudioTrack");l(this,"remoteVideoTrack");l(this,"remoteAuxiliaryTrack");l(this,"ssrc",{audio:0,video:0,auxiliary:0});l(this,"_isSDPExchanging",!1);this.flag=e.flag,this.remoteAudioTrack=e.remoteAudioTrack||new mi(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new At(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Jr(this._room,this)}get videoCodec(){var t,s;let e=(s=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:s.sdp;return e?e.includes("H264")?"h264":"vp8":"h264"}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return Ni(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,s,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.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 o,n;let t=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),s}onTrack(e){let t=e.streams[0],{track:s}=e,o=t.id===hs?h.MAIN:h.AUXILIARY;this._log.debug(`ontrack ${o} ${s.kind}`);let n=h.AUDIO;s.kind===h.VIDEO&&(n=o===h.MAIN?h.VIDEO:h.AUXILIARY);let a=this.remoteAudioTrack;n===h.VIDEO?a=this.remoteVideoTrack:n===h.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(s)}addRRTRLine(e){let t=e.split(`\r
66
66
  `),s=new Map;t.forEach((n,a)=>{/^a=rtcp-fb:/.test(n)&&t[a+1]&&!/^a=rtcp-fb:/.test(t[a+1])&&s.set(a+1,`${n.match(/^a=rtcp-fb:\d+/)[0]} rrtr`)});let o=[...s];for(let n=0;n<o.length;n++){let[a,c]=o[n];t.splice(a+n,0,c)}return t.join(`\r
67
67
  `)}addSPSDescription(e){let t=de(e);return t.media.forEach(s=>{s.type===h.VIDEO&&s.fmtp.forEach(o=>{o.config+=";sps-pps-idr-in-keyframe=1"})}),We(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=de(e);return s.media.forEach(o=>{!o.ext||(o.ext=o.ext.filter(n=>!t.includes(n.uri)))}),We(s)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return f(this,null,function*(){var s,o;try{if((((s=this._peerConnection)==null?void 0:s.connectionState)===oe.NEW||((o=this._peerConnection)==null?void 0:o.connectionState)===oe.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 n="subscribe_change";Object.values(e).find(a=>a===!0)||(n="unsubscribe"),yield this.sendSubscription(n,e)}else this.initialize(),yield this.connect(e)}catch(n){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${n.message} ${JSON.stringify(this.muteState)}`),new R({code:S.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}unsubscribe(s){return f(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 o=N({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(a=>a===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${da(o)}]`),yield this.sendSubscription(n,o),n==="unsubscribe"&&(this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,t=this.subscribeState){let s={srcTinyId:this.tinyId,srcUserId:this.userId},o=W.UNSUBSCRIBE,n=U.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(s={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=W.SUBSCRIBE_CHANGE,n=U.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:o,data:s,responseCommand:n,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new R({code:a.code,message:x({key:L.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}connect(){return f(this,arguments,function*(e=this.subscribeState){try{yield this.exchangeSDP(e),yield this.waitForPeerConnectionConnected()}catch(t){throw this.closePeerConnection(!0),t}})}exchangeSDP(e){return f(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,o={type:t,sdp:s,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:W.SUBSCRIBE,commandDesc:"exchange sdp",data:o,responseCommand:U.SUBSCRIBE_RESULT,timeout:Ma});if(!this._peerConnection){let a=new R({code:S.INVALID_OPERATION,message:x({key:L.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return f(this,null,function*(){let e={voiceActivityDetection:!1};tt()&&this._sdpSemantics===Si?(this._peerConnection.addTransceiver(h.AUDIO,{direction:Q.RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:Q.RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:Q.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:s}=yield fn();s||(this._log.warn("remove h264 desc from sdp"),t.sdp=gh(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=Eh(t.sdp),this._sdpSemantics===Si&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this._peerConnection.setLocalDescription(t)})}onSubscribeResult(e){return f(this,null,function*(){let{code:t,message:s=""}=e&&e.data||{},{type:o,sdp:n}=e&&e.data&&e.data.data||{};if(t===Fi)throw new R({code:S.NOT_SUPPORTED_H264,message:x({key:L.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new R({code:t,message:x({key:L.EXCHANGE_SDP_FAILED,data:{errMsg:s}})});this._log.debug(`accept remote answer: ${n}`),yield this._peerConnection.setRemoteDescription({type:o,sdp:n}),this.updateSSRC(n)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{de(e).media.forEach(s=>{if(!!s.ssrcs)if(s.type===h.AUDIO){let o=s.ssrcs.find(n=>{var a;return(a=n.value)==null?void 0:a.includes(hs)});o&&(this.ssrc.audio=Number(o.id))}else{let o=s.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(hs)}),n=s.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(ba)});o&&(this.ssrc.video=Number(o.id)),n&&(this.ssrc.auxiliary=Number(n.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 f(this,null,function*(){if(!(Ae(Jd.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=Lt(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}},fo=Jd;b([J(r=>function(...i){return new Promise((e,t)=>{let s=o=>{this._emitter.off("closed",s),t(new R({code:S.API_CALL_ABORTED,message:x({key:L.CONNECTION_ABORTED,data:o})}))};this._emitter.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this._emitter.off("closed",s)})})})],fo.prototype,"subscribe",1),b([It(Ke.prototype.afterConnect),On(Ke.prototype.beforeConnect)],fo.prototype,"connect",1);var Wd=fo;var Sh={voiceActivityDetection:!1},jd=class extends Ke{constructor(e){super(P(N({},e),{isUplink:!0}));l(this,"localMainAudioTrack",null);l(this,"localMainVideoTrack",null);l(this,"localAuxAudioTrack",null);l(this,"localAuxVideoTrack",null);l(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});l(this,"_isPublishingAux",!1);l(this,"_publishingLocalAudioTrack");l(this,"_publishingLocalVideoTrack");l(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});l(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,s,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(Pt()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((s=a[1])!=null&&s.track),e.smallVideo=!!((o=a[2])!=null&&o.track),e.auxVideo=!!((n=a[3])!=null&&n.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 n,a,c;let s=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):((n=this.localMainVideoTrack)==null||n.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}))),o}publish(o){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:s}){this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),t&&(this._publishingLocalVideoTrack=t),this._isPublishingAux=s;let n;t&&!s&&t.small&&(n=this._room.videoManager.smallTrack),this.sendMediaSettings(),tt()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:s}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:n}),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)),this.installTrackMuteEvents(e,t),this.sendMutedFlag()})}publishByTransceiver(n){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:s,isAuxiliary:o}){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 u=this._peerConnection.getTransceivers();if(u.length===0)this._peerConnection.addTransceiver(d||h.AUDIO,{direction:Q.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?h.VIDEO:c||h.VIDEO,{direction:Q.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s||h.VIDEO,{direction:Q.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?c||h.VIDEO:h.VIDEO,{direction:Q.SENDONLY,streams:[a]}),yield this.connect();else{let m=[];if(d&&(u[0].sender.track||m.push(0),yield u[0].sender.replaceTrack(d),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:h.AUDIO})),c){let p=o?3:1;yield u[p].sender.replaceTrack(c),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:h.VIDEO,videoType:o?h.AUXILIARY:h.BIG}),m.push(p),s&&(yield u[2].sender.replaceTrack(s),yield this.setBandwidth({bandwidth:t.small.bitrate,type:h.VIDEO,videoType:h.SMALL}),m.push(2))}yield this.setTransceiverDirection(Q.SENDONLY,m),yield this.doPublishChange(),t==null||t.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),t==null||t.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}})}publishByAddTrack(o){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:s}){this._log.info("publish by addtrack");let n=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)),n&&(yield this.addTrack(t));return}let c=new MediaStream;if(a&&c.addTrack(a),n&&c.addTrack(n),a&&this._peerConnection.addTrack(a,c),n&&(this._peerConnection.addTrack(n,c),s)){let d=new MediaStream;d.addTrack(s),this._peerConnection.addTrack(s,d)}yield this.connect()})}enableSmall(e){return f(this,null,function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(Q.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(Q.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(s){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!Pt()){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 o=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localAuxAudioTrack&&!this.localMainAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=P(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=P(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(Q.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return f(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},s=yield this._signalChannel.sendWaitForResponse({command:W.PUBLISH_STATE_CHANGE,data:t,responseCommand:U.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:U.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===S.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:o,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:o=this._publishingLocalVideoTrack),xt){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(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=o.profile.bitrate*1e3,o.small&&(this._mediaSettings.smallVideoWidth=o.small.width,this._mediaSettings.smallVideoHeight=o.small.height,this._mediaSettings.smallVideoFps=o.small.frameRate,this._mediaSettings.smallVideoBps=o.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.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),o&&o.outMediaTrack&&(this._mediaSettings.videoWidth=o.profile.width,this._mediaSettings.videoHeight=o.profile.height,this._mediaSettings.videoFps=o.profile.frameRate,this._mediaSettings.videoBps=o.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:U.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return f(this,null,function*(){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`),tt()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return f(this,null,function*(){var o;if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield s[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)==null?void 0:o.small)&&(yield s[2].sender.replaceTrack(this._room.videoManager.smallTrack)),s[n].direction===Q.INACTIVE&&(yield this.setTransceiverDirection(Q.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return f(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;Pt()&&this._peerConnection.getTransceivers().findIndex(o=>o.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let s=this._peerConnection.getSenders().find(o=>o.track&&o.track.kind===t.kind);if(s&&s.track){this._log.warn("sender already exists, remove sender first");let o=s.track;this.removeSender(s),yield this.updateOffer("remove",o)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===h.VIDEO&&e instanceof he&&e.small){let o=new MediaStream,{smallTrack:n}=this._room.videoManager;o.addTrack(n),this._peerConnection.addTrack(n,o)}yield this.updateOffer("add",t)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===hr||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=de(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;Pt()&&(t=this._peerConnection.getTransceivers().find(s=>s.sender&&s.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&te(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?h.AUXILIARY:h.MAIN} stream`),tt()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return f(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 o=t?3:1;yield s[o].sender.replaceTrack(null),o===1&&e.small&&(yield s[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(Q.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return f(this,null,function*(){if(!re)return;let s=!1,o=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let n=this._peerConnection.getTransceivers();if(t.forEach(d=>{n[d].direction!==e&&(n[d].direction=e,s=!0)}),s){this._log.info("updating offer");let d=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(d)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
68
68
  `).map(d=>{if(d.match(new RegExp(`a=(${Q.INACTIVE}|${Q.RECVONLY}|${Q.SENDONLY})`))&&a++,t.includes(a)){if(e===Q.INACTIVE&&d.includes(`a=${Q.RECVONLY}`))return o=!0,`a=${e}`;if(e===Q.SENDONLY&&d.includes(`a=${Q.INACTIVE}`))return o=!0,`a=${Q.RECVONLY}`}return d}).join(`\r