aliyun-rtc-sdk 7.1.7 → 7.1.9

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.
@@ -126,10 +126,10 @@ onmessage = function(evt) {
126
126
  `+((A=_.get("Content-Type"))!=null?A:"")+`
127
127
  `+y+`
128
128
  `;const E=(P,B)=>P[0].localeCompare(B[0]),T=P=>P[0].startsWith("x-log-")||P[0].startsWith("x-acs-");try{const P=[..._.entries()].filter(T).sort(E).map(B=>B[0]+":"+B[1]+`
129
- `).join("");R+=P}catch(P){}R+=m,v.size>0&&(R+="?");try{R+=[...v.entries()].sort(E).map(P=>P[0]+"="+P[1]).join("&")}catch(P){}const k="LOG "+b+":"+hi.HmacSHA1(R,S).toString(hi.enc.Base64);_.set("Authorization",k),_.set("x-log-date",y)}("POST",n,s.accessKeyId,s.accessKeySecret,l,p,o,h);let u=Object.fromEntries(p);return{data:e,header:u}},new Promise((n,c)=>{var o=l=>{try{h(r.next(l))}catch(p){c(p)}},d=l=>{try{h(r.throw(l))}catch(p){c(p)}},h=l=>l.done?n(l.value):Promise.resolve(l.value).then(o,d);h((r=r.apply(t,i)).next())});var t,i,r}}}typeof window!="undefined"&&Ps(window,"stsPlugin",fr);var yo=/d{1,4}|D{3,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|W{1,2}|[LlopSZN]|"[^"]*"|'[^']*'/g,Ao=/\b(?:[A-Z]{1,3}[A-Z][TC])(?:[-+]\d{4})?|((?:Australian )?(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time)\b/g,Ro=/[^-+\dA-Z]/g;function Sr(s,a,e,t){if(arguments.length!==1||typeof s!="string"||/\d/.test(s)||(a=s,s=void 0),(s=s||s===0?s:new Date)instanceof Date||(s=new Date(s)),isNaN(s))throw TypeError("Invalid date");var i=(a=String(Va[a]||a||Va.default)).slice(0,4);i!=="UTC:"&&i!=="GMT:"||(a=a.slice(4),e=!0,i==="GMT:"&&(t=!0));var r=function(){return e?"getUTC":"get"},n=function(){return s[r()+"Date"]()},c=function(){return s[r()+"Day"]()},o=function(){return s[r()+"Month"]()},d=function(){return s[r()+"FullYear"]()},h=function(){return s[r()+"Hours"]()},l=function(){return s[r()+"Minutes"]()},p=function(){return s[r()+"Seconds"]()},u=function(){return s[r()+"Milliseconds"]()},f=function(){return e?0:s.getTimezoneOffset()},m=function(){return _o(s)},b={d:function(){return n()},dd:function(){return at(n())},ddd:function(){return et.dayNames[c()]},DDD:function(){return Oa({y:d(),m:o(),d:n(),_:r(),dayName:et.dayNames[c()],short:!0})},dddd:function(){return et.dayNames[c()+7]},DDDD:function(){return Oa({y:d(),m:o(),d:n(),_:r(),dayName:et.dayNames[c()+7]})},m:function(){return o()+1},mm:function(){return at(o()+1)},mmm:function(){return et.monthNames[o()]},mmmm:function(){return et.monthNames[o()+12]},yy:function(){return String(d()).slice(2)},yyyy:function(){return at(d(),4)},h:function(){return h()%12||12},hh:function(){return at(h()%12||12)},H:function(){return h()},HH:function(){return at(h())},M:function(){return l()},MM:function(){return at(l())},s:function(){return p()},ss:function(){return at(p())},l:function(){return at(u(),3)},L:function(){return at(Math.floor(u()/10))},t:function(){return h()<12?et.timeNames[0]:et.timeNames[1]},tt:function(){return h()<12?et.timeNames[2]:et.timeNames[3]},T:function(){return h()<12?et.timeNames[4]:et.timeNames[5]},TT:function(){return h()<12?et.timeNames[6]:et.timeNames[7]},Z:function(){return t?"GMT":e?"UTC":Eo(s)},o:function(){return(f()>0?"-":"+")+at(100*Math.floor(Math.abs(f())/60)+Math.abs(f())%60,4)},p:function(){return(f()>0?"-":"+")+at(Math.floor(Math.abs(f())/60),2)+":"+at(Math.floor(Math.abs(f())%60),2)},S:function(){return["th","st","nd","rd"][n()%10>3?0:(n()%100-n()%10!=10)*n()%10]},W:function(){return m()},WW:function(){return at(m())},N:function(){return wo(s)}};return a.replace(yo,function(S){return S in b?b[S]():S.slice(1,S.length-1)})}var Va={default:"ddd mmm dd yyyy HH:MM:ss",shortDate:"m/d/yy",paddedShortDate:"mm/dd/yyyy",mediumDate:"mmm d, yyyy",longDate:"mmmm d, yyyy",fullDate:"dddd, mmmm d, yyyy",shortTime:"h:MM TT",mediumTime:"h:MM:ss TT",longTime:"h:MM:ss TT Z",isoDate:"yyyy-mm-dd",isoTime:"HH:MM:ss",isoDateTime:"yyyy-mm-dd'T'HH:MM:sso",isoUtcDateTime:"UTC:yyyy-mm-dd'T'HH:MM:ss'Z'",expiresHeaderFormat:"ddd, dd mmm yyyy HH:MM:ss Z"},et={dayNames:["Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],monthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","January","February","March","April","May","June","July","August","September","October","November","December"],timeNames:["a","p","am","pm","A","P","AM","PM"]},at=function(s){var a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:2;return String(s).padStart(a,"0")},Oa=function(s){var a=s.y,e=s.m,t=s.d,i=s._,r=s.dayName,n=s.short,c=n!==void 0&&n,o=new Date,d=new Date;d.setDate(d[i+"Date"]()-1);var h=new Date;return h.setDate(h[i+"Date"]()+1),o[i+"FullYear"]()===a&&o[i+"Month"]()===e&&o[i+"Date"]()===t?c?"Tdy":"Today":d[i+"FullYear"]()===a&&d[i+"Month"]()===e&&d[i+"Date"]()===t?c?"Ysd":"Yesterday":h[i+"FullYear"]()===a&&h[i+"Month"]()===e&&h[i+"Date"]()===t?c?"Tmw":"Tomorrow":r},_o=function(s){var a=new Date(s.getFullYear(),s.getMonth(),s.getDate());a.setDate(a.getDate()-(a.getDay()+6)%7+3);var e=new Date(a.getFullYear(),0,4);e.setDate(e.getDate()-(e.getDay()+6)%7+3);var t=a.getTimezoneOffset()-e.getTimezoneOffset();a.setHours(a.getHours()-t);var i=(a-e)/6048e5;return 1+Math.floor(i)},wo=function(s){var a=s.getDay();return a===0&&(a=7),a},Eo=function(s){return(String(s).match(Ao)||[""]).pop().replace(Ro,"").replace(/GMT\+0000/g,"UTC")},Mi=(s=>(s.prod="rs.rtn.aliyuncs.com",s.pre="prs.rtn.aliyuncs.com",s))(Mi||{});const Li="7.1.7";class nt{static getVersionNumber(){let a=Li.split("."),e="";return a.forEach(t=>{t.length===1?e+="0"+t:e+=t}),parseInt(e)}static queryingParam(a){let e=[];if(a)for(let t in a)e.push(t+"="+a[t]);return e.join("&")}static getQueryParams(a){const e=window.location.search.substring(1).split("&");for(let t=0;t<e.length;t++){const i=e[t].split("=");if(decodeURIComponent(i[0])===a)return decodeURIComponent(i[1])}}static createCallid(a=""){const e=dt();return a&&e&&e.length>a.length?`${a}${e.substring(a.length)}`:e}static checkSubOptionsValid(a){if(a){const{audio:e,video:t,screen:i}=a;if(e===!1&&t===!1&&i===!1)return!1}return!0}static isNetworkAvailable(){return I(this,null,function*(){const a=Mi.prod,{onLine:e}=navigator;if(!e)return!1;try{return yield fetch(`https://${a}/roomserver/v1/ws/version`),!0}catch(t){return!1}})}static toString(a){let e;if(a instanceof Error)e=a.message;else if(typeof a=="string")e=a;else try{e=JSON.stringify(a)}catch(t){e="undefined"}return e}static paramArrayToString(a){let e="";for(let t=0;t<a.length;t++)e!==""&&(e+=" "),e+=nt.toString(a[t]);return e}}const{BrowserUtil:To}=X.AliRTS,Io="EdgeHTML",Ua="Blink",Co="Trident",ko="Gecko",Po="WebKit",Ni=(s,a)=>{const e=a.match(s);return e&&e.length>0&&e[1]||""},Do=[{test:[/\sedg\//i,[/edg([ea]|ios)/i]],describe(s){if(/\sedg\//i.test(s))return{name:Ua};const a=Ni(/edge\/(\d+(\.?_?\d+)+)/i,s);return{name:Io,version:a}}},{test:[/trident/i],describe(s){const a={name:Co},e=Ni(/trident\/(\d+(\.?_?\d+)+)/i,s);return e&&(a.version=e),a}},{test(s){const a=/gecko/i.test(s),e=/like gecko/i.test(s);return a&&!e},describe(s){const a={name:ko},e=Ni(/gecko\/(\d+(\.?_?\d+)+)/i,s);return e&&(a.version=e),a}},{test:[/(apple)?webkit\/537\.36/i],describe:()=>({name:Ua})},{test:[/(apple)?webkit/i],describe(s){const a={name:Po},e=Ni(/webkit\/(\d+(\.?_?\d+)+)/i,s);return e&&(a.version=e),a}}],br=(s,a)=>s.find(e=>typeof e.test=="function"?e.test(a):Array.isArray(e.test)?e.test.some(t=>typeof t=="string"?a.indexOf(t)>-1:t instanceof RegExp&&t.test(a)):void 0),Mo=()=>{try{const s=navigator.userAgent||"",a=br(Do,s);if(a){const e=a.describe(s);return`${e.name}/${e.version||To.browserVersion}`}}catch(s){}return navigator.userAgent},Lo=[{test:["wow64","win64","x64"],describe:()=>"amd64"},{test:["i686","x86"],describe:()=>"x86"},{test:["aarch64","arm64"],describe:()=>"arm64"},{test:["arm"],describe:()=>"arm"}],Ba=()=>{let s="unknown";try{const a=navigator.userAgent||"",e=br(Lo,a);if(!e)return s;s=e.describe(a)}catch(a){}return s},No=[{test:[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],describe:()=>"Samsung"},{test:[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i,/\((ipad);[-\w\),; ]+apple/i,/(macintosh);/i],describe:()=>"Apple"},{test:[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],describe:()=>"Huawei"},{test:[/(?:honor)([-\w ]+)[;\)]/i],describe:()=>"Honor"},{test:[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],describe:()=>"Xiaomi"},{test:[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],describe:()=>"Oppo"},{test:[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],describe:()=>"Vivo"},{test:[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],describe:()=>"Realme"},{test:[/(pixel c)\b/i,/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],describe:()=>"Google"},{test:[/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],describe:()=>"ZTE"},{test:[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],describe:()=>"Meizu"}],xo=()=>{let s="Unknown";try{const a=navigator.userAgent||"",e=br(No,a);if(!e)return s;s=e.describe(a)}catch(a){}return s},{BrowserUtil:Ha,SystenUtil:Fa}=X.AliRTS,Vo=Ba(),xi=6e5,Vi={host:"cn-hangzhou.log.aliyuncs.com",project:"alivc-aio",logstore:"logger",time:10,count:10};function vr(){return Sr(new Date,"HH:MM:ss.l")}function ja(){return Sr(new Date,"isoDate")}var yr=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.API=2]="API",s[s.WARNING=3]="WARNING",s[s.ERROR=4]="ERROR",s[s.NONE=5]="NONE",s))(yr||{});class Oo{constructor(){g(this,"tracker");g(this,"slsPlugin");g(this,"stsData");g(this,"stsExpiration",Date.now());g(this,"clientId",dt());g(this,"bSesid",dt());g(this,"logLevel",3);g(this,"appId","");g(this,"sessionId","");g(this,"logCache",[]);g(this,"updateTaskTimer");g(this,"endReported",!0);g(this,"logSequence",0);g(this,"sendLogBeforeUnload",a=>I(this,null,function*(){if(!this.slsPlugin)return;this.logSequence+=1,a.unshift(this.getLogParams(710203,{log:`[${ja()} ${vr()}] [INF] beforeunload`,stat_log_seq:this.logSequence}));const e=`https://${Vi.project}.${Vi.host}/logstores/${Vi.logstore}`,t={__logs__:a.map(n=>this.slsPlugin.transString(n))},{data:i,header:r}=yield this.slsPlugin.process(e,JSON.stringify(t));fetch(e,{keepalive:!0,method:"POST",headers:r,body:i})}));g(this,"logMethod",(a,e=console.log)=>(...t)=>{let i=vr();this.logLevel<=a&&e(i,...t);let r=nt.paramArrayToString(t);a>0&&this.addLog(r)});g(this,"d",this.logMethod(0,console.debug));g(this,"i",this.logMethod(1));g(this,"w",this.logMethod(3,console.warn));g(this,"e",this.logMethod(4,(...a)=>{const[e,...t]=a;console.error(e,"<error>",t)}));g(this,"ev",this.logMethod(2));g(this,"a",this.logMethod(2,(...a)=>{const[e,...t]=a;if(t.length>2){const i=`${t[1]}`;i.startsWith("__g__")&&console.group(`${i.substring(5)}_${t[2]}`)}console.log(e,...t)}));g(this,"ar",this.logMethod(2,(...a)=>{const[e,...t]=a;console.log(e,...t),t.length>2&&`${t[1]}`.startsWith("__g__")&&console.groupEnd()}));g(this,"ae",this.logMethod(2,(...a)=>{const[e,...t]=a;console.error(e,"<error>",...t),t.length>2&&`${t[1]}`.startsWith("__g__")&&console.groupEnd()}));window.addEventListener("beforeunload",()=>{this.reportEnd(!0)})}init(){this.reset(),this.startSTSUpdateTask()}destroy(){this.updateTaskTimer&&clearTimeout(this.updateTaskTimer)}reset(){this.bSesid=dt(),this.endReported=!0,this.logSequence=0,this.appId="",this.sessionId=""}startSTSUpdateTask(){return I(this,null,function*(){this.updateTaskTimer&&clearTimeout(this.updateTaskTimer);try{const a=yield this.refreshSTSToken();this.createTracker(a)}catch(a){}this.updateTaskTimer=setTimeout(()=>{this.startSTSUpdateTask()},xi)})}refreshSTSToken(){return I(this,null,function*(){if(!this.stsData||this.stsExpiration<=Date.now()-xi){const a=yield this.requestSTSToken(),e=new Date(a==null?void 0:a.Expiration).getTime()||0,t=Date.now()+xi;this.stsExpiration=Math.max(e,t),this.stsData=a}return this.stsData})}requestSTSToken(){const a=Date.now(),e=`${this.clientId}|woMMssV6jmyol9fr|${a}`,t={Action:"AssumeSlsRoleV2",AuthInfo:hi.MD5(e).toString(hi.enc.Hex),ClientId:this.clientId,BusinessType:"logger",AppVersion:"1.0",Version:"2017-03-14",AuthTimestamp:`${a}`,TerminalType:"web",DeviceModel:"",Format:"JSON",SignatureMethod:"HMAC-SHA1",SignatureVersion:"1.0",Timestamp:Sr(a,"isoUtcDateTime")},i=new URLSearchParams(t).toString();return fetch(`https://slsrole.alicdn.com/?${i}`).then(r=>r.json()).then(r=>JSON.parse(window.atob(r.SlsAuthResult)))}createTracker(a){if(!this.tracker){const e={accessKeyId:a.AccessKeyId,accessKeySecret:a.AccessKeySecret,securityToken:a.SecurityToken,refreshSTSTokenInterval:xi,stsTokenFreshTime:void 0,refreshSTSToken:()=>{this.refreshSTSToken().then(r=>{e.accessKeyId=r.AccessKeyId,e.accessKeySecret=r.AccessKeySecret,e.securityToken=r.SecurityToken}).catch(()=>{})}},t=new pr(Vi),i=fr(e);t.useStsPlugin(i),this.slsPlugin=i,this.tracker=t,this.reportStartAndCache()}}changeConfig(a){a.logLevel!==void 0&&a.logLevel>=0&&a.logLevel<=5&&(this.logLevel=a.logLevel)}setSessionID(a,e){a&&e&&(this.appId=a,this.sessionId=e,this.reportStartAndCache())}reportStartAndCache(){if(!this.tracker||!this.sessionId)return;this.endReported=!1;const a={task_btm_sec:0,task_duration:0,task_etm_sec:0,task_type:"session"},e=[this.getLogParams(710201,a),this.getLogParams(710202,a)];this.tracker.sendBatchLogsImmediate(e),this.logCache.forEach(t=>{this.sendLog(t)})}reportEnd(a=!1){if(!this.tracker||!this.sessionId||this.endReported)return void this.reset();const e={task_btm_sec:0,task_duration:0,task_etm_sec:0,task_type:"session"},t=[this.getLogParams(710204,e),this.getLogParams(710205,e)];a?this.sendLogBeforeUnload(t):(this.tracker.sendBatchLogsImmediate(t),this.endReported=!0),this.reset()}getLogParams(a,e){return G({appid:`${window.location.host}`,appid_list:this.appId,appver:"",b_sesid:this.bSesid,biz_type:"rtc",cpu_info:Vo,db:Ha.browserName,dm:Ha.browserVersion,install_uuid:this.clientId,logger_v:"0.0.1",os:Fa.systemName,osv:Fa.systemVersion,p_sesid:this.bSesid,sdk_version:Li,sdkname:"AliRTCSdk",stm:Date.now(),tar_pf:"web",traceid:this.sessionId,event_id:a},e||{})}sendLog(a){if(!this.tracker||!this.sessionId)return;this.logSequence+=1;const e=this.getLogParams(710203,{log:a,stat_log_seq:this.logSequence});this.tracker.send(e)}addLog(a){const e=vr(),t=`[${ja()} ${e}] ${a}`;this.sessionId&&this.tracker?this.sendLog(t):(this.logCache.push(t),this.logCache.length>=200&&this.logCache.shift())}}class V{static getLogger(){return this.logger||(this.logger=new Oo),this.logger}static init(){this.getLogger().init()}static destroy(){this.getLogger().destroy()}static setLogLevel(a){this.getLogger().changeConfig({logLevel:a})}static setSessionID(a,e){this.getLogger().setSessionID(a,e)}static reportEnd(){this.getLogger().reportEnd()}static interface(...a){this.getLogger().a("[API]",...a)}static interfaceResult(a,e,t,...i){t?this.getLogger().ar("[ARE]",a,e,...i):this.getLogger().ae("[ARE]",a,e,...i)}static event(...a){this.getLogger().ev("[EVT]",...a)}static debug(...a){this.getLogger().d("[DBG]",...a)}static info(...a){this.getLogger().i("[INF]",...a)}static warn(...a){this.getLogger().w("[WARN]",...a)}static error(...a){this.getLogger().e("[ERR]",...a)}}g(V,"logger");var Ee=(s=>(s.PullStreamStats="remoteStat",s.RtsSubscribeExceeds="rtsSubscribeExceeds",s.UserJoined="userJoined",s.UserLeft="userLeft",s.Bye="bye",s.MuteAudio="muteAudio",s.UnmuteAudio="unmuteAudio",s.MuteVideo="muteVideo",s.UnmuteVideo="unmuteVideo",s.MuteScreen="muteScreen",s.UnmuteScreen="unmuteScreen",s.Error="error",s))(Ee||{}),Ye=(s=>(s.Local="local-device-status-change",s.Remote="remote-device-status-change",s))(Ye||{}),M=(s=>(s.Audio="sophon_audio",s.VideoLarge="sophon_video_camera_large",s.VideoSmall="sophon_video_camera_small",s.Screen="sophon_video_screen_share",s.Data="sophon_data",s))(M||{}),Ar=(s=>(s.Audio="rts audio",s.VideoLarge="rts video",s))(Ar||{}),Lt=(s=>(s.Add="add",s.Delete="delete",s.Replace="replace",s.Stop="stop",s.UnPublish="unpublish",s))(Lt||{}),li=(s=>(s[s.Camera=0]="Camera",s[s.Screen=1]="Screen",s[s.Image=2]="Image",s))(li||{}),Oi=(s=>(s[s.Microphone=0]="Microphone",s[s.Screen=1]="Screen",s[s.Mixed=2]="Mixed",s))(Oi||{}),be=(s=>(s.InRoom="inRoom",s.Join="join",s.Publish="publish",s.User="user",s.Resume="resume",s.Retry="retry",s.Reconnect="reconnect",s))(be||{}),yt=(s=>(s[s.MANUAL=0]="MANUAL",s[s.JOIN_CHANNEL=1]="JOIN_CHANNEL",s[s.ROLE_CHANGE=2]="ROLE_CHANGE",s[s.RECONNECT=3]="RECONNECT",s))(yt||{});function ii(){}const Yt=class Yt{static getInstance(){var a;return Yt.instance||(Yt.instance=new AudioContext),(a=Yt.instance.resume())==null||a.then(ii,ii).catch(ii),Yt.instance}};g(Yt,"instance");let Kt=Yt;const Ui=()=>{var a;const s=Kt.getInstance();s.state!=="running"&&s.state!=="closed"&&((a=s.resume())==null||a.then(ii,ii).catch(ii)),window.removeEventListener("mousedown",Ui),window.removeEventListener("touchstart",Ui)};window.addEventListener("mousedown",Ui),window.addEventListener("touchstart",Ui);class Uo extends se{constructor(){super();g(this,"audioContext");g(this,"stream");g(this,"sourceNode");g(this,"analyser");this.audioContext=Kt.getInstance(),this.stream=new MediaStream}getLevel(){return this.analyser?this.analyser.getLevel():0}start(e,t=1e3){this.sourceNode&&this.stop(),this.stream.addTrack(e),this.sourceNode=this.audioContext.createMediaStreamSource(this.stream);const i=this.audioContext.createMediaStreamDestination();this.analyser=function(r,n,c,o,d){let h,l=o,p=0;const u=r.createAnalyser();u.fftSize=256;const f=new Uint8Array(u.frequencyBinCount);n.connect(u),u.connect(c);const m=()=>{h&&window.clearInterval(h)},b=()=>{r.state==="suspended"&&r.resume(),h=window.setInterval(()=>{u.getByteFrequencyData(f);let S=Math.round(f.reduce((v,_)=>v+_)/f.length);S=Math.min(100,S),p=S,d&&d(S)},l)};return b(),{updateInterval:S=>{m(),l=S,b()},getLevel:()=>p,dispose:()=>{m(),n.disconnect(),u.disconnect()}}}(this.audioContext,this.sourceNode,i,t,r=>{this.emit("audioLevel",r)})}stop(){this.analyser&&this.analyser.dispose(),this.analyser=void 0,this.sourceNode=void 0,this.stream.getAudioTracks().forEach(e=>{this.stream.removeTrack(e)})}dispose(){this.stop()}}class za extends se{constructor(e,t,i,r){super();g(this,"uid");g(this,"name");g(this,"rtsManager");g(this,"callId","");g(this,"audioLevelMonitor");g(this,"audioVolumeIndicationInterval",0);this.uid=e,this.name=t,this.rtsManager=i,this.audioVolumeIndicationInterval=r,this.audioLevelMonitor=new Uo}get userId(){return this.uid}get displayname(){return this.name}createCallId(){this.callId||(this.callId=nt.createCallid())}setUserInfo(e,t){this.uid=e,this.name=t}refreshUserInfo(e){this.uid=e}getAudioLevel(){return this.audioLevelMonitor.getLevel()}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval=e}clear(){this.audioLevelMonitor.dispose()}}class Wa{static getCurrentStatus(a){let e=0;a.micOpen&&(e+=1),a.micInterrupted&&(e+=2),a.cameraOpen&&(e+=4),a.screenShare&&(e+=128),a.audioDisable&&(e+=8),a.videoDisable&&(e+=16),a.screenDisable&&(e+=256);let t=e.toString(16);for(;t.length<16;)t="0"+t;return t}static parseStatus(a){let e=parseInt(a,16);return{micOpen:!!(1&e),micInterrupted:!!(2&e),cameraOpen:!!(4&e),screenShare:!!(128&e),audioDisable:!!(8&e),videoDisable:!!(16&e),screenDisable:!!(256&e),backgroundMode:!!(32&e),accompanyPlaying:!!(64&e)}}}var kt=(s=>(s.pre="pre",s.prod="prod",s))(kt||{}),Pt=(s=>(s.AliRtcSdkCommunication="communication",s.AliRtcSdkInteractiveLive="interactive_live",s.AliRtcSdkInteractiveWithLowLatencyLive="cdn_live",s))(Pt||{}),Nt=(s=>(s.AliRtcSdkInteractive="interactive",s.AliRtcSdkLive="live",s))(Nt||{}),At=(s=>(s[s.AliEngineLocalDeviceTypeUnknown=0]="AliEngineLocalDeviceTypeUnknown",s[s.AliEngineLocalDeviceTypeMic=1]="AliEngineLocalDeviceTypeMic",s[s.AliEngineLocalDeviceTypeSpeaker=2]="AliEngineLocalDeviceTypeSpeaker",s[s.AliEngineLocalDeviceTypeAudioDevice=3]="AliEngineLocalDeviceTypeAudioDevice",s[s.AliEngineLocalDeviceTypeCamera=4]="AliEngineLocalDeviceTypeCamera",s[s.AliEngineLocalDeviceTypeDisplay=5]="AliEngineLocalDeviceTypeDisplay",s[s.AliEngineLocalDeviceTypeVideoDevice=6]="AliEngineLocalDeviceTypeVideoDevice",s))(At||{}),Ue=(s=>(s[s.AliEngineLocalDeviceExceptionTypeUnknown=0]="AliEngineLocalDeviceExceptionTypeUnknown",s[s.AliEngineLocalDeviceExceptionTypeMicOpenFail=1]="AliEngineLocalDeviceExceptionTypeMicOpenFail",s[s.AliEngineLocalDeviceExceptionTypeMicInterrupt=2]="AliEngineLocalDeviceExceptionTypeMicInterrupt",s[s.AliEngineLocalDeviceExceptionTypeMicAuthFail=3]="AliEngineLocalDeviceExceptionTypeMicAuthFail",s[s.AliEngineLocalDeviceExceptionTypeMicNotAvailable=4]="AliEngineLocalDeviceExceptionTypeMicNotAvailable",s[s.AliEngineLocalDeviceExceptionTypeSpeakerOpenFail=5]="AliEngineLocalDeviceExceptionTypeSpeakerOpenFail",s[s.AliEngineLocalDeviceExceptionTypeSpeakerInterrupt=6]="AliEngineLocalDeviceExceptionTypeSpeakerInterrupt",s[s.AliEngineLocalDeviceExceptionTypeSpeakerNotAvailable=7]="AliEngineLocalDeviceExceptionTypeSpeakerNotAvailable",s[s.AliEngineLocalDeviceExceptionTypeAudioDeviceException=8]="AliEngineLocalDeviceExceptionTypeAudioDeviceException",s[s.AliEngineLocalDeviceExceptionTypeCameraOpenFail=9]="AliEngineLocalDeviceExceptionTypeCameraOpenFail",s[s.AliEngineLocalDeviceExceptionTypeCameraInterrupt=10]="AliEngineLocalDeviceExceptionTypeCameraInterrupt",s[s.AliEngineLocalDeviceExceptionTypeCameraAuthFail=11]="AliEngineLocalDeviceExceptionTypeCameraAuthFail",s[s.AliEngineLocalDeviceExceptionTypeDisplayException=12]="AliEngineLocalDeviceExceptionTypeDisplayException",s[s.AliEngineLocalDeviceExceptionTypeVideoDeviceException=13]="AliEngineLocalDeviceExceptionTypeVideoDeviceException",s))(Ue||{}),ne=(s=>(s[s.AliRtcConnectionStatusInit=0]="AliRtcConnectionStatusInit",s[s.AliRtcConnectionStatusDisconnected=1]="AliRtcConnectionStatusDisconnected",s[s.AliRtcConnectionStatusConnecting=2]="AliRtcConnectionStatusConnecting",s[s.AliRtcConnectionStatusConnected=3]="AliRtcConnectionStatusConnected",s[s.AliRtcConnectionStatusReconnecting=4]="AliRtcConnectionStatusReconnecting",s[s.AliRtcConnectionStatusFailed=5]="AliRtcConnectionStatusFailed",s))(ne||{}),Rt=(s=>(s[s.AliRtcConnectionChangedDummyReason=0]="AliRtcConnectionChangedDummyReason",s[s.AliRtcConnectionMediaPathChanged=1]="AliRtcConnectionMediaPathChanged",s[s.AliRtcConnectionSignalingHeartbeatTimeout=2]="AliRtcConnectionSignalingHeartbeatTimeout",s[s.AliRtcConnectionSignalingHeartbeatAlive=3]="AliRtcConnectionSignalingHeartbeatAlive",s[s.AliRtcConnectionSignalingHttpDnsResolved=4]="AliRtcConnectionSignalingHttpDnsResolved",s[s.AliRtcConnectionSignalingHttpDnsFailure=5]="AliRtcConnectionSignalingHttpDnsFailure",s[s.AliRtcConnectionSignalingGslbFailure=6]="AliRtcConnectionSignalingGslbFailure",s[s.AliRtcConnectionSignalingGslbSuccess=7]="AliRtcConnectionSignalingGslbSuccess",s[s.AliRtcConnectionSignalingJoinRoomFailure=8]="AliRtcConnectionSignalingJoinRoomFailure",s[s.AliRtcConnectionSignalingJoinRoomSuccess=9]="AliRtcConnectionSignalingJoinRoomSuccess",s[s.AliRtcConnectionSignalingLeaveRoom=10]="AliRtcConnectionSignalingLeaveRoom",s[s.AliRtcConnectionSignalingConnecting=11]="AliRtcConnectionSignalingConnecting",s[s.AliRtcConnectionChangedNetworkInterrupted=12]="AliRtcConnectionChangedNetworkInterrupted",s))(Rt||{}),Rr=(s=>(s[s.AliRtcUserOfflineQuit=0]="AliRtcUserOfflineQuit",s[s.AliRtcUserOfflineDropped=1]="AliRtcUserOfflineDropped",s[s.AliRtcUserOfflineBecomeAudience=2]="AliRtcUserOfflineBecomeAudience",s))(Rr||{}),Jt=(s=>(s[s.AliRtcAudioTrackNo=0]="AliRtcAudioTrackNo",s[s.AliRtcAudioTrackMic=1]="AliRtcAudioTrackMic",s[s.AliRtcAudioTrackDual=2]="AliRtcAudioTrackDual",s))(Jt||{}),oe=(s=>(s[s.AliRtcVideoTrackNo=0]="AliRtcVideoTrackNo",s[s.AliRtcVideoTrackCamera=1]="AliRtcVideoTrackCamera",s[s.AliRtcVideoTrackScreen=2]="AliRtcVideoTrackScreen",s[s.AliRtcVideoTrackBoth=3]="AliRtcVideoTrackBoth",s))(oe||{}),ie=(s=>(s[s.AliRtcStatePublishIdle=0]="AliRtcStatePublishIdle",s[s.AliRtcStateNoPublish=1]="AliRtcStateNoPublish",s[s.AliRtcStatePublishing=2]="AliRtcStatePublishing",s[s.AliRtcStatePublished=3]="AliRtcStatePublished",s))(ie||{}),me=(s=>(s[s.AliRtcStateSubscribeIdle=0]="AliRtcStateSubscribeIdle",s[s.AliRtcStateNoSubscribe=1]="AliRtcStateNoSubscribe",s[s.AliRtcStateSubscribing=2]="AliRtcStateSubscribing",s[s.AliRtcStateSubscribed=3]="AliRtcStateSubscribed",s))(me||{}),ze=(s=>(s[s.AliRtcVideoStreamTypeNone=0]="AliRtcVideoStreamTypeNone",s[s.AliRtcVideoStreamTypeHigh=1]="AliRtcVideoStreamTypeHigh",s[s.AliRtcVideoStreamTypeLow=2]="AliRtcVideoStreamTypeLow",s))(ze||{}),ui=(s=>(s[s.CAMERA_INVALID=-1]="CAMERA_INVALID",s[s.CAMERA_REAR=0]="CAMERA_REAR",s[s.CAMERA_FRONT=1]="CAMERA_FRONT",s))(ui||{});const C=(s,a)=>(e,t,i)=>{const r=i.value;return i.value=function(...n){var l;const c=`[${((l=e.constructor)==null?void 0:l.logName)||""}]`,o=Date.now();let d=[];if(s)try{d=s(n)}catch(p){}V.interface(c,t,...d);const h=r.apply(this,n);return Promise.resolve(h).then(p=>p).catch(p=>p).then(p=>{var b;let u="";const f=p instanceof Error,m=f&&((b=e.constructor)==null?void 0:b.logError);if(a||f){if(m)u=p;else if(f)u=p.message||"";else{if(!a)return;if(p===void 0)u="";else try{u=a(p)}catch(S){}}V.interfaceResult(c,t,!(f&&m),Date.now()-o+"ms",u)}}),h},i},H=s=>s,$a="customVideoProfile",Ka="customScreenProfile",_r={width:1280,height:720,frameRate:30,maxBitrate:2e3},Ja={width:1920,height:1080,frameRate:30,maxBitrate:2600};var pi=(s=>(s[s.ERROR_DEVICE_UNKNOWNERROR=1e4]="ERROR_DEVICE_UNKNOWNERROR",s[s.ERROR_DEVICE_AUDIODEVICE_NOTFOUND=10001]="ERROR_DEVICE_AUDIODEVICE_NOTFOUND",s[s.ERROR_DEVICE_AUDIODEVICE_NOTALLOWED=10002]="ERROR_DEVICE_AUDIODEVICE_NOTALLOWED",s[s.ERROR_DEVICE_AUDIODEVICE_NOTREADABLE=10003]="ERROR_DEVICE_AUDIODEVICE_NOTREADABLE",s[s.ERROR_DEVICE_VIDEODEVICE_NOTFOUND=10004]="ERROR_DEVICE_VIDEODEVICE_NOTFOUND",s[s.ERROR_DEVICE_VIDEODEVICE_NOTALLOWED=10005]="ERROR_DEVICE_VIDEODEVICE_NOTALLOWED",s[s.ERROR_DEVICE_VIDEODEVICE_NOTREADABLE=10006]="ERROR_DEVICE_VIDEODEVICE_NOTREADABLE",s[s.ERROR_SCREENSHARE_NOTSUPPORT=10010]="ERROR_SCREENSHARE_NOTSUPPORT",s[s.ERROR_SCREENSHARE_NOTALLOWED=10011]="ERROR_SCREENSHARE_NOTALLOWED",s[s.ERROR_SCREENSHARE_ENDED=10012]="ERROR_SCREENSHARE_ENDED",s[s.ERROR_SCREENSHARE_NOPERMISSION=10013]="ERROR_SCREENSHARE_NOPERMISSION",s[s.ERROR_SCREENSHARE_SAFARI_INVALIDACCESS=10014]="ERROR_SCREENSHARE_SAFARI_INVALIDACCESS",s[s.ERROR_SCREENSHARE_UNKNOWNERRO=10019]="ERROR_SCREENSHARE_UNKNOWNERRO",s[s.ERROR_DEVICE_NOTALLOWED=10021]="ERROR_DEVICE_NOTALLOWED",s[s.ERROR_DEVICE_NOTSUPPORT=2e4]="ERROR_DEVICE_NOTSUPPORT",s))(pi||{});const Bo={1e4:Ue.AliEngineLocalDeviceExceptionTypeUnknown,2e4:Ue.AliEngineLocalDeviceExceptionTypeUnknown,10001:Ue.AliEngineLocalDeviceExceptionTypeMicNotAvailable,10002:Ue.AliEngineLocalDeviceExceptionTypeMicAuthFail,10003:Ue.AliEngineLocalDeviceExceptionTypeMicOpenFail,10005:Ue.AliEngineLocalDeviceExceptionTypeCameraAuthFail,10004:Ue.AliEngineLocalDeviceExceptionTypeVideoDeviceException,10006:Ue.AliEngineLocalDeviceExceptionTypeCameraOpenFail,10010:Ue.AliEngineLocalDeviceExceptionTypeDisplayException,10011:Ue.AliEngineLocalDeviceExceptionTypeDisplayException,10012:Ue.AliEngineLocalDeviceExceptionTypeDisplayException,10013:Ue.AliEngineLocalDeviceExceptionTypeDisplayException,10014:Ue.AliEngineLocalDeviceExceptionTypeDisplayException,10019:Ue.AliEngineLocalDeviceExceptionTypeDisplayException};var ot=(s=>(s.CREATE_ENGINE="create_engine",s.JOIN="join",s.WANT_INSERT_PUB_TASK="wantInsertPubTask",s.INSERT_PUB_TASK="InsertPubTask",s.HANDLE_PUB_TASK="HandlePubTask",s.RECV_NOTIFY_PUBLISH="RecvNotifyPublish",s.INSERT_SUB_TASK="InsertSubTask",s.HANDLE_SUB_TASK="HandleSubTask",s.FIRST_REMOTE="first_remote",s))(ot||{}),ht=(s=>(s.START="start",s.SEND_SIG="send_sig",s.RECV_RST="recv_rst",s.END="end",s.RECEIVED="received",s.DECODED="decoded",s.PLAYED="played",s))(ht||{}),U=(s=>(s[s.ERR_JOIN_ALREADY_JOINED=16843521]="ERR_JOIN_ALREADY_JOINED",s[s.ERR_JOIN_BAD_APPID=33620481]="ERR_JOIN_BAD_APPID",s[s.ERR_JOIN_INVALID_APPID=33620482]="ERR_JOIN_INVALID_APPID",s[s.ERR_JOIN_BAD_CHANNEL=33620484]="ERR_JOIN_BAD_CHANNEL",s[s.ERR_JOIN_INVALID_CHANNEL=33620483]="ERR_JOIN_INVALID_CHANNEL",s[s.ERR_JOIN_BAD_TOKEN=33620485]="ERR_JOIN_BAD_TOKEN",s[s.ERR_JOIN_TIMEOUT=16908804]="ERR_JOIN_TIMEOUT",s[s.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD=16974081]="ERR_JOIN_ERR_JOIN_BAD_PARAMBAD",s[s.ERR_JOIN_CHANNEL_FAILED=16974338]="ERR_JOIN_CHANNEL_FAILED",s[s.ERR_LOG_ALREADY_INIT=16974085]="ERR_LOG_ALREADY_INIT",s[s.ERR_LOG_ROOT_PATH_ERROR=16974086]="ERR_LOG_ROOT_PATH_ERROR",s[s.ERR_MIC_OPEN_FAIL=17040388]="ERR_MIC_OPEN_FAIL",s[s.ERR_SPEAKER_OPEN_FAIL=17040389]="ERR_SPEAKER_OPEN_FAIL",s[s.ERR_MIC_INTERRUPT=17040390]="ERR_MIC_INTERRUPT",s[s.ERR_SPEAKER_INTERRUPT=17040391]="ERR_SPEAKER_INTERRUPT",s[s.ERR_MIC_AUTH_FAIL=17040392]="ERR_MIC_AUTH_FAIL",s[s.ERR_MIC_NOT_AVAILABLE=17040393]="ERR_MIC_NOT_AVAILABLE",s[s.ERR_SPEAKER_NOT_AVAILABLE=17040400]="ERR_SPEAKER_NOT_AVAILABLE",s[s.ERR_CAMERA_OPEN_FAIL=17039620]="ERR_CAMERA_OPEN_FAIL",s[s.ERR_CAMERA_AUTH_FAIL=17039621]="ERR_CAMERA_AUTH_FAIL",s[s.ERR_CAMERA_INTERRUPT=17039622]="ERR_CAMERA_INTERRUPT",s[s.ERR_CAMERA_NOT_AVAILABLE=17039623]="ERR_CAMERA_NOT_AVAILABLE",s[s.ERR_VIDEO_DISPLAY_OPEN_FAIL=17039873]="ERR_VIDEO_DISPLAY_OPEN_FAIL",s[s.ERR_VIDEO_DISPLAY_INTERRUPT=1064992]="ERR_VIDEO_DISPLAY_INTERRUPT",s[s.ERR_ICE_CONNECTION_CONNECT_FAIL=17105409]="ERR_ICE_CONNECTION_CONNECT_FAIL",s[s.ERR_ICE_CONNECTION_RECONNECT_FAI=17105410]="ERR_ICE_CONNECTION_RECONNECT_FAI",s[s.ERR_ICE_CONNECTION_MOBILITY_FAIL=17105411]="ERR_ICE_CONNECTION_MOBILITY_FAIL",s[s.ERR_ICE_CONNECTION_HEARTBEAT_TIMEOUT=16908812]="ERR_ICE_CONNECTION_HEARTBEAT_TIMEOUT",s[s.ERR_LATENCY_LIVE_COMMUNICATION_FAILED=17235971]="ERR_LATENCY_LIVE_COMMUNICATION_FAILED",s[s.ERR_LATENCY_LIVE_MEIDASETTING_FAILED=17235972]="ERR_LATENCY_LIVE_MEIDASETTING_FAILED",s[s.ERR_LATENCY_LIVE_NONE_BROADCASTER=17235973]="ERR_LATENCY_LIVE_NONE_BROADCASTER",s[s.ERR_LATENCY_LIVE_NEED_RESTART=17235974]="ERR_LATENCY_LIVE_NEED_RESTART",s[s.ERR_LATENCY_LIVE_NEED_RESTART_AGAIN_LATER=17235975]="ERR_LATENCY_LIVE_NEED_RESTART_AGAIN_LATER",s[s.ERR_LATENCY_LIVE_SERVICE_UNAVAILABLE=17235976]="ERR_LATENCY_LIVE_SERVICE_UNAVAILABLE",s[s.ERR_LATENCY_LIVE_MEDIACONNECTION_INTERRUPTION=17235977]="ERR_LATENCY_LIVE_MEDIACONNECTION_INTERRUPTION",s[s.ERR_SDK_PUBLISH_INVAILD=16974597]="ERR_SDK_PUBLISH_INVAILD",s[s.ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL=16843782]="ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL",s[s.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED=16843856]="ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED",s[s.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED=16843857]="ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED",s[s.ERR_SDK_PUBLISH_DUAL_STREAM_FAILED=16843858]="ERR_SDK_PUBLISH_DUAL_STREAM_FAILED",s[s.ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED=16843859]="ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED",s[s.ERR_SDK_PUBLISH_SCREEN_SHARE_CONFIG_ERROR=16843860]="ERR_SDK_PUBLISH_SCREEN_SHARE_CONFIG_ERROR",s[s.ERR_SDK_SUBSCRIBE_INVAILD=16974852]="ERR_SDK_SUBSCRIBE_INVAILD",s[s.ERR_SDK_SUBSCRIBE_NOT_JOIN_CHANNEL=16844112]="ERR_SDK_SUBSCRIBE_NOT_JOIN_CHANNEL",s[s.ERR_SDK_SUBSCRIBE_AUDIO_STREAM_FAILED=16844113]="ERR_SDK_SUBSCRIBE_AUDIO_STREAM_FAILED",s[s.ERR_SDK_SUBSCRIBE_VIDEO_STREAM_FAILED=16844114]="ERR_SDK_SUBSCRIBE_VIDEO_STREAM_FAILED",s[s.ERR_SDK_SUBSCRIBE_DUAL_STREAM_FAILED=16844115]="ERR_SDK_SUBSCRIBE_DUAL_STREAM_FAILED",s[s.ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED=16844116]="ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED",s[s.ERR_SDK_SUBSCRIBE_DATA_FAILED=16844117]="ERR_SDK_SUBSCRIBE_DATA_FAILED",s[s.ERR_SDK_SUBSCRIBE_DATA_ERROR=16844118]="ERR_SDK_SUBSCRIBE_DATA_ERROR",s[s.ERR_SDK_INVALID_STATE=16974340]="ERR_SDK_INVALID_STATE",s[s.ERR_INVALID_ARGUMENTS=16974083]="ERR_INVALID_ARGUMENTS",s[s.ERR_SESSION_REMOVED=33620229]="ERR_SESSION_REMOVED",s[s.ERR_SDK_UPDATE_ROLE_CHANNEL=16908801]="ERR_SDK_UPDATE_ROLE_CHANNEL",s[s.ERR_INNER=-1]="ERR_INNER",s[s.ERR_SDK_MPU_TASK_PUBLISH_OK=0]="ERR_SDK_MPU_TASK_PUBLISH_OK",s[s.ERR_SDK_MPU_TASK_STREAM_NOT_FOUND=17825793]="ERR_SDK_MPU_TASK_STREAM_NOT_FOUND",s[s.ERR_SDK_MPU_TASK_STREAM_ALREADY_EXIST=17825794]="ERR_SDK_MPU_TASK_STREAM_ALREADY_EXIST",s[s.ERR_SDK_MPU_TASK_INVALID_PARAM=17825795]="ERR_SDK_MPU_TASK_INVALID_PARAM",s[s.ERR_SDK_MPU_TASK_INTERNAL_ERROR=17825796]="ERR_SDK_MPU_TASK_INTERNAL_ERROR",s[s.ERR_SDK_MPU_TASK_RTMP_SERVER_ERROR=17825797]="ERR_SDK_MPU_TASK_RTMP_SERVER_ERROR",s[s.ERR_SDK_MPU_TASK_RTMP_STREAM_URL_ERROR=17825798]="ERR_SDK_MPU_TASK_RTMP_STREAM_URL_ERROR",s[s.ERR_SDK_MPU_TASK_PUBLISH_TIMEOUT=17825799]="ERR_SDK_MPU_TASK_PUBLISH_TIMEOUT",s[s.ERR_SDK_MPU_TASK_NOT_AUTHORIZED=17825800]="ERR_SDK_MPU_TASK_NOT_AUTHORIZED",s[s.ERR_SDK_CHANNEL_RELAY_STATE_ERROR=18874369]="ERR_SDK_CHANNEL_RELAY_STATE_ERROR",s[s.ERR_SDK_CHANNEL_RELAY_SRC_NOT_ALLOW=18874370]="ERR_SDK_CHANNEL_RELAY_SRC_NOT_ALLOW",s[s.ERR_SDK_CHANNEL_RELAY_JOIN_DEST_FAILED=18874371]="ERR_SDK_CHANNEL_RELAY_JOIN_DEST_FAILED",s[s.ERR_SDK_CHANNEL_RELAY_TOKEN_INVALID=18874372]="ERR_SDK_CHANNEL_RELAY_TOKEN_INVALID",s[s.ERR_SDK_CHANNEL_RELAY_ROLE_ERROR=18874373]="ERR_SDK_CHANNEL_RELAY_ROLE_ERROR",s[s.ERR_SDK_CHANNEL_RELAY_INVALID_PARAM=18874374]="ERR_SDK_CHANNEL_RELAY_INVALID_PARAM",s[s.ERR_SDK_CHANNEL_RELAY_TO_SELF_ERROR=18874375]="ERR_SDK_CHANNEL_RELAY_TO_SELF_ERROR",s))(U||{});class O extends Error{constructor(e,t,i){super(t);g(this,"_code");g(this,"_extra");this._code=e,this._extra=i}static fromRtsError(e){return e instanceof O?e:new O((e==null?void 0:e.errorCode)||-1,(e==null?void 0:e.message)||(e==null?void 0:e.errorCodeName)||"rts error",e)}static fromError(e,t=-1,i=""){return new O(t,(e==null?void 0:e.message)||(e==null?void 0:e.reason)||i||"error",e)}get code(){return this._code}set code(e){this._code=e}get reason(){return this.message}get extra(){return this._extra}}function Ga(s){var a;if(((a=s==null?void 0:s.nodeName)==null?void 0:a.toLowerCase())==="video")return s.setAttribute("playsinline",""),s;if(typeof s=="string"){let e=document.getElementById(s);if(e){if(e.nodeName.toLocaleLowerCase()==="video")return e.setAttribute("playsinline",""),e;throw new O(U.ERR_INVALID_ARGUMENTS,"element should be HtmlVideoElement")}throw new O(U.ERR_INVALID_ARGUMENTS,"element not founded")}throw new O(U.ERR_INVALID_ARGUMENTS,"element id should be string")}function wr(s){var e;const a=[];if(Array.isArray(s))s.forEach(t=>{try{a.push(Ga(t))}catch(i){}});else if(typeof s=="string"||((e=s==null?void 0:s.nodeName)==null?void 0:e.toLowerCase())==="video")try{a.push(Ga(s))}catch(t){}return a}function xt(s){return new Promise(a=>setTimeout(a,s))}function qa(s,a,e=1e3,t=i=>!0){return I(this,null,function*(){let i=0;for(;i<a;)try{return yield s(i)}catch(r){if(i++,i>=a||!t(r))throw r||void 0;yield new Promise(n=>setTimeout(n,e))}})}function Er(s,a){let e=a;return typeof window.__ali_prefer_media_server=="string"&&window.__ali_prefer_media_server!==""&&(e=window.__ali_prefer_media_server),e?`${s}&ali_prefer_media_server=${e}`:s}function ri(s,a){var e;try{const{archCfgs:t}=s;if(!t||!Array.isArray(t))return;const i=t.find(r=>r.arch==="grtn");return i?(e=i.user_specified)==null?void 0:e[a]:void 0}catch(t){return}}function si(s,a){try{const{config:e}=s;return e?e==null?void 0:e[a]:void 0}catch(e){return}}const Xa=(s,a,e=!1)=>{const t=()=>(s.muted=!0,Promise.race([xt(500),s._playPromise||Promise.resolve()]).catch(()=>{}).then(()=>{let i;return e&&s.srcObject===a?i=Promise.resolve():(s.load(),s.srcObject=a,i=s.play(),s._playPromise=i),i}));return new Promise(i=>{if(X.AliRTS.BrowserUtil.isMicroMessenger){const r=window.top!==window.self,n=window.WeixinJSBridge||window.top.WeixinJSBridge;n?n.invoke("getNetworkType",{},()=>{i(t())}):(r?window.top.document:document).addEventListener("WeixinJSBridgeReady",()=>{n.invoke("getNetworkType",{},()=>{i(t())})}),setTimeout(()=>{i(t())},1e3)}else setTimeout(()=>{i(t())},0)})},_t=s=>{Promise.race([xt(100),s._playPromise||Promise.resolve()]).catch(()=>{}).then(()=>{s.srcObject=null,s._playPromise=void 0})};var Tr=(s=>(s[s.AliEngineDataMsgNone=0]="AliEngineDataMsgNone",s[s.AliEngineDataMsgMusicProgress=1]="AliEngineDataMsgMusicProgress",s[s.AliEngineDataMsgCustom=2]="AliEngineDataMsgCustom",s))(Tr||{});class Bi{constructor(a,e,t,i=0){g(this,"msgType");g(this,"msgId");g(this,"protocolVersion");g(this,"tlvVersion");this.msgType=a,this.msgId=e,this.protocolVersion=t,this.tlvVersion=i}build(){const a=new Uint8Array(4);return a.set(Uint8Array.from([this.protocolVersion,this.tlvVersion<<4|15&this.msgType]),0),a.set(Uint16Array.from([this.msgId]),2),a}static parse(a){const e=new DataView(a),t=e.getUint8(0),i=e.getUint8(1)>>4,r=15&e.getUint8(1),n=e.getUint16(2);return new Bi(r,n,t,i)}}class Hi{constructor(a,e,t){g(this,"_byteArray");if(this._byteArray=new Uint8Array(0),a!==void 0&&e!==void 0&&t!==void 0){const i=new Bi(a,e,t).build();this._byteArray=new Uint8Array(i.byteLength+this._byteArray.byteLength),this._byteArray.set(i,0)}}write(a,e){const t=this._byteArray,i=new ArrayBuffer(5),r=new DataView(i);r.setUint8(0,a),r.setUint32(1,e.byteLength);const n=new Uint8Array(t.byteLength+5+e.byteLength);n.set(t,0),n.set(new Uint8Array(i),t.byteLength),n.set(new Uint8Array(e),t.byteLength+5),this._byteArray=n}static parse(a){const e={},t=new DataView(a);let i=0;for(;i<a.byteLength;){const r=t.getUint8(i),n=t.getUint32(i+1);if(!(i+5+n<=a.byteLength))break;{const c=a.slice(i+5,i+5+n);e[r]=c,i+=5+n}}return e}get buffer(){return this._byteArray.buffer}}class mi{constructor(a=0,e=!0,t=1,i=!1,r=0,n=!1,c=!1,o=3){g(this,"_fin",!0);g(this,"_hasExtension",!1);g(this,"_version",0);g(this,"_frameType",1);g(this,"_isEncrypted",!1);g(this,"_isCompressed",!1);g(this,"_signalType",3);g(this,"_payloadLength",0);this._fin=e,this._hasExtension=i,this._version=r,this._frameType=t,this._isEncrypted=n,this._isCompressed=c,this._signalType=o,this._payloadLength=a}get fin(){return this._fin}get hasExtension(){return this._hasExtension}get version(){return this._version}get frameType(){return this._frameType}get isEncrypted(){return this._isEncrypted}get isCompressed(){return this._isCompressed}get signalType(){return this._signalType}get payloadLength(){return this._payloadLength}toBuffer(){const a=new ArrayBuffer(4),e=new DataView(a);return e.setUint8(0,(this._fin?1:0)<<7|(this._hasExtension?1:0)<<6|this._version<<4|15&this._frameType),e.setUint8(1,(this._isEncrypted?1:0)<<7|(this._isCompressed?1:0)<<6|15&this._signalType),e.setUint16(2,this._payloadLength),a}static parse(a){const e=new DataView(a),t=e.getUint8(0)>>7==1,i=(64&e.getUint8(0))>>6==1,r=(48&e.getUint8(0))>>4,n=15&e.getUint8(0),c=e.getUint8(1)>>7==1,o=(64&e.getUint8(1))>>6==1,d=15&e.getUint8(1),h=e.getUint16(2);return new mi(h,t,n,i,r,c,o,d)}}class Fi{constructor(a,e){g(this,"_body");g(this,"_header",new mi);this._header=a,this._body=e}get header(){return this._header}get isFin(){return this._header.fin}get body(){return this._body}toGRTNBuffer(){const a=this._header.toBuffer(),e=this._body,t=new ArrayBuffer(4);new DataView(t).setUint8(0,1*Math.pow(2,4));const i=new Uint8Array(t.byteLength+a.byteLength+e.byteLength);return i.set(new Uint8Array(t),0),i.set(new Uint8Array(a),t.byteLength),i.set(new Uint8Array(e),t.byteLength+a.byteLength),i.buffer}static parse(a){const e=a.slice(0,4),t=mi.parse(e);let i=new ArrayBuffer(0);return a.byteLength-4>=t.payloadLength&&(i=a.slice(4,4+t.payloadLength)),new Fi(t,i)}}const Ir=s=>{const a=s.byteLength,e=new DataView(s);let t=0;for(let i=0;i<a;i++)t=256*t+e.getUint8(i);return t};let Ya=0;class Vt{constructor(a,e=0,t=0,i=0){g(this,"data");g(this,"networkTime");g(this,"futureOrProgress");g(this,"type");this.data=a,this.type=e,this.networkTime=t,this.futureOrProgress=i}toBuffer(){const a=new Hi(0,0,0);a.write(1,Uint8Array.from([0]).buffer),a.write(2,Uint16Array.from([0]).buffer),Ya++,a.write(3,Uint32Array.from([Ya]).buffer);const e=new Hi;return e.write(1,Uint8Array.from([0]).buffer),e.write(2,Uint8Array.from([this.type]).buffer),e.write(3,Uint32Array.from([this.futureOrProgress]).buffer),e.write(4,Uint32Array.from([Number(this.networkTime>>32&4294967295),Number(4294967295&this.networkTime)]).buffer),e.write(5,this.data),a.write(30,e.buffer),a.buffer}static parse(a){if(!a||a.byteLength<4)return;Bi.parse(a.slice(0,4));const e=Hi.parse(a.slice(4))[30];if(!e)return;const t=Hi.parse(e),i=t[2],r=t[3],n=t[4],c=t[5];return c.byteLength!==0?new Vt(c,Ir(i),Ir(n),Ir(r)):void 0}}var Ho=Object.defineProperty,Fo=Object.getOwnPropertyDescriptor,De=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?Fo(a,e):a,n=s.length-1;n>=0;n--)(i=s[n])&&(r=(t?i(a,e,r):i(r))||r);return t&&r&&Ho(a,e,r),r};class gi extends se{constructor(){super();g(this,"_state");g(this,"time");this._state=ie.AliRtcStatePublishIdle,this.time=Date.now()}get state(){return this._state}setState(e){const t=this._state,i=this.time;this._state=e,this.time=Date.now(),this.emit("change",t,e,Math.floor((this.time-i)/1e3))}}const Ce=(Tt=class extends za{constructor(e){const{rtsManager:t,localStreamManager:i,slsReporter:r,signalingManager:n,audioVolumeIndicationInterval:c,parameter:o}=e;super("","",t,c);g(this,"_url","");g(this,"joinTime",0);g(this,"publishPromise",Promise.resolve({traceId:"",l1ip:void 0}));g(this,"previewElements",[]);g(this,"screenPreviewElements",[]);g(this,"streamManager");g(this,"dc");g(this,"streamTracks");g(this,"publishId",dt());g(this,"signalingManager");g(this,"shouldPublish",!1);g(this,"traceId","");g(this,"monitorTimerId");g(this,"monitorDataCache",{});g(this,"trackTraceIdMap",{});g(this,"candidateDataCache",[]);g(this,"pcMediaStatsMap",{});g(this,"slsReporter");g(this,"audioPubState");g(this,"videoPubState");g(this,"videoSmallPubState");g(this,"screenPubState");g(this,"dataPubState");g(this,"parameter",{});g(this,"onTrackEnd",e=>{this.emit(e)});this.streamManager=i,this.signalingManager=n,this.slsReporter=r,this.parameter=o,this.streamManager.on("trackended",d=>{this.onTrackEnd(d)}),this.streamManager.on("publishupdate",()=>{this.publishUpdate()}),this.audioPubState=new gi,this.audioPubState.on("change",(d,h,l)=>{this.emit("audioPublishStateChanged",d,h,l)}),this.videoPubState=new gi,this.videoPubState.on("change",(d,h,l)=>{this.emit("videoPublishStateChanged",d,h,l)}),this.videoSmallPubState=new gi,this.videoSmallPubState.on("change",(d,h,l)=>{this.emit("dualStreamPublishStateChanged",d,h,l)}),this.screenPubState=new gi,this.screenPubState.on("change",(d,h,l)=>{this.emit("screenPublishStateChanged",d,h,l)}),this.dataPubState=new gi,this.dataPubState.on("change",(d,h,l)=>{this.emit("dataPublishStateChanged",d,h,l)}),this.startStreamMonitor()}get url(){return this._url}set url(e){this._url=e,this.rtsManager.updateAuth(e)}get joined(){return!!this.uid}get isPublishing(){return this.rtsManager.publishingTracks.length>0}get publishStreams(){return this.streamManager.publishStreams}get cameraTrack(){return this.streamManager.cameraStreamInfo.originVideoTrack}get screenTrack(){return this.streamManager.screenStreamInfo.originVideoTrack}get audioTrack(){return this.streamManager.cameraStreamInfo.originAudioTrack}get hasCamera(){return!!this.streamManager.cameraStreamInfo.originVideoTrack}get hasMicrophone(){return!!this.streamManager.cameraStreamInfo.originAudioTrack}get hasScreenShare(){return!!this.streamManager.screenStreamInfo.originVideoTrack}get hasCameraTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:r})=>i==="video"&&t&&r===M.VideoLarge))}get hasCameraDualTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:r})=>i==="video"&&t&&r===M.VideoSmall))}get hasScreenTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:r})=>i==="video"&&t&&r===M.Screen))}get hasAudioTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:r})=>i==="audio"&&t&&r===M.Audio))}get cameraDirection(){var e,t;return(t=(e=this.streamManager.cameraStreamInfo)==null?void 0:e.cameraVideoConstraints)==null?void 0:t.facingMode}get audioCaptureDisabled(){return this.streamManager.audioCaptureDisabled}get cameraCaptureDisabled(){return this.streamManager.cameraCaptureDisabled}get publishLocalVideoStreamEnabled(){return this.streamManager.publishLocalVideoStreamEnabled}get publishLocalAudioStreamEnabled(){return this.streamManager.publishLocalAudioStreamEnabled}get publishLocalScreenStreamEnabled(){return this.streamManager.publishLocalScreenStreamEnabled}setPublishLocalAudioStreamEnabled(e){this.streamManager.publishLocalAudioStreamEnabled=e}setPublishLocalVideoStreamEnabled(e){this.streamManager.publishLocalVideoStreamEnabled=e}setPublishLocalScreenStreamEnabled(e){this.streamManager.publishLocalScreenStreamEnabled=e}initInfo(e,t){this.joinTime=Date.now(),this.rtsManager.localJoinTime=this.joinTime,this.setUserInfo(e.userId,e.userId),this.url=t,this.callId=e.sessionId||nt.createCallid(),this.updatePubId()}setVideoProfile(e){return I(this,null,function*(){yield this.streamManager.setVideoProfile($a,e)})}setVideoContentHint(e){this.streamManager.setVideoContentHint(e)}setScreenContentHint(e){this.streamManager.setScreenContentHint(e)}setAudioProfile(e){return I(this,null,function*(){yield this.streamManager.setAudioProfile(e)})}setScreenProfile(e){return I(this,null,function*(){yield this.streamManager.setScreenProfile(Ka,e)})}setCameraDirection(e){if(e===ui.CAMERA_FRONT)this.streamManager.setCameraVideoConstraints({facingMode:"user"});else{if(e!==ui.CAMERA_REAR)throw new O(U.ERR_CAMERA_OPEN_FAIL,`camera direction set to ${e} failed`);this.streamManager.setCameraVideoConstraints({facingMode:"environment"})}}setCameraDeviceId(e){this.streamManager.setCameraVideoConstraints({deviceId:e})}muteLocalCamera(e){this.streamManager.setCameraMuted(e),this.slsReporter.reportMute(this.callId,!e,"video")}muteLocalMic(e){this.streamManager.setAudioMuted(e),this.slsReporter.reportMute(this.callId,!e,"audio")}muteLocalScreen(e){this.streamManager.setScreenMuted(e),this.slsReporter.reportMute(this.callId,!e,"screen")}setMicrophoneDeviceId(e){this.streamManager.setMicAudioConstraints({deviceId:e})}setMicrophoneConstraints(e){this.streamManager.setMicAudioConstraints(e)}updatePubId(){this.publishId=dt()}clearPublishState(){this.streamTracks=void 0}leave(){return I(this,null,function*(){this.shouldPublish=!1,this.isPublishing&&(yield this.unPublish()),this.joinTime=0,this.dc=void 0})}clear(){return I(this,null,function*(){Yr(Tt.prototype,this,"clear").call(this),this.stopPreview(),this.resetPreviewElements(),this.resetSecondayPreviewElements(),this.clearStream(),yield this.leave(),this.streamManager.cameraCaptureDisabled=!1})}resetElement(e){this.previewElements.includes(e)&&(_t(e),this.previewElements.splice(this.previewElements.indexOf(e),1)),this.screenPreviewElements.includes(e)&&(_t(e),this.screenPreviewElements.splice(this.screenPreviewElements.indexOf(e),1))}setPreviewElement(e){const{videoElement:t,screen:i}=e;i?this.screenPreviewElements.includes(t)||(this.screenPreviewElements.push(t),this.preview(e)):this.previewElements.includes(t)||(this.previewElements.push(t),this.preview(e))}startDefaultCameraAndMic(e){return I(this,null,function*(){const{hasCamera:t,cameraCaptureDisabled:i,publishLocalVideoStreamEnabled:r}=this,{hasMicrophone:n,audioCaptureDisabled:c,publishLocalAudioStreamEnabled:o}=this,d=!t&&!e&&!i&&r,h=!n&&!c&&o;try{d&&h?yield this.startCameraAndMic():d?yield this.startCameraCapture():h&&(yield this.startAudioCapture())}catch(l){const p=l.errorCode;let u=U.ERR_CAMERA_OPEN_FAIL;throw d?((p===pi.ERROR_DEVICE_VIDEODEVICE_NOTALLOWED||pi.ERROR_DEVICE_NOTALLOWED)&&(u=U.ERR_CAMERA_AUTH_FAIL),u=U.ERR_CAMERA_OPEN_FAIL):((p===pi.ERROR_DEVICE_AUDIODEVICE_NOTALLOWED||pi.ERROR_DEVICE_NOTALLOWED)&&(u=U.ERR_MIC_AUTH_FAIL),u=U.ERR_MIC_OPEN_FAIL),new O(u,`auto open fail: ${l.message}`)}})}setViewConfig(e,t){if(e){if(![oe.AliRtcVideoTrackCamera,oe.AliRtcVideoTrackScreen].includes(t))throw new O(U.ERR_INVALID_ARGUMENTS,"set view config invalid track",{track:t});e.forEach(i=>{this.setPreviewElement({videoElement:i,screen:t===oe.AliRtcVideoTrackScreen})})}else t===oe.AliRtcVideoTrackCamera?this.stopPreview({primary:!0,screen:!1}):this.stopPreview({primary:!1,screen:!0})}startCameraCapture(){return I(this,null,function*(){return this.streamManager.cameraCaptureDisabled=!1,yield this.createLocalStream({video:!0})})}stopCameraCapture(){return I(this,null,function*(){this.streamManager.cameraCaptureDisabled=!0,yield this.stopLocalStream({video:!0})})}startAudioCapture(){return I(this,null,function*(){return this.streamManager.audioCaptureDisabled=!1,yield this.createLocalStream({audio:!0})})}stopAudioCapture(){return I(this,null,function*(){this.streamManager.audioCaptureDisabled=!0,yield this.stopLocalStream({audio:!0})})}startCameraAndMic(){return I(this,null,function*(){return this.streamManager.cameraCaptureDisabled=!1,this.streamManager.audioCaptureDisabled=!1,yield this.createLocalStream({video:!0,audio:!0})})}preview(e){return I(this,null,function*(){const{videoElement:t,screen:i}=e!=null?e:{};try{let r=i?this.streamManager.screenStreamInfo.previewStream:this.streamManager.cameraStreamInfo.previewStream;if(!t)throw new O(U.ERR_INVALID_ARGUMENTS,"no video element found",{videoElement:t});return r?(Xa(t,r.mediaStream),this.setPreviewElement(e),r.mediaStream):void V.info(`[${Tt.logName}]`,"preview no stream founded")}catch(r){const n=U.ERR_INNER;throw O.fromError(r,n,"preview failed")}})}previewAll(e){return I(this,null,function*(){const{primary:t=!0,screen:i=!0}=e!=null?e:{};if(t&&this.previewElements.length)for(let r=0;r<this.previewElements.length;r++){const n=this.previewElements[r];yield this.preview({videoElement:n})}if(i&&this.screenPreviewElements.length)for(let r=0;r<this.screenPreviewElements.length;r++){const n=this.screenPreviewElements[r];yield this.preview({videoElement:n,screen:!0})}})}stopPreview(e){const{videoElement:t,primary:i=!0,screen:r=!0}=e||{};if(t){const n=this.previewElements.findIndex(c=>c===t);if(n>=0)this.previewElements.splice(n,1),_t(t);else{const c=this.screenPreviewElements.findIndex(o=>o===t);c>=0&&(this.screenPreviewElements.splice(c,1),_t(t))}}else i&&(this.previewElements.forEach(n=>{_t(n)}),this.previewElements=[]),r&&(this.screenPreviewElements.forEach(n=>{_t(n)}),this.screenPreviewElements=[])}resumePublish(){return I(this,null,function*(){this.shouldPublish&&(yield this.startPublish(!0))})}createLocalStream(e){return I(this,null,function*(){try{if(e.video)for(let i=0;i<this.previewElements.length;i++){const r=this.previewElements[i];_t(r)}else if(e.screen)for(let i=0;i<this.screenPreviewElements.length;i++){const r=this.screenPreviewElements[i];_t(r)}const t=yield this.streamManager.createLocalStream(e);return t!=null&&t.audioTrack&&this.audioVolumeIndicationInterval>0&&this.audioLevelMonitor.start(t.audioTrack,this.audioVolumeIndicationInterval),e.video?this.previewAll({primary:!0}):e.screen&&this.previewAll({screen:!0}),t}catch(t){const i=Bo[t.errorCode];throw i&&(e.audio?this.emit("localDeviceException",At.AliEngineLocalDeviceTypeMic,i,""):e.video?this.emit("localDeviceException",At.AliEngineLocalDeviceTypeCamera,i,""):e.screen?this.emit("localDeviceException",At.AliEngineLocalDeviceTypeDisplay,i,""):this.emit("localDeviceException",At.AliEngineLocalDeviceTypeUnknown,i,"")),t}})}stopLocalStream(e){return I(this,null,function*(){e.audio&&this.audioLevelMonitor.stop(),yield this.streamManager.stopLocalStream(e)})}compareAndPublish(e,t,i){return I(this,null,function*(){var n,c;if(!e&&!t)return;if(e&&!t){const o={};return i===M.Audio?o.audio=!0:i===M.VideoLarge||i===M.VideoSmall?(o.video=!0,o.vMsid=i):i===M.Screen&&(o.screen=!0),yield this.publishDeleteTracks(o)}const r={};if(t!=null&&t.hasVideo&&(r.isScreen=i===M.Screen,r.vMsid=i),t!=null&&t.hasAudio&&(r.aMsid=i),!e&&t)return yield this.publishAdd(t,r,!1);if(e&&t&&e.trackId!==(((n=t.videoTrack)==null?void 0:n.id)||((c=t.audioTrack)==null?void 0:c.id)))return yield this.publishReplace(t,r)})}reportAudioProfile(){const e=this.streamManager.cameraStreamInfo.audioProfile||"standard",t=X.AliRTS.AudioProfileMap.get(e);this.slsReporter.reportPublishProfile(M.Audio,{a_profile:e,bits:(t==null?void 0:t.maxBitrate)||0,samplerate:(t==null?void 0:t.sampleRate)||0,channel:(t==null?void 0:t.channelCount)||0})}reportVideoProfile(){const e=this.streamManager.cameraStreamInfo.videoProfile||"",t=X.AliRTS.VideoProfileMap.get(e);t&&this.slsReporter.reportPublishProfile(M.VideoLarge,{v_profile:e,wdth:(t==null?void 0:t.width)||0,hgt:(t==null?void 0:t.height)||0,fps:(t==null?void 0:t.frameRate)||0,bitrate:(t==null?void 0:t.maxBitrate)||0})}reportScreenProfile(){const e=this.streamManager.screenStreamInfo.videoProfile||"",t=X.AliRTS.VideoProfileMap.get(e);t&&this.slsReporter.reportPublishProfile(M.Screen,{v_profile:e,wdth:(t==null?void 0:t.width)||0,hgt:(t==null?void 0:t.height)||0,fps:(t==null?void 0:t.frameRate)||0,bitrate:(t==null?void 0:t.maxBitrate)||0})}updateDataChannel(e){var t;e&&(((t=this.dc)==null?void 0:t.datachannel)!==(e==null?void 0:e.datachannel)&&(e.ssrc=`web_${Date.now()}_${(e==null?void 0:e.datachannel.id)||"0"}`),this.dc=e,this.dc.datachannel&&(this.dc.datachannel.binaryType="arraybuffer"))}publishDataChannel(){return I(this,null,function*(){if(this.dataPubState.state!==ie.AliRtcStatePublishing){this.dataPubState.setState(ie.AliRtcStatePublishing);try{const e=yield this.rtsManager.publishAddDataChannel(this.url);e?(this.updateDataChannel(e),this.dataPubState.setState(ie.AliRtcStatePublished)):(this.dataPubState.setState(ie.AliRtcStateNoPublish),this.emit("publishDataError",new O(U.ERR_INNER,"publishDataError")))}catch(e){V.error("[LocalUser]","publishDataChannel error",e),this.dataPubState.setState(ie.AliRtcStateNoPublish)}}})}startPublish(){return I(this,arguments,function*(e=!1,t=yt.MANUAL){var d;if(!this.joined)return;this.shouldPublish=!0;const i=this.streamManager.publishStreams,{audio:r,video:n,videoSmall:c,screen:o}=i;if(r||n||c||o){this.createCallId();try{const h=new Date().getTime();r&&this.audioPubState.setState(ie.AliRtcStatePublishing),n&&this.videoPubState.setState(ie.AliRtcStatePublishing),c&&this.videoSmallPubState.setState(ie.AliRtcStatePublishing),o&&this.screenPubState.setState(ie.AliRtcStatePublishing),this.publishPromise=this.rtsManager.publish(this.url,this.callId,e,t);const{traceId:l,l1ip:p}=yield this.publishPromise;this.streamTracks=this.rtsManager.publishingTracks,this.traceId=l;const u={type:Lt.Add,userid:this.userId,sessionid:"",displayname:this.name,pubid:this.publishId,resume:e,subscribe:{signal:"",pullstreamurl:this.url},l1ip:this.parameter.reportL1IP?p:void 0,callid:this.callId,tracks:this.streamTracks,traceid:l};(d=this.parameter.data)!=null&&d.enablePubDataChannel&&this.publishDataChannel().then(()=>{this.syncPublishToRoomServer(u,i,h)}),r&&(this.trackTraceIdMap[M.Audio]=l,this.reportAudioProfile()),c&&(this.trackTraceIdMap[M.VideoSmall]=l),n&&(this.trackTraceIdMap[M.VideoLarge]=l,this.reportVideoProfile()),o&&(this.trackTraceIdMap[M.Screen]=l,this.reportScreenProfile()),yield this.syncPublishToRoomServer(u,i,h),r&&this.audioPubState.setState(ie.AliRtcStatePublished),n&&this.videoPubState.setState(ie.AliRtcStatePublished),c&&this.videoSmallPubState.setState(ie.AliRtcStatePublished),o&&this.screenPubState.setState(ie.AliRtcStatePublished)}catch(h){throw r&&this.audioPubState.setState(ie.AliRtcStateNoPublish),n&&this.videoPubState.setState(ie.AliRtcStateNoPublish),c&&this.videoSmallPubState.setState(ie.AliRtcStateNoPublish),o&&this.screenPubState.setState(ie.AliRtcStateNoPublish),h}}else V.event(`[${Tt.logName}]`,"startPublish no stream founded")})}updateStreams(){return I(this,null,function*(){yield this.streamManager.updateStreams()})}publishUpdate(e){return I(this,null,function*(){var n,c,o,d,h,l;if(V.info(`[${Tt.logName}]`,"publishUpdate",e||"-",this.shouldPublish),!this.shouldPublish)return;if(!this.rtsManager.isConnecting&&!this.rtsManager.isConnected)return void(yield this.startPublish());yield this.publishPromise;const t=this.streamManager.publishStreams;let i;const r=new Date().getTime();try{const p=(n=this.streamTracks)==null?void 0:n.find(({ssrc:w,type:y,msid:A})=>y==="audio"&&w&&A===M.Audio),u=yield this.compareAndPublish(p,t.audio,M.Audio);u&&(i=u);const f=(c=this.streamTracks)==null?void 0:c.find(({ssrc:w,type:y,msid:A})=>y==="video"&&w&&A===M.VideoLarge),m=yield this.compareAndPublish(f,t.video,M.VideoLarge);m&&(i=m);const b=(o=this.streamTracks)==null?void 0:o.find(({ssrc:w,type:y,msid:A})=>y==="video"&&w&&A===M.VideoSmall),S=yield this.compareAndPublish(b,t.videoSmall,M.VideoSmall);S&&(i=S);const v=(d=this.streamTracks)==null?void 0:d.find(({ssrc:w,type:y,msid:A})=>y==="video"&&w&&A===M.Screen),_=yield this.compareAndPublish(v,t.screen,M.Screen);if(_&&(i=_),!i){if(!(e===yt.RECONNECT&&this.rtsManager.publishingTracks.length>0))return;{if((h=this.parameter.data)!=null&&h.enablePubDataChannel){const A=this.rtsManager.getDatachannelByMsid({url:this.url,msid:M.Data});this.updateDataChannel(A)}const w=this.rtsManager.publishingTracks.find(({type:A})=>A==="video"),y=this.rtsManager.publishingTracks.find(({type:A})=>A==="audio");(w||y)&&(yield this.rtsManager.waitPublishSender(this.url,!w,w?w.msid:y==null?void 0:y.msid)),i={type:Lt.Add,userid:this.userId,sessionid:"",displayname:this.name,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.rtsManager.publishingTracks,traceid:this.traceId}}}(l=this.parameter.data)!=null&&l.enablePubDataChannel&&!this.dc&&(yield this.publishDataChannel()),yield this.syncPublishToRoomServer(i,t,r)}catch(p){const{code:u}=p!=null?p:{},f=this.url;throw u===403&&f&&(yield this.refreshPushStreamUrl(),i=yield this.publishUpdate()),p}return i})}syncPublishToRoomServer(e,t,i){return I(this,null,function*(){var o;if(!e)throw new O(U.ERR_INNER,"sync publish to room server failed because no publishInfo");let r=e;if(this.dc){const c=e,{tracks:d}=c,h=jt(c,["tracks"]);r=vt(G({},h),{tracks:[...d,{type:"data",msid:M.Data,ssrc:((o=this.dc)==null?void 0:o.ssrc)||"web_sophon_data",codec:"text"}]})}const n=yield this.signalingManager.publish(r);e.signaltid=n.tid})}refreshPushStreamUrl(){return I(this,null,function*(){const e=new O(U.ERR_INNER,"refresh push stream url error"),t=this.url;if(!t)throw e;const i=yield this.signalingManager.refreshUrl({pushstreamurl:t});if(!(i!=null&&i.pushstreamurl))throw e;this.url=i.pushstreamurl})}publishAdd(e,t,i=!1,r=0){return I(this,null,function*(){this.createCallId();const n=(t==null?void 0:t.aMsid)===M.Audio,c=(t==null?void 0:t.vMsid)===M.VideoLarge,o=(t==null?void 0:t.vMsid)===M.VideoSmall,d=(t==null?void 0:t.vMsid)===M.Screen;n&&this.audioPubState.setState(ie.AliRtcStatePublishing),c&&this.videoPubState.setState(ie.AliRtcStatePublishing),o&&this.videoSmallPubState.setState(ie.AliRtcStatePublishing),d&&this.screenPubState.setState(ie.AliRtcStatePublishing);try{const h=yield this.rtsManager.publishAdd(this.url,e,this.callId,t,!1,!0);n&&(this.audioPubState.setState(ie.AliRtcStatePublished),this.reportAudioProfile(),this.trackTraceIdMap[M.Audio]=h),c&&(this.videoPubState.setState(ie.AliRtcStatePublished),this.reportVideoProfile(),this.trackTraceIdMap[M.VideoLarge]=h),o&&(this.videoSmallPubState.setState(ie.AliRtcStatePublished),this.trackTraceIdMap[M.VideoSmall]=h),d&&(this.screenPubState.setState(ie.AliRtcStatePublished),this.reportScreenProfile(),this.trackTraceIdMap[M.Screen]=h),this.streamTracks=this.rtsManager.publishingTracks;const l={type:Lt.Add,userid:this.userId,sessionid:"",displayname:this.name,pubid:this.publishId,resume:i,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.streamTracks,traceid:h};return this.reportSelfDeviceStatus(),this.monitorTimerId||this.startStreamMonitor(),l}catch(h){let l=U.ERR_SDK_PUBLISH_INVAILD;if(n&&(this.audioPubState.setState(ie.AliRtcStateNoPublish),l=U.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED),c&&(this.videoPubState.setState(ie.AliRtcStateNoPublish),l=U.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED),o&&(this.videoSmallPubState.setState(ie.AliRtcStateNoPublish),l=U.ERR_SDK_PUBLISH_DUAL_STREAM_FAILED),d&&(this.screenPubState.setState(ie.AliRtcStateNoPublish),l=U.ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED),h.errorCode===15006&&r<3)return this.publishAdd(e,t,i,r+1);throw O.fromError(h,l,"publish add failed")}})}publishReplace(e,t){return I(this,null,function*(){try{yield this.rtsManager.publishReplace(this.url,e,t),this.streamTracks=this.rtsManager.publishingTracks;const i=(t==null?void 0:t.vMsid)===M.VideoLarge,r=(t==null?void 0:t.vMsid)===M.Screen;i&&this.streamManager.setVideoProfile(void 0,void 0,!0),r&&this.streamManager.setScreenProfile(void 0,void 0);const n={type:Lt.Replace,userid:this.userId,sessionid:"",pubid:this.publishId,displayname:this.name,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.streamTracks};return this.reportSelfDeviceStatus(),n}catch(i){throw O.fromError(i,U.ERR_INNER,`publish replace failed, vMsid: ${t==null?void 0:t.vMsid} aMsid: ${t==null?void 0:t.aMsid}`)}})}publishDeleteTracks(e){return I(this,null,function*(){const t={type:Lt.Delete,userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};try{return yield this.rtsManager.publishDelete(this.url,e),this.streamTracks=this.rtsManager.publishingTracks,e.audio&&this.audioPubState.setState(ie.AliRtcStateNoPublish),e.video&&(e.vMsid===M.VideoSmall?this.videoSmallPubState.setState(ie.AliRtcStateNoPublish):this.videoPubState.setState(ie.AliRtcStateNoPublish)),e.screen&&this.screenPubState.setState(ie.AliRtcStateNoPublish),t.tracks=this.streamTracks,this.reportSelfDeviceStatus(),t}catch(i){throw O.fromError(i,U.ERR_INNER,"publish delete tracks failed")}})}publishStop(){return I(this,null,function*(){V.info(`[${Tt.logName}]`,"publishStop",{url:this.url});const e=new Date().getTime();try{const t=this.hasAudioTrackInMS,i=this.hasCameraTrackInMS,r=this.hasCameraDualTrackInMS,n=this.hasScreenTrackInMS;yield this.rtsManager.publishStop(this.url),t&&this.audioPubState.setState(ie.AliRtcStateNoPublish),i&&this.videoPubState.setState(ie.AliRtcStateNoPublish),r&&this.videoSmallPubState.setState(ie.AliRtcStateNoPublish),n&&this.screenPubState.setState(ie.AliRtcStateNoPublish),this.traceId="",Object.keys(this.monitorDataCache).forEach(o=>{this.reportPublishMonitor(o)}),this.streamTracks=[];const c={type:Lt.Stop,userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};return this.syncPublishToRoomServer(c,{},e),c}catch(t){throw O.fromError(t,U.ERR_INNER,"publish stop failed")}})}unPublish(){return I(this,null,function*(){this.shouldPublish=!1;const e=new Date().getTime();let t={type:Lt.UnPublish,userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};try{if(this.isPublishing){const i=this.hasAudioTrackInMS,r=this.hasCameraTrackInMS,n=this.hasCameraDualTrackInMS,c=this.hasScreenTrackInMS;yield this.rtsManager.unpublish(),this.streamTracks=[],this.stopStreamMonitor(),i&&this.audioPubState.setState(ie.AliRtcStateNoPublish),r&&this.videoPubState.setState(ie.AliRtcStateNoPublish),n&&this.videoSmallPubState.setState(ie.AliRtcStateNoPublish),c&&this.screenPubState.setState(ie.AliRtcStateNoPublish),this.traceId="",this.clearStream()}return this.dc&&(this.rtsManager.publishStopDataChannel(this.url,this.dc),this.dataPubState.setState(ie.AliRtcStateNoPublish),this.dc=void 0),this.slsReporter.reportUnpublish(this.callId||"",e,0,""),t}catch(i){throw O.fromError(i,U.ERR_INNER,"unpublish failed")}})}reportSelfDeviceStatus(){this.emit(Ye.Local,this.getDeviceStatus())}getDeviceStatus(){var t,i,r,n;let e={micOpen:!1,micInterrupted:!1,cameraOpen:!1,screenShare:!1,audioDisable:!0,videoDisable:!0,screenDisable:!0,backgroundMode:!1,accompanyPlaying:!1};return e.cameraOpen=this.hasCameraTrackInMS,e.videoDisable=this.hasCamera&&!((t=this.streamManager.cameraStreamInfo.originVideoTrack)!=null&&t.enabled),e.micOpen=this.hasAudioTrackInMS,e.audioDisable=this.hasMicrophone&&!((i=this.streamManager.cameraStreamInfo.originAudioTrack)!=null&&i.enabled),e.screenShare=this.hasScreenTrackInMS,e.screenDisable=this.hasScreenShare&&!((n=(r=this.streamManager.screenStreamInfo)==null?void 0:r.originVideoTrack)!=null&&n.enabled),Wa.getCurrentStatus(e)}resetPreviewElements(){this.previewElements.forEach(e=>{e.srcObject=null,e._playPromise=void 0},[]),this.previewElements=[]}resetSecondayPreviewElements(){this.screenPreviewElements.forEach(e=>{e.srcObject=null,e._playPromise=void 0},[]),this.screenPreviewElements=[]}getMediaStats(e){return this.pcMediaStatsMap[e]}reportPublishMonitor(e){if(!e)return;let t;try{t=e===M.Audio?this.rtsManager.getStreamByMsid({url:this.url,aMsid:e}).audioTrack:this.rtsManager.getStreamByMsid({url:this.url,vMsid:e}).videoTrack}catch(i){}this.slsReporter.reportPublishMonitor(this.callId,this.trackTraceIdMap[e]||"",e,t,this.monitorDataCache[e]),this.monitorDataCache[e]=[]}reportNetwork(){this.slsReporter.reportNetworkMonitor(this.candidateDataCache),this.candidateDataCache=[]}startStreamMonitor(){this.monitorTimerId||(this.monitorTimerId=window.setInterval(()=>I(this,null,function*(){var e,i;try{const r=yield this.rtsManager.getPCStats();let n,c;if(r==null||r.forEach(d=>{d.type==="media-source"||d.type==="media-playout"?d.id&&(this.pcMediaStatsMap[d.id]=d):d.type==="candidate-pair"&&d.state==="succeeded"&&(n=d)}),((e=this.candidateDataCache)==null?void 0:e.length)>0){const d=this.candidateDataCache[this.candidateDataCache.length-1]||{},t=d,{_last:h}=t;c=jt(t,["_last"])}((i=this.candidateDataCache)==null?void 0:i.length)>=30&&this.reportNetwork(),n&&(n._last=c,this.candidateDataCache.push(n));let o=Object.keys(this.monitorDataCache).filter(d=>{var h;return((h=this.monitorDataCache[d])==null?void 0:h.length)>0});(this.streamTracks||[]).forEach(d=>{const h=d.msid;if(!h)return;let l;o.includes(h)&&(o=o.filter(p=>p!==h)),l=h===M.Audio?this.rtsManager.getPublishAudioStats(this.url):this.rtsManager.getPublishVideoStats(this.url,h),l.then(p=>{if(!p.timestamp)return;this.monitorDataCache[h]||(this.monitorDataCache[h]=[]);const u=this.getMediaStats(p.mediaSourceId);p._source=u;const f=this.monitorDataCache[h];let m;if((f==null?void 0:f.length)>0){const S=f[f.length-1]||{},b=S,{_last:v}=b;m=jt(b,["_last"])}(f==null?void 0:f.length)>=30&&this.reportPublishMonitor(h),p._last=m,p._codec=d.codec||"",this.monitorDataCache[h].push(p)})}),o.forEach(d=>{this.reportPublishMonitor(d)})}catch(r){}}),1e3))}stopStreamMonitor(){this.monitorTimerId&&(clearInterval(this.monitorTimerId),this.monitorTimerId=void 0),Object.keys(this.monitorDataCache).forEach(e=>{this.reportPublishMonitor(e)})}clearStream(){this.streamManager.stop(),this.audioPubState.setState(ie.AliRtcStatePublishIdle),this.videoPubState.setState(ie.AliRtcStatePublishIdle),this.videoSmallPubState.setState(ie.AliRtcStatePublishIdle),this.screenPubState.setState(ie.AliRtcStatePublishIdle)}getCurrentCameraDeviceId(){var e;return(e=this.streamManager.cameraStreamInfo.originVideoTrack)==null?void 0:e.getSettings().deviceId}getCurrentMicDeviceId(){var e;return(e=this.streamManager.cameraStreamInfo.originAudioTrack)==null?void 0:e.getSettings().deviceId}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.audioLevelMonitor.stop(),e>0&&this.streamManager.cameraStreamInfo.originAudioTrack&&this.audioLevelMonitor.start(this.streamManager.cameraStreamInfo.originAudioTrack,e),this.audioVolumeIndicationInterval=e)}sendSEI(e,t,i){return I(this,null,function*(){if(!this.url)return;let r=0;return r=!t||t<1?1:t-1,this.rtsManager.sendSEI(this.url,e,r,i)})}sendDataChannelMessage(e){var i;if(!((i=this.parameter.data)!=null&&i.enablePubDataChannel))throw new O(U.ERR_INNER,"data channel publish is not enabled");if(!this.dc)throw new O(U.ERR_INNER,"data channel is not ready");const t=function(r,n){let c=0;const o=[];for(;c<r.byteLength;){const d=Math.min(n,r.byteLength-c),h=r.slice(c,c+d);o.push(h),c+=d}return o}(e.toBuffer(),1156);t.forEach((r,n)=>{const c=new Fi(new mi(r.byteLength,n===t.length-1,n===0?1:0),r);this.dc.send(c.toGRTNBuffer())})}getStats(){return I(this,null,function*(){const e=[];if(this.hasAudioTrackInMS){const n=yield this.rtsManager.getPublishAudioStats(this.url);n&&e.push({stats:n,track:Jt.AliRtcAudioTrackMic})}const t=[];if(this.hasCameraTrackInMS){const n=yield this.rtsManager.getPublishVideoStats(this.url,M.VideoLarge);n&&t.push({track:oe.AliRtcVideoTrackCamera,streamType:ze.AliRtcVideoStreamTypeHigh,stats:n})}if(this.hasCameraDualTrackInMS){const n=yield this.rtsManager.getPublishVideoStats(this.url,M.VideoSmall);n&&t.push({track:oe.AliRtcVideoTrackCamera,streamType:ze.AliRtcVideoStreamTypeLow,stats:n})}if(this.hasScreenTrackInMS){const n=yield this.rtsManager.getPublishVideoStats(this.url,M.Screen);n&&t.push({track:oe.AliRtcVideoTrackScreen,stats:n})}let i;const r=yield this.rtsManager.getPCStats();return r==null||r.forEach(n=>{n.type==="candidate-pair"&&n.state==="succeeded"&&(i=n)}),{audio:e,video:t,candidate:i}})}},g(Tt,"logName","LocalUser"),Tt);De([C()],Ce.prototype,"clearPublishState",1),De([C()],Ce.prototype,"clear",1),De([C(H)],Ce.prototype,"startDefaultCameraAndMic",1),De([C()],Ce.prototype,"setViewConfig",1),De([C()],Ce.prototype,"startCameraCapture",1),De([C()],Ce.prototype,"stopCameraCapture",1),De([C()],Ce.prototype,"startAudioCapture",1),De([C()],Ce.prototype,"stopAudioCapture",1),De([C()],Ce.prototype,"startCameraAndMic",1),De([C()],Ce.prototype,"stopPreview",1),De([C()],Ce.prototype,"resumePublish",1),De([C()],Ce.prototype,"createLocalStream",1),De([C()],Ce.prototype,"stopLocalStream",1),De([C(H)],Ce.prototype,"startPublish",1),De([C()],Ce.prototype,"updateStreams",1),De([C(([s])=>[s])],Ce.prototype,"syncPublishToRoomServer",1),De([C()],Ce.prototype,"refreshPushStreamUrl",1),De([C(([s,a,e])=>[JSON.stringify(e)])],Ce.prototype,"publishAdd",1),De([C(([s,a])=>[JSON.stringify(a)])],Ce.prototype,"publishReplace",1),De([C(H)],Ce.prototype,"publishDeleteTracks",1),De([C()],Ce.prototype,"publishStop",1),De([C()],Ce.prototype,"unPublish",1),De([C(([s,a,e])=>[s.length,a,e])],Ce.prototype,"sendSEI",1);let jo=Ce;var lt=(s=>(s.OPUS="opus",s.H264="H264",s.H265="H265",s.AV1="AV1",s.UNKNOWN="",s))(lt||{}),ce=(s=>(s[s.NotSubscribe=0]="NotSubscribe",s[s.Subscribing=1]="Subscribing",s[s.Subscribed=2]="Subscribed",s))(ce||{}),Gt=(s=>(s.VideoTrackEnded="videoTrackEnded",s.AudioTrackEnded="audioTrackEnded",s.ScreenTrackEnded="screenTrackEnded",s))(Gt||{});const Qa=s=>I(this,null,function*(){return yield X.AliRTS.createStream({custom:!0,mediaStream:s})}),fi=s=>I(this,null,function*(){const a=(e=>{const t=new MediaStream;return t.addTrack(e),t})(s);return yield Qa(a)});var zo=Object.defineProperty,Wo=Object.getOwnPropertyDescriptor;class ji extends se{constructor(){super();g(this,"audioInfo",{subscribeState:ce.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:lt.UNKNOWN});g(this,"videoLargeInfo",{subscribeState:ce.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:lt.UNKNOWN});g(this,"videoSmallInfo",{subscribeState:ce.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:lt.UNKNOWN});g(this,"screenInfo",{subscribeState:ce.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:lt.UNKNOWN});g(this,"dataInfo",{subscribeState:ce.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:lt.UNKNOWN});g(this,"audioVolume",1);g(this,"audioMuted",!1);g(this,"userStatus")}getAudioInfo(){return this.audioInfo}getVideoSmallInfo(){return this.videoSmallInfo}getVideoLargeInfo(){return this.videoLargeInfo}getScreenInfo(){return this.screenInfo}getDataInfo(){return this.dataInfo}get subscribingInfos(){return[this.audioInfo,this.videoLargeInfo,this.videoSmallInfo,this.screenInfo].filter(e=>e.msid&&e.subscribeState===ce.Subscribed)}get hasTrack(){return this.hasAudio||this.hasVideo||this.hasScreen||this.hasData}get hasAudio(){return this.audioInfo.ssrc!==""}get hasVideo(){return this.videoLargeInfo.ssrc!==""||this.videoSmallInfo.ssrc!==""}get hasVideoLarge(){return this.videoLargeInfo.ssrc!==""}get hasVideoSmall(){return this.videoSmallInfo.ssrc!==""}get hasScreen(){return this.screenInfo.ssrc!==""}get hasData(){return this.dataInfo.ssrc!==""}get isAudioSubscribed(){return this.audioInfo.subscribeState===ce.Subscribed}get isAudioSubscribing(){return this.audioInfo.subscribeState===ce.Subscribing}get isVideoSubscribed(){return this.isVideoLargeSubscribed||this.isVideoSmallSubscribed}get isVideoSubscribing(){return this.isVideoLargeSubscribing||this.isVideoSmallSubscribing}get isVideoLargeSubscribed(){return this.videoLargeInfo.subscribeState===ce.Subscribed}get isVideoLargeSubscribing(){return this.videoLargeInfo.subscribeState===ce.Subscribing}get isVideoSmallSubscribed(){return this.videoSmallInfo.subscribeState===ce.Subscribed}get isVideoSmallSubscribing(){return this.videoSmallInfo.subscribeState===ce.Subscribing}get isScreenSubscribed(){return this.screenInfo.subscribeState===ce.Subscribed}get isScreenSubscribing(){return this.screenInfo.subscribeState===ce.Subscribing}get isDataSubscribed(){return this.dataInfo.subscribeState===ce.Subscribed}get isDataSubscribing(){return this.dataInfo.subscribeState===ce.Subscribing}get audioCodec(){return this.audioInfo.codec}get videoCodec(){return this.hasVideoLarge?this.videoLargeInfo.codec:this.hasVideoSmall?this.videoSmallInfo.codec:this.hasScreen?this.screenInfo.codec:lt.UNKNOWN}get audioTrackInfo(){return this.hasAudio?Jt.AliRtcAudioTrackMic:Jt.AliRtcAudioTrackNo}get videoTrackInfo(){return this.hasVideo&&this.hasScreen?oe.AliRtcVideoTrackBoth:this.hasVideo?oe.AliRtcVideoTrackCamera:this.hasScreen?oe.AliRtcVideoTrackScreen:oe.AliRtcVideoTrackNo}updateTracks(e){let t="",i="",r="",n="",c="";return e?(e.forEach(o=>{var p;let d=lt.UNKNOWN;const h=((p=o==null?void 0:o.attr)==null?void 0:p.reason)==="reconnect";if(o.userdata){const{codec:u}=JSON.parse(o.userdata);u&&(d=u)}var l;(l=o.msid)===M.Audio||l===Ar.Audio?(t=o.ssrc,this.audioInfo.msid=o.msid,this.audioInfo.codec=d,(h||this.audioInfo.ssrc!==t)&&(this.audioInfo.subscribeState=ce.NotSubscribe)):(u=>u===M.VideoSmall)(o.msid)?(r=o.ssrc,this.videoSmallInfo.msid=o.msid,this.videoSmallInfo.codec=d,(h||this.videoSmallInfo.ssrc!==r)&&(this.videoSmallInfo.subscribeState=ce.NotSubscribe)):(u=>u===M.VideoLarge||u===Ar.VideoLarge)(o.msid)?(i=o.ssrc,this.videoLargeInfo.msid=o.msid,this.videoLargeInfo.codec=d,(h||this.videoLargeInfo.ssrc!==i)&&(this.videoLargeInfo.subscribeState=ce.NotSubscribe)):(u=>u===M.Screen)(o.msid)?(n=o.ssrc,this.screenInfo.msid=o.msid,this.screenInfo.codec=d,(h||this.screenInfo.ssrc!==n)&&(this.screenInfo.subscribeState=ce.NotSubscribe)):(u=>u===M.Data)(o.msid)&&(c=o.ssrc,this.dataInfo.msid=o.msid,this.dataInfo.codec=d,(h||this.dataInfo.ssrc!==c)&&(this.dataInfo.subscribeState=ce.NotSubscribe))}),this.updateRemoteTrackSsrc(t,i,r,n,c)):this.updateRemoteTrackSsrc(t,i,r,n,c),{}}updateRemoteTrackSsrc(e,t,i,r,n){this.audioInfo.ssrc=e,this.videoSmallInfo.ssrc=i,this.videoLargeInfo.ssrc=t,this.screenInfo.ssrc=r,this.dataInfo.ssrc=n}markRemoteTrackSubscribing(e){return e.video&&(e.vMsid===this.videoSmallInfo.msid&&(this.videoSmallInfo.subscribeState=ce.Subscribing),e.vMsid!==this.videoLargeInfo.msid&&e.vMsid||(this.videoLargeInfo.subscribeState=ce.Subscribing)),e.screen&&(this.screenInfo.subscribeState=ce.Subscribing),e.audio&&(this.audioInfo.subscribeState=ce.Subscribing),e.data&&(this.dataInfo.subscribeState=ce.Subscribing),{videoLargeInfo:this.videoLargeInfo,videoSmallInfo:this.videoSmallInfo}}updateRemoteTrackSubState(e){return e.video!==void 0&&(e.vMsid!==this.videoSmallInfo.msid&&e.vMsid||(this.videoSmallInfo.subscribeState=e.video?ce.Subscribed:ce.NotSubscribe),e.vMsid!==this.videoLargeInfo.msid&&e.vMsid||(this.videoLargeInfo.subscribeState=e.video?ce.Subscribed:ce.NotSubscribe)),e.screen!==void 0&&(this.screenInfo.subscribeState=e.screen?ce.Subscribed:ce.NotSubscribe),e.audio!==void 0&&(this.audioInfo.subscribeState=e.audio?ce.Subscribed:ce.NotSubscribe),e.data!==void 0&&(this.dataInfo.subscribeState=e.data?ce.Subscribed:ce.NotSubscribe),{audioInfo:this.audioInfo,videoLargeInfo:this.videoLargeInfo,videoSmallInfo:this.videoSmallInfo,screenInfo:this.screenInfo,dataInfo:this.dataInfo}}updateRemoteUserDeviceStatus(e){let t=Wa.parseStatus(e);const{audioDisable:i,videoDisable:r,screenDisable:n}=t;return this.userStatus?(this.userStatus.audioDisable!=i&&(this.userStatus.audioDisable=i,this.emit(Ye.Remote,i?Ee.MuteAudio:Ee.UnmuteAudio)),this.userStatus.videoDisable!=r&&(this.userStatus.videoDisable=r,this.emit(Ye.Remote,r?Ee.MuteVideo:Ee.UnmuteVideo)),this.userStatus.screenDisable!=n&&(this.userStatus.screenDisable=n,this.emit(Ye.Remote,n?Ee.MuteScreen:Ee.UnmuteScreen))):(this.userStatus=t,this.emit(Ye.Remote,i?Ee.MuteAudio:Ee.UnmuteAudio),this.emit(Ye.Remote,r?Ee.MuteVideo:Ee.UnmuteVideo),this.emit(Ye.Remote,n?Ee.MuteScreen:Ee.UnmuteScreen)),!1}}g(ji,"logName","RemoteStreamInfo"),((s,a,e,t)=>{for(var i,r=t>1?void 0:t?Wo(a,e):a,n=s.length-1;n>=0;n--)(i=s[n])&&(r=(t?i(a,e,r):i(r))||r);t&&r&&zo(a,e,r)})([C()],ji.prototype,"updateRemoteTrackSubState",1);class Za{constructor(a){g(this,"remoteUser");this.remoteUser=a}get userId(){return this.remoteUser.userId}get displayName(){return this.remoteUser.displayname}get isMuteAudioPlaying(){return this.remoteUser.getAudioMuted()}get hasAudio(){return this.remoteUser.hasAudioTrack}get hasCamera(){return this.remoteUser.hasVideoTrack}get hasCameraLarge(){return this.remoteUser.hasVideoLargeTrack}get hasCameraSmall(){return this.remoteUser.hasVideoSmallTrack}get hasScreenShare(){return this.remoteUser.hasScreenTrack}get isAudioSubscribing(){return this.remoteUser.isAudioSubscribing}get isVideoSubscribing(){return this.remoteUser.isVideoSubscribing}get isVideoLargeSubscribing(){return this.remoteUser.isVideoLargeSubscribing}get isVideoSmallSubscribing(){return this.remoteUser.isVideoSmallSubscribing}get isScreenSubscribing(){return this.remoteUser.isScreenSubscribing}get audioElement(){return this.remoteUser.getAudioElement()}}var $o=Object.defineProperty,Ko=Object.getOwnPropertyDescriptor,Ke=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?Ko(a,e):a,n=s.length-1;n>=0;n--)(i=s[n])&&(r=(t?i(a,e,r):i(r))||r);return t&&r&&$o(a,e,r),r};class ai extends se{constructor(){super();g(this,"state");g(this,"time");g(this,"_enabled");this.state=me.AliRtcStateSubscribeIdle,this.time=Date.now(),this._enabled=!0}setState(e){if(this.state===e)return;const t=this.state,i=this.time;this.state=e,this.time=Date.now(),this.emit("change",t,e,Math.floor((this.time-i)/1e3))}get currentState(){return this.state}getEnabled(){return this._enabled}setEnabled(e){this._enabled=e}}const We=(Qe=class extends za{constructor(e){var u;const{userId:t,displayName:i,rtsManager:r,usersViewMap:n,slsReporter:c,signalingManager:o,localUser:d,audioVolumeIndicationInterval:h,playoutVolume:l,parameter:p}=e;super(t,i,r,h);g(this,"remoteCallid","");g(this,"remoteUserInfo");g(this,"localUser");g(this,"lastPubId","");g(this,"stream");g(this,"screenStream");g(this,"viewMap");g(this,"audioTrack");g(this,"audioElement");g(this,"subscribed",!1);g(this,"mediaStream");g(this,"secondaryMediaStream");g(this,"prevSubConfig");g(this,"signalingManager");g(this,"slsReporter");g(this,"wantSubAudio",!1);g(this,"wantSubVideo",!1);g(this,"wantSubScreen",!1);g(this,"defaultVideoStreamType",ze.AliRtcVideoStreamTypeHigh);g(this,"audioMuted",!1);g(this,"playoutVolume",1);g(this,"playoutGainNode");g(this,"audioSubState");g(this,"videoSubState");g(this,"videoLargeSubState",new ai);g(this,"videoSmallSubState",new ai);g(this,"screenSubState");g(this,"dataSubState");g(this,"dc");g(this,"dcMsgWaitingPieces",[]);g(this,"streamInfo");g(this,"_streamUrl","");g(this,"parameter",{});g(this,"monitorTimerId");g(this,"monitorDataCache",{});g(this,"trackTraceIdMap",{});g(this,"handleAudioContextSuspended",e=>{e.target.state==="suspended"&&this.emit("remoteAudioPlayError",this.uid,"AudioContext suspended")});g(this,"onDataChannelMessage",e=>{var r;const t=Fi.parse(e.slice(4));let i;if(t.body){if(!t.isFin)return t.header.frameType===1&&(this.dcMsgWaitingPieces=[]),void this.dcMsgWaitingPieces.push(t.body);if(this.dcMsgWaitingPieces.length>0){const n=this.dcMsgWaitingPieces.reduce((c,o)=>c+o.byteLength,t.body.byteLength);try{const c=new ArrayBuffer(n);let o=0;for(let d=0;d<this.dcMsgWaitingPieces.length;d++){const h=this.dcMsgWaitingPieces[d];new Uint8Array(c,o,h.byteLength).set(new Uint8Array(h)),o+=h.byteLength}new Uint8Array(c,o,t.body.byteLength).set(new Uint8Array(t.body)),i=Vt.parse(c)}catch(c){}this.dcMsgWaitingPieces=[],i||(i=Vt.parse(t.body))}else i=Vt.parse(t.body);i||V.event(`[${Qe.logName}]`,`parse data channel message fail, piece count: ${this.dcMsgWaitingPieces.length+1}`)}i&&(V.event(`[${Qe.logName}]`,`receive dc message, length(${(r=i.data)==null?void 0:r.byteLength})`),this.emit("remoteDataChannelMessage",this.uid,i))});g(this,"onDataChannelError",e=>{this.emit("occurError",O.fromError(e,U.ERR_SDK_SUBSCRIBE_DATA_ERROR))});g(this,"dataChannelConnected",e=>{e&&(this.dc=e,this.dc.datachannel&&(this.dc.datachannel.binaryType="arraybuffer"),this.dc.off("message",this.onDataChannelMessage),this.dc.off("error",this.onDataChannelError),this.dc.on("message",this.onDataChannelMessage),this.dc.on("error",this.onDataChannelError))});g(this,"handleAudioPaused",()=>{this.emit("remoteAudioPlayError",this.uid,"paused")});this.streamInfo=new ji,this.remoteUserInfo=new Za(this),this.parameter=p,this.streamInfo.on(Ye.Remote,f=>{this.emit(Ye.Remote,f,this.userId)}),this.signalingManager=o,this.viewMap=(u=n[t])!=null?u:{cameraViews:[],screenViews:[]},n[t]=this.viewMap,this.slsReporter=c,this.localUser=d,this.audioSubState=new ai,this.audioSubState.on("change",(f,m,b)=>{this.emit("audioSubscribeStateChanged",this.uid,f,m,b)}),this.videoSubState=new ai,this.videoSubState.on("change",(f,m,b)=>{this.emit("videoSubscribeStateChanged",this.uid,f,m,b)}),this.screenSubState=new ai,this.screenSubState.on("change",(f,m,b)=>{this.emit("screenSubscribeStateChanged",this.uid,f,m,b)}),this.dataSubState=new ai,this.dataSubState.on("change",(f,m,b)=>{this.emit("dataSubscribeStateChanged",this.uid,f,m,b)}),this.playoutVolume=l}get streamUrl(){return this._streamUrl}set streamUrl(e){this._streamUrl=e,this.rtsManager.updateAuth(e)}isWantSubAudio(){return this.wantSubAudio}setWantSubAudio(e){this.wantSubAudio=e}isWantSubVideo(){return this.wantSubVideo}setWantSubVideo(e){this.wantSubVideo=e}isWantSubScreen(){return this.wantSubScreen}setWantSubScreen(e){this.wantSubScreen=e}setRemoteDefaultVideoStreamType(e){e!==this.defaultVideoStreamType&&(this.defaultVideoStreamType=e,this.updateSubscribe(be.User))}setAudioMuted(e){this.audioMuted=e,this.toggleAudio(!e)}getAudioElement(){return this.audioElement}setPlayoutVolume(e){if(this.playoutVolume=e,this.audioElement)if(this.parameter.enableAudioContextPlayoutVolume)if(this.playoutGainNode)this.playoutGainNode.gain.value=e;else{const t=this.audioElement.srcObject;if(t){const i=Kt.getInstance();i.addEventListener("statechange",this.handleAudioContextSuspended);const r=i.createMediaStreamSource(t);this.audioElement.muted=!0,this.playoutGainNode=i.createGain(),r.connect(this.playoutGainNode),this.playoutGainNode.gain.value=e,this.playoutGainNode.connect(i.destination)}}else this.audioElement.volume=e}getAudioMuted(){return this.audioMuted}get hasAudioTrack(){var e;return!!((e=this.streamInfo)!=null&&e.hasAudio)}get hasVideoTrack(){var e;return!!((e=this.streamInfo)!=null&&e.hasVideo)}get hasVideoLargeTrack(){var e;return!!((e=this.streamInfo)!=null&&e.hasVideoLarge)}get hasVideoSmallTrack(){var e;return!!((e=this.streamInfo)!=null&&e.hasVideoSmall)}get hasScreenTrack(){var e;return!!((e=this.streamInfo)!=null&&e.hasScreen)}get isAudioSubscribing(){var e,t;return!!((e=this.streamInfo)!=null&&e.isAudioSubscribed)||!!((t=this.streamInfo)!=null&&t.isAudioSubscribing)}get isVideoSubscribing(){var e,t;return!!((e=this.streamInfo)!=null&&e.isVideoSubscribed)||!!((t=this.streamInfo)!=null&&t.isVideoSubscribing)}get isVideoLargeSubscribing(){var e,t;return!!((e=this.streamInfo)!=null&&e.isVideoLargeSubscribed)||!!((t=this.streamInfo)!=null&&t.isVideoLargeSubscribing)}get isVideoSmallSubscribing(){var e,t;return!!((e=this.streamInfo)!=null&&e.isVideoSmallSubscribed)||!!((t=this.streamInfo)!=null&&t.isVideoSmallSubscribing)}get isScreenSubscribing(){var e,t;return!!((e=this.streamInfo)!=null&&e.isScreenSubscribed)||!!((t=this.streamInfo)!=null&&t.isScreenSubscribing)}get isDataSubscribing(){var e,t;return!!((e=this.streamInfo)!=null&&e.isDataSubscribed)||!!((t=this.streamInfo)!=null&&t.isDataSubscribing)}get audioEnabled(){var e,t;return!!((t=(e=this.stream)==null?void 0:e.audioTrack)!=null&&t.enabled)}get videoEnabled(){var e,t;return!!((t=(e=this.stream)==null?void 0:e.videoTrack)!=null&&t.enabled)}get screenEnabled(){var e,t;return!!((t=(e=this.screenStream)==null?void 0:e.videoTrack)!=null&&t.enabled)}get getAudioTrack(){return this.audioTrack}get getCameraStream(){return this.stream}get getScreenStream(){return this.screenStream}setViewConfig(e,t){if(t!==oe.AliRtcVideoTrackScreen&&t!==oe.AliRtcVideoTrackCamera)throw new O(U.ERR_INVALID_ARGUMENTS,"track is not AliRtcVideoTrackScreen or AliRtcVideoTrackCamera");e?wr(e).forEach(i=>{i.setAttribute("playsinline",""),X.AliRTS.BrowserUtil.isMicroMessenger&&(i.setAttribute("x5-video-player-type","h5-page"),i.setAttribute("x5-playsinline",""),X.AliRTS.SystenUtil.isAndroid||X.AliRTS.SystenUtil.isIos&&i.setAttribute("x-webkit-airplay","allow")),t===oe.AliRtcVideoTrackScreen?this.viewMap.screenViews.push(i):this.viewMap.cameraViews.push(i),this.play(i,t===oe.AliRtcVideoTrackScreen)}):(this.stopPlayAll(t===oe.AliRtcVideoTrackScreen),t===oe.AliRtcVideoTrackScreen?this.viewMap.screenViews=[]:this.viewMap.cameraViews=[])}clear(e=!0){return I(this,null,function*(){var t;this.subscribeStopDataChannel(),e&&this.doStopSubscribe(this.streamUrl),Yr(Qe.prototype,this,"clear").call(this),this.stopPlayAudio(),this.clearStream(),this.clearScreenStream(),this.playoutGainNode&&(this.playoutGainNode.disconnect(),this.playoutGainNode=void 0,Kt.getInstance().removeEventListener("statechange",this.handleAudioContextSuspended)),(t=this.streamInfo)==null||t.removeAllListeners(Ye.Remote)})}updateRemoteUserDeviceStatus(e){var t;(t=this.streamInfo)==null||t.updateRemoteUserDeviceStatus(e)}updateRemoteTracks(e,t,i,r){return I(this,null,function*(){var c;return this.remoteCallid=e,this.streamUrl&&this.streamInfo.hasTrack||(this.streamUrl=t),this.callId=e!=null?e:"",this.streamInfo||(this.streamInfo=new ji),(c=this.streamInfo)==null?void 0:c.updateTracks(r)})}subscribe(r,n){return I(this,arguments,function*(e,t,i=Date.now()){var u,f;let c=e;if(!c){const{hasAudio:m,hasVideo:b,hasScreen:S,hasData:v}=(u=this.streamInfo)!=null?u:{};c={audio:this.wantSubAudio&&m,video:this.wantSubVideo&&b,screen:this.wantSubScreen&&S,data:((f=this.parameter.data)==null?void 0:f.enableSubDataChannel)&&v}}this.streamInfo.markRemoteTrackSubscribing(c);const{screen:o,audio:d,video:h,vMsid:l}=c,p=[];(h||d)&&p.push({audio:d,video:h,vMsid:l}),o&&p.push({screen:o}),(p.length!==0||e!=null&&e.data)&&(yield Promise.all(p.map(m=>this.subscribeProxy(m,t||be.User,i))),e!=null&&e.data&&this.subscribeDataChannel())})}subscribeProxy(e,t,i){return I(this,null,function*(){var c,o,d,h;let r=new Date().getTime(),n="";try{e.audio&&this.audioSubState.setState(me.AliRtcStateSubscribing),e.video&&(this.videoSubState.currentState!==me.AliRtcStateSubscribeIdle&&this.videoSubState.currentState!==me.AliRtcStateNoSubscribe||this.videoSubState.setState(me.AliRtcStateSubscribing)),e.screen&&this.screenSubState.setState(me.AliRtcStateSubscribing);const l=yield this.rtsManager.subscribe({remoteUser:this,options:e},t,((c=this.localUser)==null?void 0:c.callId)||"",this.callId,i);this.streamInfo.updateRemoteTrackSubState(e),n=l.traceId||"";const{stream:p}=l;if(e.audio){this.trackTraceIdMap[M.Audio]=n;const f=p.audioTrack;f&&(this.audioTrack=f,(o=p.mediaStream)==null||o.removeTrack(f),this.playAudio(),this.audioVolumeIndicationInterval&&this.audioLevelMonitor.start(f,this.audioVolumeIndicationInterval)),this.audioSubState.getEnabled()||this.toggleAudio(!1),this.audioSubState.setState(me.AliRtcStateSubscribed)}e.video&&(this.updateStream(p,this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing),this.videoSubState.getEnabled()||this.toggleVideo(!1),this.videoSubState.setState(me.AliRtcStateSubscribed),e.vMsid===M.VideoSmall?(this.trackTraceIdMap[M.VideoSmall]=n,this.videoSmallSubState.setState(me.AliRtcStateSubscribed)):(this.trackTraceIdMap[M.VideoLarge]=n,this.videoLargeSubState.setState(me.AliRtcStateSubscribed))),e.screen&&(this.trackTraceIdMap[M.Screen]=n,this.updateScreenStream(p),this.videoSubState.getEnabled()||this.toggleScreen(!1),this.screenSubState.setState(me.AliRtcStateSubscribed));const u=new Date().getTime()-r;this.slsReporter.reportSubscribe(((d=this.localUser)==null?void 0:d.callId)||"",this.callId,!!e.video&&e.vMsid===M.VideoLarge,!!e.video&&e.vMsid===M.VideoSmall,!!e.screen,!!e.audio,0,"",u,{pctid:this.rtsManager.pcTraceId,subtid:n,ajsub:t===be.Join?1:0,url:this.streamUrl,est:r}),this.startStreamMonitor(),l.isHTTP&&l.statsCheckPromise&&(yield Promise.race([l.statsCheckPromise,xt(1500)]))}catch(l){const p=new Date().getTime()-r;e.audio&&this.audioSubState.setState(me.AliRtcStateNoSubscribe),e.video&&this.videoSubState.setState(me.AliRtcStateNoSubscribe),e.screen&&this.screenSubState.setState(me.AliRtcStateNoSubscribe),l&&(l.message=`user(${this.uid}) subscribe error, ${(l==null?void 0:l.message)||""}`);let u=U.ERR_INNER;e.audio&&(u=U.ERR_SDK_SUBSCRIBE_AUDIO_STREAM_FAILED),e.video&&(u=e.vMsid===M.VideoSmall?U.ERR_SDK_SUBSCRIBE_DUAL_STREAM_FAILED:U.ERR_SDK_SUBSCRIBE_VIDEO_STREAM_FAILED),e.screen&&(u=U.ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED),this.slsReporter.reportSubscribe(((h=this.localUser)==null?void 0:h.callId)||"",this.callId,!!e.video&&e.vMsid===M.VideoLarge,!!e.video&&e.vMsid===M.VideoSmall,!!e.screen,!!e.audio,u,"",p,{pctid:this.rtsManager.pcTraceId,subtid:"",ajsub:t===be.Join?1:0,url:this.streamUrl,est:r});const f=O.fromError(l,u);throw this.emit("remoteSubscribeError",f),f}})}subscribeDeleteTracks(e){return I(this,null,function*(){const{audio:t,video:i,screen:r,data:n,vMsid:c}=e,o=[];(t||i||n)&&o.push({audio:t,video:i,vMsid:c}),r&&o.push({screen:r}),o.length!==0&&(yield Promise.all(o.map(d=>this.subscribeDeleteProxy(d))),e.data&&this.subscribeStopDataChannel())})}subscribeDeleteProxy(e){return I(this,null,function*(){try{const t=yield this.rtsManager.subscribeDelete({remoteUser:this,options:e}),{stream:i}=t!=null?t:{},r={};e.audio===!0&&(r.audio=!1,this.audioSubState.setState(me.AliRtcStateNoSubscribe)),e.video===!0&&(r.video=!1,e.vMsid===M.VideoSmall?(this.videoSmallSubState.setState(me.AliRtcStateNoSubscribe),this.videoLargeSubState.currentState!==me.AliRtcStateNoSubscribe&&this.videoLargeSubState.currentState!==me.AliRtcStateSubscribeIdle||this.videoSubState.setState(me.AliRtcStateNoSubscribe)):(this.videoLargeSubState.setState(me.AliRtcStateNoSubscribe),this.videoSmallSubState.currentState!==me.AliRtcStateNoSubscribe&&this.videoSmallSubState.currentState!==me.AliRtcStateSubscribeIdle||this.videoSubState.setState(me.AliRtcStateNoSubscribe))),e.screen===!0&&(r.screen=!1,this.screenSubState.setState(me.AliRtcStateNoSubscribe));const{callId:n,remoteCallid:c}=this,o={callid:n,remoteCallid:c,remoteStream:i};return e.audio&&(this.audioLevelMonitor.stop(),this.stopPlayAudio(),this.audioTrack=void 0),this.streamInfo.updateRemoteTrackSubState({audio:e.audio!==!0&&void 0,video:e.video!==!0&&void 0,screen:e.screen!==!0&&void 0,vMsid:e.vMsid}),o}catch(t){throw O.fromError(t,U.ERR_INNER,"subscribe delete failed")}})}restore(){this.callId="",this.clearStream(),this.clearScreenStream(),this.audioTrack=void 0,this.streamInfo.updateRemoteTrackSubState({audio:!1,video:!1,screen:!1,data:!1}),this.audioElement&&this.audioElement.removeEventListener("pause",this.handleAudioPaused)}resumeAudio(){return I(this,null,function*(){const e=Kt.getInstance();return e.state!=="running"&&e.resume(),this.audioElement?this.audioElement.play():this.playAudio()})}resumeVideo(e){return I(this,null,function*(){return e&&e!==oe.AliRtcVideoTrackCamera&&e!==oe.AliRtcVideoTrackBoth?e&&e!==oe.AliRtcVideoTrackScreen&&e!==oe.AliRtcVideoTrackBoth?void 0:this.playAll(!0):this.playAll()})}resumePlay(){this.playAudio(),this.playAll(),this.playAll(!0)}stopSubscribe(e){return I(this,null,function*(){var i,r;let t=new Date().getTime();try{let n;n=e?yield this.subscribeDeleteTracks(e):yield this.doStopSubscribe(this.streamUrl),this.slsReporter.reportUnsubscribe(((i=this.localUser)==null?void 0:i.callId)||(n==null?void 0:n.callid)||"",this.callId,new Date().getTime()-t,0,"")}catch(n){throw this.slsReporter.reportUnsubscribe(((r=this.localUser)==null?void 0:r.callId)||"",this.callId,new Date().getTime()-t,0,""),n}})}doStopSubscribe(e){return I(this,null,function*(){var r,n,c,o;const{callId:t,remoteCallid:i}=this;if((this.isAudioSubscribing||this.isVideoSubscribing||this.isScreenSubscribing)&&e)try{this.stopStreamMonitor(),yield this.rtsManager.subscribeStop(e),this.restore();const d={callid:t,remoteCallid:i,remoteStream:this.stream};return this.callId="",d}catch(d){if(((o=(c=(n=(r=d==null?void 0:d.extraInfo)==null?void 0:r.parsedData)==null?void 0:n.streams)==null?void 0:c[0])==null?void 0:o.res_code)!==404)throw O.fromError(d,U.ERR_INNER,"subscribe stop failed")}})}updateStream(e,t=!1){return I(this,null,function*(){this.stream&&this.stream.videoTrack&&e.mediaStream&&t&&(yield new Promise(i=>{let r,n;if(e.mediaStream){n=document.createElement("video");const c=()=>{V.event(`uid: ${this.userId} new mediaStream canplay`),n&&n.removeEventListener("canplaythrough",c,!1),n=void 0,clearTimeout(r),i(!0)};n.addEventListener("canplaythrough",c,!1),(n._playPromise||Promise.resolve()).then(()=>{n&&e.mediaStream&&(n.srcObject=e.mediaStream)})}else i(!0);r=window.setTimeout(()=>{V.event(`uid: ${this.userId} new mediaStream timeout`),n=void 0,i(!0)},3e3)}),this.updateSubscribe(be.User)),this.stream=e,this.playAll(!1,t),!this.subscribed&&e&&(this.subscribed=!0),e.hasAudio&&this.isAudioSubscribing&&e.enableAudio(),e.hasVideo&&this.isVideoSubscribing&&e.enableVideo()})}updateScreenStream(e){this.screenStream=e,this.playAll(!0),!this.subscribed&&e&&(this.subscribed=!0),e.hasVideo&&this.isScreenSubscribing&&e.enableVideo()}clearStream(){var e;(e=this.stream)==null||e.stop(),this.stream=void 0}clearScreenStream(){var e;(e=this.screenStream)==null||e.stop(),this.screenStream=void 0}subscribeDataChannel(){if(this.dc)try{this.dc.dispose(),this.dcMsgWaitingPieces=[],this.dc.off("message",this.onDataChannelMessage),this.dc=void 0}catch(e){}(this.streamInfo.hasAudio||this.streamInfo.hasVideo||this.streamInfo.hasScreen)&&(this.dataSubState.setState(me.AliRtcStateSubscribing),this.rtsManager.subscribeAddDataChannel(this.streamUrl).then(e=>{if(e)return this.dataChannelConnected(e),this.dataSubState.setState(me.AliRtcStateSubscribed),void this.streamInfo.updateRemoteTrackSubState({data:!0});throw new Error("no dc founded")}).catch(e=>{const t=O.fromError(e,U.ERR_INNER,"subscribe data failed");this.emit("remoteSubscribeError",t),this.dataSubState.setState(me.AliRtcStateNoSubscribe)}))}subscribeStopDataChannel(){if(this.dc){try{this.rtsManager.subscribeStopDatachannel(this.streamUrl,this.dc)}catch(e){}this.dcMsgWaitingPieces=[],this.dc.off("message",this.onDataChannelMessage),this.dc.off("error",this.onDataChannelError),this.dataSubState.setState(me.AliRtcStateNoSubscribe),this.dc=void 0,this.streamInfo.updateRemoteTrackSubState({data:!1})}}getRetryOptions(){var i,r,n,c,o,d,h;const e={};this.wantSubAudio&&((i=this.streamInfo)!=null&&i.hasAudio)&&(e.audio=!0,e.aMsid=((r=this.streamInfo.getAudioInfo())==null?void 0:r.msid)||M.Audio),this.wantSubVideo&&((n=this.streamInfo)!=null&&n.hasVideo)&&(this.defaultVideoStreamType===ze.AliRtcVideoStreamTypeLow&&((c=this.streamInfo)!=null&&c.hasVideoSmall)?(e.video=!0,e.vMsid=M.VideoSmall):(o=this.streamInfo)!=null&&o.hasVideoLarge&&(e.video=!0,e.vMsid=((d=this.streamInfo.getVideoLargeInfo())==null?void 0:d.msid)||M.VideoLarge)),this.wantSubScreen&&((h=this.streamInfo)!=null&&h.hasScreen)&&(e.screen=!0);let t={};if(e.audio||e.video)t={audio:e.audio,video:e.video},this.streamInfo.updateRemoteTrackSubState({screen:!1,data:!1});else{if(!e.screen)return;t={screen:e.screen},this.streamInfo.updateRemoteTrackSubState({data:!1})}return{remoteUser:this,options:t}}updateSubscribe(e){var n,c,o,d,h,l,p,u,f,m,b,S,v,_,w,y,A;const t=Date.now(),i={},r={};if(this.wantSubAudio&&!this.isAudioSubscribing&&((n=this.streamInfo)!=null&&n.hasAudio)?(i.audio=!0,i.aMsid=((c=this.streamInfo.getAudioInfo())==null?void 0:c.msid)||M.Audio):this.wantSubAudio&&((o=this.streamInfo)!=null&&o.hasAudio)||!this.isAudioSubscribing||(r.audio=!0,r.aMsid=((d=this.streamInfo.getAudioInfo())==null?void 0:d.msid)||M.Audio),this.wantSubVideo&&((h=this.streamInfo)!=null&&h.hasVideo)?(this.defaultVideoStreamType===ze.AliRtcVideoStreamTypeLow&&!this.isVideoSmallSubscribing&&((l=this.streamInfo)!=null&&l.hasVideoSmall)?(i.video=!0,i.vMsid=M.VideoSmall):this.isVideoLargeSubscribing||!((p=this.streamInfo)!=null&&p.hasVideoLarge)||this.defaultVideoStreamType===ze.AliRtcVideoStreamTypeLow&&this.isVideoSmallSubscribing||(i.video=!0,i.vMsid=((u=this.streamInfo.getVideoLargeInfo())==null?void 0:u.msid)||M.VideoLarge),this.defaultVideoStreamType===ze.AliRtcVideoStreamTypeLow&&this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing&&this.streamInfo.hasVideoSmall?(r.video=!0,r.vMsid=M.VideoLarge):this.defaultVideoStreamType===ze.AliRtcVideoStreamTypeHigh&&this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing&&(r.video=!0,r.vMsid=M.VideoSmall)):this.wantSubVideo&&((f=this.streamInfo)!=null&&f.hasVideo)||!this.isVideoSubscribing||(r.video=!0,r.vMsid=this.streamInfo.isVideoSmallSubscribed||this.streamInfo.isVideoSmallSubscribing?M.VideoSmall:((m=this.streamInfo.getVideoLargeInfo())==null?void 0:m.msid)||M.VideoLarge),this.wantSubScreen&&!this.isScreenSubscribing&&((b=this.streamInfo)!=null&&b.hasScreen)?i.screen=!0:this.wantSubScreen&&((S=this.streamInfo)!=null&&S.hasScreen)||!this.isScreenSubscribing||(r.screen=!0),(v=this.parameter.data)!=null&&v.enableSubDataChannel&&!this.isDataSubscribing&&((_=this.streamInfo)!=null&&_.hasData)?i.data=!0:(w=this.parameter.data)!=null&&w.enableSubDataChannel&&((y=this.streamInfo)!=null&&y.hasData)||!this.isDataSubscribing||(r.data=!0),this.dc&&i.data&&this.subscribeStopDataChannel(),(i.audio||i.video||i.screen||i.data)&&(this.createCallId(),this.subscribe(i,e,t)),(r.audio||r.video||r.screen)&&this.subscribeDeleteTracks(r),e===be.Reconnect){if(V.event(`[${Qe.logName}]`,"reconnect, try to resume"),this.streamInfo.hasData&&!i.data){const R=this.rtsManager.getDatachannelByMsid({url:this.streamUrl,msid:this.streamInfo.getDataInfo().msid||M.Data});this.dataChannelConnected(R)}if(this.streamInfo.hasAudio&&!i.audio){const R=this.rtsManager.getStreamByMsid({url:this.streamUrl,aMsid:this.streamInfo.getAudioInfo().msid||M.Audio});R&&R.audioTrack&&(this.audioTrack=R.audioTrack,this.audioVolumeIndicationInterval>0&&(this.audioLevelMonitor.stop(),this.audioLevelMonitor.start(this.audioTrack,this.audioVolumeIndicationInterval)),this.playAudio())}if(this.streamInfo.hasVideo&&!i.video){const R=this.rtsManager.getStreamByMsid({url:this.streamUrl,vMsid:this.streamInfo.isVideoSmallSubscribed||this.streamInfo.isVideoSmallSubscribing?M.VideoSmall:((A=this.streamInfo.getVideoLargeInfo())==null?void 0:A.msid)||M.VideoLarge});R&&R.mediaStream&&(this.stream=R,this.playAll(!1))}if(this.streamInfo.hasScreen&&!i.screen){const R=this.rtsManager.getStreamByMsid({url:this.streamUrl,vMsid:this.streamInfo.getScreenInfo().msid||M.Screen});R&&R.mediaStream&&(this.screenStream=R,this.playAll(!0))}}return{addOption:i,deleteOption:r}}handleAutoPlayFailed(){V.event(`[${Qe.logName}]`,"auto play failed"),this.emit("remoteAudioAutoPlayFail",this.uid);const e=()=>{this.resumeAudio().then(()=>{document.removeEventListener("click",e,!1),document.removeEventListener("touchstart",e,!1)})};document.addEventListener("click",e,!1),document.addEventListener("touchstart",e,!1)}handleVideoPlayFailded(e,t){this.emit("remoteVideoAutoPlayFail",this.uid,t);const i=()=>{var n;const r=(n=t===oe.AliRtcVideoTrackScreen?this.screenStream:this.stream)==null?void 0:n.mediaStream;e.srcObject===r&&this.play(e,t===oe.AliRtcVideoTrackScreen),document.removeEventListener("click",i,!1),document.removeEventListener("touchstart",i,!1)};document.addEventListener("click",i,!1),document.addEventListener("touchstart",i,!1)}playAudio(){return I(this,null,function*(){var e,t;if(this.audioTrack){if(this.toggleAudio(!this.audioMuted),this.audioElement||(V.event(`[${Qe.logName}]`,this.userId,"create audio element"),this.audioElement=document.createElement("audio"),this.audioElement.setAttribute("autoplay","autoplay"),this.audioElement.addEventListener("pause",this.handleAudioPaused),this.setPlayoutVolume(this.playoutVolume)),((t=(e=this.audioElement.srcObject)==null?void 0:e.getAudioTracks())==null?void 0:t[0])!==this.audioTrack){let i=this.audioElement.srcObject;i?i.getAudioTracks().forEach(r=>{i.removeTrack(r)}):(i=new MediaStream,this.audioElement.srcObject=i),i.addTrack(this.audioTrack)}if(X.AliRTS.SystenUtil.isIos&&parseInt(X.AliRTS.SystenUtil.systemVersion)<=13){V.event(`[${Qe.logName}]`,"play audio for iOS 13-");const i=this.audioElement;i.setAttribute("autoplay","");const r=()=>{i.removeEventListener("playing",r),i.pause(),i.play().catch(()=>{this.handleAutoPlayFailed()})};this.audioElement.addEventListener("playing",r)}else(()=>{var i;V.event(`[${Qe.logName}]`,"try play audio"),(i=this.audioElement)==null||i.play().then(()=>{V.event(`[${Qe.logName}]`,"play audio success")}).catch(()=>{this.handleAutoPlayFailed()})})()}else V.event(`[${Qe.logName}]`,this.userId,"audio track is null")})}stopPlayAudio(){this.audioElement&&(this.audioElement.pause(),this.audioElement.removeEventListener("pause",this.handleAudioPaused))}playAll(e=!1,t=!1){e?(this.viewMap.screenViews||[]).forEach(i=>{this.play(i,e,t)}):(this.viewMap.cameraViews||[]).forEach(i=>{this.play(i,e,t)})}play(e,t=!1,i=!1){const r=t?this.screenStream:this.stream;e&&r&&r.mediaStream&&Xa(e,r.mediaStream,i).catch(n=>{n.code!==20&&n.name!=="AbortError"&&this.handleVideoPlayFailded(e,t?oe.AliRtcVideoTrackScreen:oe.AliRtcVideoTrackCamera)})}stopPlayAll(e=!1){e?this.viewMap.screenViews.forEach(t=>{_t(t)}):this.viewMap.cameraViews.forEach(t=>{_t(t)})}toggleAudio(e=!0){this.audioSubState.setEnabled(e),this.audioElement&&(this.audioElement.muted=!e)}toggleVideo(e=!0){this.videoSubState.setEnabled(e),this.stream&&(e?this.stream.enableVideo():this.stream.disableVideo())}toggleScreen(e=!0){this.screenSubState.setEnabled(e),this.screenStream&&(e?this.screenStream.enableVideo():this.screenStream.disableVideo())}getStats(){return I(this,null,function*(){var i,r,n,c,o;const e=[];if(this.isAudioSubscribing){const d=yield this.rtsManager.getSubscribeAudioStats(this.streamUrl);d&&e.push({uid:this.uid,track:Jt.AliRtcAudioTrackMic,stats:d})}const t=[];if((i=this.streamInfo)!=null&&i.isVideoLargeSubscribed){const d=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,((r=this.streamInfo.getVideoLargeInfo())==null?void 0:r.msid)||M.VideoLarge);d&&t.push({uid:this.uid,track:oe.AliRtcVideoTrackCamera,streamType:ze.AliRtcVideoStreamTypeHigh,stats:d})}if((n=this.streamInfo)!=null&&n.isVideoSmallSubscribed){const d=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,((c=this.streamInfo.getVideoSmallInfo())==null?void 0:c.msid)||M.VideoSmall);d&&t.push({uid:this.uid,track:oe.AliRtcVideoTrackCamera,streamType:ze.AliRtcVideoStreamTypeLow,stats:d})}if(this.isScreenSubscribing){const d=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,((o=this.streamInfo.getScreenInfo())==null?void 0:o.msid)||M.Screen);d&&t.push({uid:this.uid,track:oe.AliRtcVideoTrackScreen,stats:d})}return{audio:e,video:t}})}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.audioLevelMonitor.stop(),e>0&&this.audioTrack&&this.audioLevelMonitor.start(this.audioTrack,e),this.audioVolumeIndicationInterval=e)}reportSubscribeMonitor(e){var t;e&&(this.slsReporter.reportSubscribeMonitor(((t=this.localUser)==null?void 0:t.callId)||"",this.callId,this.trackTraceIdMap[e]||"",e,this.monitorDataCache[e]),this.monitorDataCache[e]=[])}startStreamMonitor(){this.monitorTimerId||(this.monitorTimerId=window.setInterval(()=>I(this,null,function*(){try{if(this.streamInfo.subscribingInfos.length===0)return void this.stopStreamMonitor();let e=Object.keys(this.monitorDataCache).filter(t=>{var i;return((i=this.monitorDataCache[t])==null?void 0:i.length)>0});this.streamInfo.subscribingInfos.forEach(t=>{const i=t.msid;if(!i)return;let r;e.includes(i)&&(e=e.filter(c=>c!==i));const n=i===M.Audio;r=n?this.rtsManager.getSubscribeAudioStats(this.streamUrl):this.rtsManager.getSubscribeVideoStats(this.streamUrl,i),r.then(c=>{var l;if(!c.timestamp)return;this.monitorDataCache[i]||(this.monitorDataCache[i]=[]);const o=this.monitorDataCache[i];let d;if((o==null?void 0:o.length)>0){const p=o[o.length-1]||{},h=p,{_last:u}=h;d=jt(h,["_last"])}(o==null?void 0:o.length)>=30&&this.reportSubscribeMonitor(i),c._last=d,c._codec=t.codec,n&&(c._source=(l=this.localUser)==null?void 0:l.getMediaStats(c.playoutId)),this.monitorDataCache[i].push(c)})}),e.forEach(t=>{this.reportSubscribeMonitor(t)})}catch(e){}}),1e3))}stopStreamMonitor(){this.monitorTimerId&&(clearInterval(this.monitorTimerId),this.monitorTimerId=void 0),Object.keys(this.monitorDataCache).forEach(e=>{this.reportSubscribeMonitor(e)})}},g(Qe,"logName","RemoteUser"),Qe);Ke([C()],We.prototype,"clear",1),Ke([C()],We.prototype,"updateRemoteUserDeviceStatus",1),Ke([C()],We.prototype,"updateRemoteTracks",1),Ke([C(H)],We.prototype,"subscribe",1),Ke([C()],We.prototype,"subscribeProxy",1),Ke([C(H)],We.prototype,"subscribeDeleteProxy",1),Ke([C()],We.prototype,"restore",1),Ke([C(H)],We.prototype,"resumeAudio",1),Ke([C(H)],We.prototype,"stopSubscribe",1),Ke([C(H)],We.prototype,"doStopSubscribe",1),Ke([C()],We.prototype,"clearStream",1),Ke([C()],We.prototype,"clearScreenStream",1),Ke([C()],We.prototype,"updateSubscribe",1),Ke([C()],We.prototype,"playAudio",1),Ke([C()],We.prototype,"stopPlayAudio",1),Ke([C((s,a,e)=>[typeof s=="string"?s:s==null?void 0:s.nodeType,a||"-",e||"-"])],We.prototype,"play",1),Ke([C()],We.prototype,"stopPlayAll",1);let Jo=We;var Ot=(s=>(s[s.AliRtcPluginErrorCodeSuccess=0]="AliRtcPluginErrorCodeSuccess",s[s.AliRtcPluginErrorCodeFailed=-1]="AliRtcPluginErrorCodeFailed",s[s.AliRtcPluginErrorNoFindPlugin=-2]="AliRtcPluginErrorNoFindPlugin",s[s.AliRtcPluginErrorParameterError=-3]="AliRtcPluginErrorParameterError",s[s.AliRtcPluginErrorLoadError=-4]="AliRtcPluginErrorLoadError",s[s.AliRtcPluginErrorCreateError=-5]="AliRtcPluginErrorCreateError",s[s.AliRtcPluginErrorInitError=-6]="AliRtcPluginErrorInitError",s[s.AliRtcPluginErrorInitTokenError=-7]="AliRtcPluginErrorInitTokenError",s))(Ot||{});class Go extends se{constructor(){super(...arguments);g(this,"plugins",new Map)}add(e,t){if(this.plugins.has(e.name))throw new O(Ot.AliRtcPluginErrorCreateError,`Plugin ${e.name} already exists`);this.plugins.set(e.name,e),t&&e.setOptions(t),this.emit("added",e),e.on("enabled",()=>this.emit("added",e)),e.on("disabled",()=>this.emit("removed",e)),e.on("updated",()=>this.emit("updated",e))}remove(e){const t=this.plugins.get(e);if(!t)throw new O(Ot.AliRtcPluginErrorNoFindPlugin,`Plugin ${e} not founded`);this.plugins.delete(e),t.removeAllListeners(),this.emit("removed",t)}removeAll(){this.plugins.forEach(e=>{this.remove(e.name)})}get(e){return this.plugins.get(e)}has(e){return!!this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}}var qo=Object.defineProperty,Xo=Object.getOwnPropertyDescriptor,Be=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?Xo(a,e):a,n=s.length-1;n>=0;n--)(i=s[n])&&(r=(t?i(a,e,r):i(r))||r);return t&&r&&qo(a,e,r),r};const zi=([s])=>{const{remoteUser:a,options:e}=s;return[`user(${a.userId})`,e]},xe=(Te=class extends se{constructor(e,t,i){super();g(this,"rts");g(this,"encodedInsertableStreams",!0);g(this,"audioRedEnabled",!1);g(this,"localStreamManager");g(this,"slsReporter");g(this,"_rtsPeerConnectionType","publish");g(this,"connecting",!1);g(this,"connected",!1);g(this,"rtsDisconnected",!1);g(this,"_pcTraceId","");g(this,"_localJoinTime",0);g(this,"connectionResolve");g(this,"connectingPromise");g(this,"dcResolve");g(this,"dcReject");g(this,"dcConnectingPromise");g(this,"_publishingTracks",[]);g(this,"parameter",{});g(this,"preferredPubL1Ip");g(this,"preferredSubL1Ip");this.localStreamManager=e,this.slsReporter=t,this.parameter=i,this.rts=X.AliRTS.createClient({singlePcConfig:{usePcReconnect:!0},datachannelDelayOpen:!0}),this.addRTSListener()}addRTSListener(){this.rts.on("connectStatusChange",e=>{var t,i,r,n;if(V.event(`[${Te.logName}]`,"rts connectStatusChange to:",e.status),e.status===X.EConnectStatus.CONNECT_STATUS_DISCONNECTED)this.dcReject&&this.dcReject(),this.setConnected(!1),this.rtsDisconnected=!0,this.slsReporter.reportWarning("rts disconnected"),this.emit("disconnected");else if(e.status===X.EConnectStatus.CONNECT_STATUS_CONNECTED){if(this.rtsDisconnected){const c=(n=(r=(i=(t=this.rts.commonController)==null?void 0:t.peerCore)==null?void 0:i.getSignal())==null?void 0:r.getDatachannelCore())==null?void 0:n.readyState;V.event(`[${Te.logName}]`,"dcReadyState:",c),c==="open"&&this.dcResolve&&this.dcResolve(!0)}this.rtsDisconnected=!1,this.setConnected(!0)}}),this.rts.on("reconnectFinish",()=>{V.event(`[${Te.logName}]`,"rts reconnectFinish");try{this.emit("connected",!0,this._rtsPeerConnectionType)}catch(e){V.error(`[${Te.logName}]`,"emit connected error:",e)}}),this.rts.on("datachannelStatusChange",e=>{V.event(`[${Te.logName}]`,"rts datachannelStatusChange to:",e.status),e.status===X.EDatachannelStatus.DATACHANNEL_STATUS_OPEN?this.dcResolve&&this.dcResolve(!0):e.status===X.EDatachannelStatus.DATACHANNEL_STATUS_CLOSE&&(this.dcReject&&this.dcReject(),this.dcConnectingPromise=new Promise((t,i)=>{this.dcResolve=t,this.dcReject=i}))}),this.rts.on("receivedSEI",e=>{var t;if(this.emit("seimessage",e.url,e.sei.payloadType,e.sei.data),e.sei.payloadType===99)try{const i=JSON.parse(new TextDecoder().decode(e.sei.data));this.slsReporter.reportLoopAudioDelay(((t=this.publishingTracks.find(r=>r.type==="audio"))==null?void 0:t.ssrc)||"",i)}catch(i){}}),this.rts.on("onError",e=>{V.event(`[${Te.logName}]`,"rts onError event:",e)}),this.rts.on("reconnect",e=>{V.event(`[${Te.logName}]`,"rts reconnect event:",e)})}updateAuth(e){this.rts.updateAuth(e)}get pcTraceId(){return this._pcTraceId}set localJoinTime(e){this._localJoinTime=e}setEncodedInsertableStreams(e){this.encodedInsertableStreams=e}setReceiverPreferredVideoCodecH265(){var r;let e=(r=RTCRtpReceiver.getCapabilities("video"))==null?void 0:r.codecs;if(!e||e.length===0)return;const t=e.filter(n=>n.mimeType.toLowerCase()!=="video/rtx");let i=t.findIndex(n=>n.mimeType==="video/H265");if(i+1){let n=t[i];t.splice(i,1),t.unshift(n),this.rts.setReceiverCodecPreferences({video:t})}}setSenderPreferredVideoCodecH265(){var r;let e=(r=RTCRtpSender.getCapabilities("video"))==null?void 0:r.codecs;if(!e||e.length===0)return;const t=e.filter(n=>n.mimeType.toLowerCase()!=="video/rtx");let i=t.findIndex(n=>n.mimeType==="video/H265");if(i+1){let n=t[i];t.splice(i,1),t.unshift(n),this.rts.setSenderCodecPreferences({video:t})}}supportVideoCodec(e){var t,i,r;return e===lt.H265?(t=RTCRtpSender.getCapabilities("video"))==null?void 0:t.codecs.some(n=>n.mimeType==="video/H265"):e===lt.H264?(i=RTCRtpSender.getCapabilities("video"))==null?void 0:i.codecs.some(n=>n.mimeType==="video/H264"):e===lt.AV1&&((r=RTCRtpSender.getCapabilities("video"))==null?void 0:r.codecs.some(n=>n.mimeType==="video/AV1"))}changeVideoCodec(e){this.supportVideoCodec(e)?(V.info(`[${Te.logName}]`,"changeVideoCodec to:",e),lt.H265===e&&(this.setSenderPreferredVideoCodecH265(),this.setReceiverPreferredVideoCodecH265())):V.warn(`[${Te.logName}]`,`not support video codec: ${e}`)}setAudioRedEnabled(e){var t;if(e!==this.audioRedEnabled){try{const i=[...((t=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:t.codecs)||[]];if(i.length>0){if(e){const r=i.findIndex(c=>c.mimeType==="audio/red"),n=i.findIndex(c=>c.mimeType==="audio/opus");if(r>-1&&n>-1&&r>n){const c=i[n];i[n]=i[r],i[r]=c}}this.rts.setSenderCodecPreferences({audio:i}),this.rts.setReceiverCodecPreferences({audio:i})}}catch(i){}this.audioRedEnabled=e}}clear(){this.setConnected(!1),this.rtsDisconnected=!1,this._publishingTracks=[];try{this.rts.removeAllListeners(),this.rts.unpublish(),this.rts.unsubscribe()}catch(e){}this.rts=X.AliRTS.createClient(),this.addRTSListener()}startConnect(){this.connecting=!0,this.connectingPromise=new Promise(e=>{this.connectionResolve=e}),this.dcConnectingPromise=new Promise((e,t)=>{this.dcResolve=e,this.dcReject=t})}setConnected(e){var t;this.connected=e,this.connecting=!1,(t=this.connectionResolve)==null||t.call(this,!0)}get isConnecting(){return this.connecting}get isConnected(){return this.connected}get publishingTracks(){return this._publishingTracks}getPubMsid(e,t){const{aMsid:i,vMsid:r}=t!=null?t:{},n={};return e.hasAudio&&(n.aMsid=[i!=null?i:M.Audio]),e.hasScreen&&(n.vMsid=[M.Screen]),e.hasVideo&&(n.vMsid=[r!=null?r:t!=null&&t.isScreen?M.Screen:M.VideoLarge]),n}updatePublishingTracks(e){e&&(this._publishingTracks=e.map(({msid:t,from:i,ssrc:r,codec:n,type:c,trackId:o})=>({msid:t,from:i,type:c,ssrc:`${r}`,codec:n!=null?n:"",trackId:o})))}httpPublish(n,c){return I(this,arguments,function*(e,t,i=!1,r=yt.MANUAL){let o;const d=Date.now();this.startConnect();const{publishStream:h,videoSmallStream:l,screenStream:p,vMsid:u}=yield this.localStreamManager.createHTTPPublishStream();if(!h)return V.warn(`[${Te.logName}]`,"publishStream is null"),{traceId:"",l1ip:o};const f=this.getPubMsid(h,{vMsid:u});f.answerSdpHook=_=>{const w=/\d+\.\d+\.\d+\.\d+(?=\s+1106|\s+8000)/.exec(_);return w!=null&&w[0]&&(o=w[0]),_},this.handleHTTPConfig(f),this._rtsPeerConnectionType="publish";let m=!h.hasVideo,b=u,S="";const v=Date.now();try{S=yield this.rts.publish(Er(e,this.preferredPubL1Ip),h,f)}catch(_){this.setConnected(!1);const w=2e3-(Date.now()-v);throw w<=0?this.emit("disconnected"):setTimeout(()=>{this.emit("disconnected")},w),this.slsReporter.reportPublish(i,e,t,h.hasVideo&&(!u||u===M.VideoLarge),h.hasVideo&&u===M.VideoSmall,h.hasVideo&&u===M.Screen,h.hasAudio,(_==null?void 0:_.errorCode)||-1,this.pcTraceId,"",v),O.fromRtsError(_)}V.event(`[${Te.logName}]`,"rts publish success",S),this.slsReporter.reportPublish(i,e,t,h.hasVideo&&(!u||u===M.VideoLarge),h.hasVideo&&u===M.VideoSmall,h.hasVideo&&u===M.Screen,h.hasAudio,0,S,S,v),this.slsReporter.reportConnectionLatencyEvent(ot.HANDLE_PUB_TASK,ht.START,t,S,d),this.slsReporter.reportConnectionLatencyEvent(ot.HANDLE_PUB_TASK,ht.END,t,S,Date.now());try{const _=Date.now();return this._pcTraceId=S,this.setConnected(!0),this._publishingTracks=this.rts.getPublishTrackInfoList(),l&&(yield this.publishAdd(e,l,t,{vMsid:M.VideoSmall},i),m=!1,b=M.VideoSmall),p&&(yield this.publishAdd(e,p,t,{vMsid:M.Screen},i),m=!1,b=M.Screen),yield this.waitPublishSender(e,m,b),this.slsReporter.reportPublishFirstPacket(i,t,v,_,this._localJoinTime,m?M.Audio:f.vMsid,S||"",S||"",r),{traceId:S,l1ip:o}}catch(_){throw this.setConnected(!1),O.fromError(_)}})}waitPublishSender(e,t=!1,i){return I(this,null,function*(){return Promise.race([xt(1e3),((r,n)=>{let c=0;const o=()=>(t?this.rts.getPublishAudioStats(e,i):this.rts.getPublishVideoStats(e,i)).then(d=>!(d.bytesSent>0)&&c<r?(c++,new Promise(h=>setTimeout(()=>h(o()),n))):Promise.resolve());return o()})(5,100)]).catch(()=>{})})}getPublishVideoStats(e,t){return I(this,null,function*(){return yield this.rts.getPublishVideoStats(e,t)})}getPublishAudioStats(e,t){return I(this,null,function*(){return yield this.rts.getPublishAudioStats(e,t)})}publishAdd(d,h,l,p){return I(this,arguments,function*(e,t,i,r,n=!1,c=!1,o=yt.MANUAL){var m,b,S,v,_,w,y,A;yield this.dcConnectingPromise;const u=Date.now(),f=this.getPubMsid(t,r);try{const R=yield qa(E=>I(this,null,function*(){return E>0&&V.event(`[${Te.logName}]`,`publishAdd retry times: ${E}`),this.isConnected?(yield this.dcConnectingPromise,this.rts.publishAdd([G({url:e,stream:t,updateSourceStream:!1},f)])):Promise.reject(new O(U.ERR_INNER,"rts not connected"))}),10,0,E=>(E==null?void 0:E.errorCode)===15006);if(R){const E=Date.now(),[T]=R;return this.slsReporter.reportPublish(!1,e,i,((m=f.vMsid)==null?void 0:m[0])===M.VideoLarge,((b=f.vMsid)==null?void 0:b[0])===M.VideoSmall,((S=f.vMsid)==null?void 0:S[0])===M.Screen,((v=f.aMsid)==null?void 0:v[0])===M.Audio,0,this.pcTraceId,T.traceId||"",u),this.updatePublishingTracks(T.trackInfoList),c&&(yield this.waitPublishSender(e,!t.hasVideo,t.hasVideo?r==null?void 0:r.vMsid:r==null?void 0:r.aMsid)),this.slsReporter.reportPublishFirstPacket(n,i,u,E,this._localJoinTime,(t.hasVideo?r==null?void 0:r.vMsid:r==null?void 0:r.aMsid)||"",this.pcTraceId,T.traceId||"",o),T.traceId||""}}catch(R){throw this.slsReporter.reportPublish(!1,e,i,((_=f.vMsid)==null?void 0:_[0])===M.VideoLarge,((w=f.vMsid)==null?void 0:w[0])===M.VideoSmall,((y=f.vMsid)==null?void 0:y[0])===M.Screen,((A=f.aMsid)==null?void 0:A[0])===M.Audio,(R==null?void 0:R.errorCode)||-1,this.pcTraceId,"",u),R!=null&&R.errorCode?O.fromRtsError(R):O.fromError(R)}return""})}publishDelete(e,t){return I(this,null,function*(){var d,h,l,p,u,f,m,b;yield this.dcConnectingPromise;const i=(h=(d=this.publishingTracks)==null?void 0:d.find(({msid:S})=>S===M.Audio))==null?void 0:h.msid,r=(p=(l=this.publishingTracks)==null?void 0:l.find(({msid:S})=>S===M.VideoLarge))==null?void 0:p.msid,n=(f=(u=this.publishingTracks)==null?void 0:u.find(({msid:S})=>S===M.Screen))==null?void 0:f.msid,c=[];t.screen&&n?c.push(n):t.video&&c.push(t.vMsid||r);const o=[];t.audio&&i&&o.push(i),V.event(Te.logName,"publishDelete",{streamUrl:e,aMsid:o,vMsid:c});try{const[S]=(yield this.rts.publishDeleteTracks([{url:e,aMsid:o,vMsid:c}]))||[];return V.event(Te.logName,"publishDelete",{result:S}),S&&this.updatePublishingTracks(S.trackInfoList),((b=(m=S==null?void 0:S.trackInfoList)==null?void 0:m[0])==null?void 0:b.trackId)||""}catch(S){throw O.fromRtsError(S)}})}publishReplace(e,t,i){return I(this,null,function*(){var c,o;yield this.dcConnectingPromise;const{vMsid:r,aMsid:n}=i!=null?i:{};try{const d=yield this.rts.publishReplaceTracks([{url:e,stream:t,vMsid:r,aMsid:n}]),[h]=d;return this.updatePublishingTracks(h.trackInfoList),((o=(c=h==null?void 0:h.trackInfoList)==null?void 0:c[0])==null?void 0:o.trackId)||""}catch(d){throw O.fromRtsError(d)}})}publishStop(e){return I(this,null,function*(){return yield this.rts.publishStop([{url:e}]),this._publishingTracks=[],""})}publishAddDataChannel(e){return I(this,null,function*(){yield this.dcConnectingPromise;const t=yield this.rts.publishAddDatachannel({signalUrl:e,url:Er(e,this.preferredPubL1Ip),label:M.Data,msid:M.Data}),i=t==null?void 0:t.datachannel;if(i&&i.send){const r=new ArrayBuffer(4);new DataView(r).setUint8(0,240),i.datachannel.send(r)}return i})}publishStopDataChannel(e,t){return I(this,null,function*(){return yield this.rts.publishStopDatachannel({url:e,datachannel:t})})}unpublish(){return I(this,null,function*(){yield this.rts.unpublish(),this._publishingTracks=[],this.connecting=!1,this.connected=!1})}getSubConfig(e,t){let i=t!=null?t:{};t||(i={audio:!0,video:!0,screen:!0});const r={};return i.audio&&(r.aMsid=[(e==null?void 0:e.getAudioInfo().msid)||M.Audio]),i.video?i.vMsid?r.vMsid=[i.vMsid]:r.vMsid=e!=null&&e.hasVideoLarge?[(e==null?void 0:e.getVideoLargeInfo().msid)||M.VideoLarge]:e!=null&&e.hasVideoSmall?[(e==null?void 0:e.getVideoSmallInfo().msid)||M.VideoSmall]:[M.VideoLarge]:i.screen&&(r.vMsid=[(e==null?void 0:e.getScreenInfo().msid)||M.Screen]),r}handleHTTPConfig(e){var t,i,r,n,c,o,d,h,l,p;if(this.encodedInsertableStreams&&(e.encodedInsertableStreams=!0),(i=(t=this.parameter)==null?void 0:t.net)!=null&&i.useTCP&&(e.tcpOnly=!0),(n=(r=this.parameter)==null?void 0:r.net)!=null&&n.cumuDelay&&(e.cumuDelay=!0),(o=(c=this.parameter)==null?void 0:c.net)!=null&&o.disableHeartbeat&&(e.disableHeartbeat=!0),(h=(d=this.parameter)==null?void 0:d.net)==null?void 0:h.mediaTimeout){const u=(p=(l=this.parameter)==null?void 0:l.net)==null?void 0:p.mediaTimeout;u>1e3&&u<1e5&&(e.mediaTimeout=u)}e.retryTimes=17,e.retryInterval=5e3}httpSubscribe(e){return I(this,null,function*(){var c,o;const{remoteUser:t,options:i}=e;let r=t.streamUrl;i.video||i.screen?i!=null&&i.audio||(r+="@subaudio=no"):r+="@subvideo=no";const n=this.getSubConfig(t.streamInfo,i);this.handleHTTPConfig(n),this._rtsPeerConnectionType="subscribe",(o=(c=this.parameter)==null?void 0:c.net)!=null&&o.rrtr&&(n.offerSdpHook=d=>{const h=d.replace(/(a=rtpmap:(\d+).*\r\n)/g,`$1a=rtcp-fb:$2 rrtr\r
129
+ `).join("");R+=P}catch(P){}R+=m,v.size>0&&(R+="?");try{R+=[...v.entries()].sort(E).map(P=>P[0]+"="+P[1]).join("&")}catch(P){}const k="LOG "+b+":"+hi.HmacSHA1(R,S).toString(hi.enc.Base64);_.set("Authorization",k),_.set("x-log-date",y)}("POST",n,s.accessKeyId,s.accessKeySecret,l,p,o,h);let u=Object.fromEntries(p);return{data:e,header:u}},new Promise((n,c)=>{var o=l=>{try{h(r.next(l))}catch(p){c(p)}},d=l=>{try{h(r.throw(l))}catch(p){c(p)}},h=l=>l.done?n(l.value):Promise.resolve(l.value).then(o,d);h((r=r.apply(t,i)).next())});var t,i,r}}}typeof window!="undefined"&&Ps(window,"stsPlugin",fr);var yo=/d{1,4}|D{3,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|W{1,2}|[LlopSZN]|"[^"]*"|'[^']*'/g,Ao=/\b(?:[A-Z]{1,3}[A-Z][TC])(?:[-+]\d{4})?|((?:Australian )?(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time)\b/g,Ro=/[^-+\dA-Z]/g;function Sr(s,a,e,t){if(arguments.length!==1||typeof s!="string"||/\d/.test(s)||(a=s,s=void 0),(s=s||s===0?s:new Date)instanceof Date||(s=new Date(s)),isNaN(s))throw TypeError("Invalid date");var i=(a=String(Va[a]||a||Va.default)).slice(0,4);i!=="UTC:"&&i!=="GMT:"||(a=a.slice(4),e=!0,i==="GMT:"&&(t=!0));var r=function(){return e?"getUTC":"get"},n=function(){return s[r()+"Date"]()},c=function(){return s[r()+"Day"]()},o=function(){return s[r()+"Month"]()},d=function(){return s[r()+"FullYear"]()},h=function(){return s[r()+"Hours"]()},l=function(){return s[r()+"Minutes"]()},p=function(){return s[r()+"Seconds"]()},u=function(){return s[r()+"Milliseconds"]()},f=function(){return e?0:s.getTimezoneOffset()},m=function(){return _o(s)},b={d:function(){return n()},dd:function(){return at(n())},ddd:function(){return et.dayNames[c()]},DDD:function(){return Oa({y:d(),m:o(),d:n(),_:r(),dayName:et.dayNames[c()],short:!0})},dddd:function(){return et.dayNames[c()+7]},DDDD:function(){return Oa({y:d(),m:o(),d:n(),_:r(),dayName:et.dayNames[c()+7]})},m:function(){return o()+1},mm:function(){return at(o()+1)},mmm:function(){return et.monthNames[o()]},mmmm:function(){return et.monthNames[o()+12]},yy:function(){return String(d()).slice(2)},yyyy:function(){return at(d(),4)},h:function(){return h()%12||12},hh:function(){return at(h()%12||12)},H:function(){return h()},HH:function(){return at(h())},M:function(){return l()},MM:function(){return at(l())},s:function(){return p()},ss:function(){return at(p())},l:function(){return at(u(),3)},L:function(){return at(Math.floor(u()/10))},t:function(){return h()<12?et.timeNames[0]:et.timeNames[1]},tt:function(){return h()<12?et.timeNames[2]:et.timeNames[3]},T:function(){return h()<12?et.timeNames[4]:et.timeNames[5]},TT:function(){return h()<12?et.timeNames[6]:et.timeNames[7]},Z:function(){return t?"GMT":e?"UTC":Eo(s)},o:function(){return(f()>0?"-":"+")+at(100*Math.floor(Math.abs(f())/60)+Math.abs(f())%60,4)},p:function(){return(f()>0?"-":"+")+at(Math.floor(Math.abs(f())/60),2)+":"+at(Math.floor(Math.abs(f())%60),2)},S:function(){return["th","st","nd","rd"][n()%10>3?0:(n()%100-n()%10!=10)*n()%10]},W:function(){return m()},WW:function(){return at(m())},N:function(){return wo(s)}};return a.replace(yo,function(S){return S in b?b[S]():S.slice(1,S.length-1)})}var Va={default:"ddd mmm dd yyyy HH:MM:ss",shortDate:"m/d/yy",paddedShortDate:"mm/dd/yyyy",mediumDate:"mmm d, yyyy",longDate:"mmmm d, yyyy",fullDate:"dddd, mmmm d, yyyy",shortTime:"h:MM TT",mediumTime:"h:MM:ss TT",longTime:"h:MM:ss TT Z",isoDate:"yyyy-mm-dd",isoTime:"HH:MM:ss",isoDateTime:"yyyy-mm-dd'T'HH:MM:sso",isoUtcDateTime:"UTC:yyyy-mm-dd'T'HH:MM:ss'Z'",expiresHeaderFormat:"ddd, dd mmm yyyy HH:MM:ss Z"},et={dayNames:["Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],monthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","January","February","March","April","May","June","July","August","September","October","November","December"],timeNames:["a","p","am","pm","A","P","AM","PM"]},at=function(s){var a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:2;return String(s).padStart(a,"0")},Oa=function(s){var a=s.y,e=s.m,t=s.d,i=s._,r=s.dayName,n=s.short,c=n!==void 0&&n,o=new Date,d=new Date;d.setDate(d[i+"Date"]()-1);var h=new Date;return h.setDate(h[i+"Date"]()+1),o[i+"FullYear"]()===a&&o[i+"Month"]()===e&&o[i+"Date"]()===t?c?"Tdy":"Today":d[i+"FullYear"]()===a&&d[i+"Month"]()===e&&d[i+"Date"]()===t?c?"Ysd":"Yesterday":h[i+"FullYear"]()===a&&h[i+"Month"]()===e&&h[i+"Date"]()===t?c?"Tmw":"Tomorrow":r},_o=function(s){var a=new Date(s.getFullYear(),s.getMonth(),s.getDate());a.setDate(a.getDate()-(a.getDay()+6)%7+3);var e=new Date(a.getFullYear(),0,4);e.setDate(e.getDate()-(e.getDay()+6)%7+3);var t=a.getTimezoneOffset()-e.getTimezoneOffset();a.setHours(a.getHours()-t);var i=(a-e)/6048e5;return 1+Math.floor(i)},wo=function(s){var a=s.getDay();return a===0&&(a=7),a},Eo=function(s){return(String(s).match(Ao)||[""]).pop().replace(Ro,"").replace(/GMT\+0000/g,"UTC")},Mi=(s=>(s.prod="rs.rtn.aliyuncs.com",s.pre="prs.rtn.aliyuncs.com",s))(Mi||{});const Li="7.1.9";class nt{static getVersionNumber(){let a=Li.split("."),e="";return a.forEach(t=>{t.length===1?e+="0"+t:e+=t}),parseInt(e)}static queryingParam(a){let e=[];if(a)for(let t in a)e.push(t+"="+a[t]);return e.join("&")}static getQueryParams(a){const e=window.location.search.substring(1).split("&");for(let t=0;t<e.length;t++){const i=e[t].split("=");if(decodeURIComponent(i[0])===a)return decodeURIComponent(i[1])}}static createCallid(a=""){const e=dt();return a&&e&&e.length>a.length?`${a}${e.substring(a.length)}`:e}static checkSubOptionsValid(a){if(a){const{audio:e,video:t,screen:i}=a;if(e===!1&&t===!1&&i===!1)return!1}return!0}static isNetworkAvailable(){return I(this,null,function*(){const a=Mi.prod,{onLine:e}=navigator;if(!e)return!1;try{return yield fetch(`https://${a}/roomserver/v1/ws/version`),!0}catch(t){return!1}})}static toString(a){let e;if(a instanceof Error)e=a.message;else if(typeof a=="string")e=a;else try{e=JSON.stringify(a)}catch(t){e="undefined"}return e}static paramArrayToString(a){let e="";for(let t=0;t<a.length;t++)e!==""&&(e+=" "),e+=nt.toString(a[t]);return e}}const{BrowserUtil:To}=X.AliRTS,Io="EdgeHTML",Ua="Blink",Co="Trident",ko="Gecko",Po="WebKit",Ni=(s,a)=>{const e=a.match(s);return e&&e.length>0&&e[1]||""},Do=[{test:[/\sedg\//i,[/edg([ea]|ios)/i]],describe(s){if(/\sedg\//i.test(s))return{name:Ua};const a=Ni(/edge\/(\d+(\.?_?\d+)+)/i,s);return{name:Io,version:a}}},{test:[/trident/i],describe(s){const a={name:Co},e=Ni(/trident\/(\d+(\.?_?\d+)+)/i,s);return e&&(a.version=e),a}},{test(s){const a=/gecko/i.test(s),e=/like gecko/i.test(s);return a&&!e},describe(s){const a={name:ko},e=Ni(/gecko\/(\d+(\.?_?\d+)+)/i,s);return e&&(a.version=e),a}},{test:[/(apple)?webkit\/537\.36/i],describe:()=>({name:Ua})},{test:[/(apple)?webkit/i],describe(s){const a={name:Po},e=Ni(/webkit\/(\d+(\.?_?\d+)+)/i,s);return e&&(a.version=e),a}}],br=(s,a)=>s.find(e=>typeof e.test=="function"?e.test(a):Array.isArray(e.test)?e.test.some(t=>typeof t=="string"?a.indexOf(t)>-1:t instanceof RegExp&&t.test(a)):void 0),Mo=()=>{try{const s=navigator.userAgent||"",a=br(Do,s);if(a){const e=a.describe(s);return`${e.name}/${e.version||To.browserVersion}`}}catch(s){}return navigator.userAgent},Lo=[{test:["wow64","win64","x64"],describe:()=>"amd64"},{test:["i686","x86"],describe:()=>"x86"},{test:["aarch64","arm64"],describe:()=>"arm64"},{test:["arm"],describe:()=>"arm"}],Ba=()=>{let s="unknown";try{const a=navigator.userAgent||"",e=br(Lo,a);if(!e)return s;s=e.describe(a)}catch(a){}return s},No=[{test:[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],describe:()=>"Samsung"},{test:[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i,/\((ipad);[-\w\),; ]+apple/i,/(macintosh);/i],describe:()=>"Apple"},{test:[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],describe:()=>"Huawei"},{test:[/(?:honor)([-\w ]+)[;\)]/i],describe:()=>"Honor"},{test:[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],describe:()=>"Xiaomi"},{test:[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],describe:()=>"Oppo"},{test:[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],describe:()=>"Vivo"},{test:[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],describe:()=>"Realme"},{test:[/(pixel c)\b/i,/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],describe:()=>"Google"},{test:[/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],describe:()=>"ZTE"},{test:[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],describe:()=>"Meizu"}],xo=()=>{let s="Unknown";try{const a=navigator.userAgent||"",e=br(No,a);if(!e)return s;s=e.describe(a)}catch(a){}return s},{BrowserUtil:Ha,SystenUtil:Fa}=X.AliRTS,Vo=Ba(),xi=6e5,Vi={host:"cn-hangzhou.log.aliyuncs.com",project:"alivc-aio",logstore:"logger",time:10,count:10};function vr(){return Sr(new Date,"HH:MM:ss.l")}function ja(){return Sr(new Date,"isoDate")}var yr=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.API=2]="API",s[s.WARNING=3]="WARNING",s[s.ERROR=4]="ERROR",s[s.NONE=5]="NONE",s))(yr||{});class Oo{constructor(){g(this,"tracker");g(this,"slsPlugin");g(this,"stsData");g(this,"stsExpiration",Date.now());g(this,"clientId",dt());g(this,"bSesid",dt());g(this,"logLevel",3);g(this,"appId","");g(this,"sessionId","");g(this,"logCache",[]);g(this,"updateTaskTimer");g(this,"endReported",!0);g(this,"logSequence",0);g(this,"sendLogBeforeUnload",a=>I(this,null,function*(){if(!this.slsPlugin)return;this.logSequence+=1,a.unshift(this.getLogParams(710203,{log:`[${ja()} ${vr()}] [INF] beforeunload`,stat_log_seq:this.logSequence}));const e=`https://${Vi.project}.${Vi.host}/logstores/${Vi.logstore}`,t={__logs__:a.map(n=>this.slsPlugin.transString(n))},{data:i,header:r}=yield this.slsPlugin.process(e,JSON.stringify(t));fetch(e,{keepalive:!0,method:"POST",headers:r,body:i})}));g(this,"logMethod",(a,e=console.log)=>(...t)=>{let i=vr();this.logLevel<=a&&e(i,...t);let r=nt.paramArrayToString(t);a>0&&this.addLog(r)});g(this,"d",this.logMethod(0,console.debug));g(this,"i",this.logMethod(1));g(this,"w",this.logMethod(3,console.warn));g(this,"e",this.logMethod(4,(...a)=>{const[e,...t]=a;console.error(e,"<error>",t)}));g(this,"ev",this.logMethod(2));g(this,"a",this.logMethod(2,(...a)=>{const[e,...t]=a;if(t.length>2){const i=`${t[1]}`;i.startsWith("__g__")&&console.group(`${i.substring(5)}_${t[2]}`)}console.log(e,...t)}));g(this,"ar",this.logMethod(2,(...a)=>{const[e,...t]=a;console.log(e,...t),t.length>2&&`${t[1]}`.startsWith("__g__")&&console.groupEnd()}));g(this,"ae",this.logMethod(2,(...a)=>{const[e,...t]=a;console.error(e,"<error>",...t),t.length>2&&`${t[1]}`.startsWith("__g__")&&console.groupEnd()}));window.addEventListener("beforeunload",()=>{this.reportEnd(!0)})}init(){this.reset(),this.startSTSUpdateTask()}destroy(){this.updateTaskTimer&&clearTimeout(this.updateTaskTimer)}reset(){this.bSesid=dt(),this.endReported=!0,this.logSequence=0,this.appId="",this.sessionId=""}startSTSUpdateTask(){return I(this,null,function*(){this.updateTaskTimer&&clearTimeout(this.updateTaskTimer);try{const a=yield this.refreshSTSToken();this.createTracker(a)}catch(a){}this.updateTaskTimer=setTimeout(()=>{this.startSTSUpdateTask()},xi)})}refreshSTSToken(){return I(this,null,function*(){if(!this.stsData||this.stsExpiration<=Date.now()-xi){const a=yield this.requestSTSToken(),e=new Date(a==null?void 0:a.Expiration).getTime()||0,t=Date.now()+xi;this.stsExpiration=Math.max(e,t),this.stsData=a}return this.stsData})}requestSTSToken(){const a=Date.now(),e=`${this.clientId}|woMMssV6jmyol9fr|${a}`,t={Action:"AssumeSlsRoleV2",AuthInfo:hi.MD5(e).toString(hi.enc.Hex),ClientId:this.clientId,BusinessType:"logger",AppVersion:"1.0",Version:"2017-03-14",AuthTimestamp:`${a}`,TerminalType:"web",DeviceModel:"",Format:"JSON",SignatureMethod:"HMAC-SHA1",SignatureVersion:"1.0",Timestamp:Sr(a,"isoUtcDateTime")},i=new URLSearchParams(t).toString();return fetch(`https://slsrole.alicdn.com/?${i}`).then(r=>r.json()).then(r=>JSON.parse(window.atob(r.SlsAuthResult)))}createTracker(a){if(!this.tracker){const e={accessKeyId:a.AccessKeyId,accessKeySecret:a.AccessKeySecret,securityToken:a.SecurityToken,refreshSTSTokenInterval:xi,stsTokenFreshTime:void 0,refreshSTSToken:()=>{this.refreshSTSToken().then(r=>{e.accessKeyId=r.AccessKeyId,e.accessKeySecret=r.AccessKeySecret,e.securityToken=r.SecurityToken}).catch(()=>{})}},t=new pr(Vi),i=fr(e);t.useStsPlugin(i),this.slsPlugin=i,this.tracker=t,this.reportStartAndCache()}}changeConfig(a){a.logLevel!==void 0&&a.logLevel>=0&&a.logLevel<=5&&(this.logLevel=a.logLevel)}setSessionID(a,e){a&&e&&(this.appId=a,this.sessionId=e,this.reportStartAndCache())}reportStartAndCache(){if(!this.tracker||!this.sessionId)return;this.endReported=!1;const a={task_btm_sec:0,task_duration:0,task_etm_sec:0,task_type:"session"},e=[this.getLogParams(710201,a),this.getLogParams(710202,a)];this.tracker.sendBatchLogsImmediate(e),this.logCache.forEach(t=>{this.sendLog(t)})}reportEnd(a=!1){if(!this.tracker||!this.sessionId||this.endReported)return void this.reset();const e={task_btm_sec:0,task_duration:0,task_etm_sec:0,task_type:"session"},t=[this.getLogParams(710204,e),this.getLogParams(710205,e)];a?this.sendLogBeforeUnload(t):(this.tracker.sendBatchLogsImmediate(t),this.endReported=!0),this.reset()}getLogParams(a,e){return G({appid:`${window.location.host}`,appid_list:this.appId,appver:"",b_sesid:this.bSesid,biz_type:"rtc",cpu_info:Vo,db:Ha.browserName,dm:Ha.browserVersion,install_uuid:this.clientId,logger_v:"0.0.1",os:Fa.systemName,osv:Fa.systemVersion,p_sesid:this.bSesid,sdk_version:Li,sdkname:"AliRTCSdk",stm:Date.now(),tar_pf:"web",traceid:this.sessionId,event_id:a},e||{})}sendLog(a){if(!this.tracker||!this.sessionId)return;this.logSequence+=1;const e=this.getLogParams(710203,{log:a,stat_log_seq:this.logSequence});this.tracker.send(e)}addLog(a){const e=vr(),t=`[${ja()} ${e}] ${a}`;this.sessionId&&this.tracker?this.sendLog(t):(this.logCache.push(t),this.logCache.length>=200&&this.logCache.shift())}}class V{static getLogger(){return this.logger||(this.logger=new Oo),this.logger}static init(){this.getLogger().init()}static destroy(){this.getLogger().destroy()}static setLogLevel(a){this.getLogger().changeConfig({logLevel:a})}static setSessionID(a,e){this.getLogger().setSessionID(a,e)}static reportEnd(){this.getLogger().reportEnd()}static interface(...a){this.getLogger().a("[API]",...a)}static interfaceResult(a,e,t,...i){t?this.getLogger().ar("[ARE]",a,e,...i):this.getLogger().ae("[ARE]",a,e,...i)}static event(...a){this.getLogger().ev("[EVT]",...a)}static debug(...a){this.getLogger().d("[DBG]",...a)}static info(...a){this.getLogger().i("[INF]",...a)}static warn(...a){this.getLogger().w("[WARN]",...a)}static error(...a){this.getLogger().e("[ERR]",...a)}}g(V,"logger");var Ee=(s=>(s.PullStreamStats="remoteStat",s.RtsSubscribeExceeds="rtsSubscribeExceeds",s.UserJoined="userJoined",s.UserLeft="userLeft",s.Bye="bye",s.MuteAudio="muteAudio",s.UnmuteAudio="unmuteAudio",s.MuteVideo="muteVideo",s.UnmuteVideo="unmuteVideo",s.MuteScreen="muteScreen",s.UnmuteScreen="unmuteScreen",s.Error="error",s))(Ee||{}),Ye=(s=>(s.Local="local-device-status-change",s.Remote="remote-device-status-change",s))(Ye||{}),M=(s=>(s.Audio="sophon_audio",s.VideoLarge="sophon_video_camera_large",s.VideoSmall="sophon_video_camera_small",s.Screen="sophon_video_screen_share",s.Data="sophon_data",s))(M||{}),Ar=(s=>(s.Audio="rts audio",s.VideoLarge="rts video",s))(Ar||{}),Lt=(s=>(s.Add="add",s.Delete="delete",s.Replace="replace",s.Stop="stop",s.UnPublish="unpublish",s))(Lt||{}),li=(s=>(s[s.Camera=0]="Camera",s[s.Screen=1]="Screen",s[s.Image=2]="Image",s))(li||{}),Oi=(s=>(s[s.Microphone=0]="Microphone",s[s.Screen=1]="Screen",s[s.Mixed=2]="Mixed",s))(Oi||{}),be=(s=>(s.InRoom="inRoom",s.Join="join",s.Publish="publish",s.User="user",s.Resume="resume",s.Retry="retry",s.Reconnect="reconnect",s))(be||{}),yt=(s=>(s[s.MANUAL=0]="MANUAL",s[s.JOIN_CHANNEL=1]="JOIN_CHANNEL",s[s.ROLE_CHANGE=2]="ROLE_CHANGE",s[s.RECONNECT=3]="RECONNECT",s))(yt||{});function ii(){}const Yt=class Yt{static getInstance(){var a;return Yt.instance||(Yt.instance=new AudioContext),(a=Yt.instance.resume())==null||a.then(ii,ii).catch(ii),Yt.instance}};g(Yt,"instance");let Kt=Yt;const Ui=()=>{var a;const s=Kt.getInstance();s.state!=="running"&&s.state!=="closed"&&((a=s.resume())==null||a.then(ii,ii).catch(ii)),window.removeEventListener("mousedown",Ui),window.removeEventListener("touchstart",Ui)};window.addEventListener("mousedown",Ui),window.addEventListener("touchstart",Ui);class Uo extends se{constructor(){super();g(this,"audioContext");g(this,"stream");g(this,"sourceNode");g(this,"analyser");this.audioContext=Kt.getInstance(),this.stream=new MediaStream}getLevel(){return this.analyser?this.analyser.getLevel():0}start(e,t=1e3){this.sourceNode&&this.stop(),this.stream.addTrack(e),this.sourceNode=this.audioContext.createMediaStreamSource(this.stream);const i=this.audioContext.createMediaStreamDestination();this.analyser=function(r,n,c,o,d){let h,l=o,p=0;const u=r.createAnalyser();u.fftSize=256;const f=new Uint8Array(u.frequencyBinCount);n.connect(u),u.connect(c);const m=()=>{h&&window.clearInterval(h)},b=()=>{r.state==="suspended"&&r.resume(),h=window.setInterval(()=>{u.getByteFrequencyData(f);let S=Math.round(f.reduce((v,_)=>v+_)/f.length);S=Math.min(100,S),p=S,d&&d(S)},l)};return b(),{updateInterval:S=>{m(),l=S,b()},getLevel:()=>p,dispose:()=>{m(),n.disconnect(),u.disconnect()}}}(this.audioContext,this.sourceNode,i,t,r=>{this.emit("audioLevel",r)})}stop(){this.analyser&&this.analyser.dispose(),this.analyser=void 0,this.sourceNode=void 0,this.stream.getAudioTracks().forEach(e=>{this.stream.removeTrack(e)})}dispose(){this.stop()}}class za extends se{constructor(e,t,i,r){super();g(this,"uid");g(this,"name");g(this,"rtsManager");g(this,"callId","");g(this,"audioLevelMonitor");g(this,"audioVolumeIndicationInterval",0);this.uid=e,this.name=t,this.rtsManager=i,this.audioVolumeIndicationInterval=r,this.audioLevelMonitor=new Uo}get userId(){return this.uid}get displayname(){return this.name}createCallId(){this.callId||(this.callId=nt.createCallid())}setUserInfo(e,t){this.uid=e,this.name=t}refreshUserInfo(e){this.uid=e}getAudioLevel(){return this.audioLevelMonitor.getLevel()}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval=e}clear(){this.audioLevelMonitor.dispose()}}class Wa{static getCurrentStatus(a){let e=0;a.micOpen&&(e+=1),a.micInterrupted&&(e+=2),a.cameraOpen&&(e+=4),a.screenShare&&(e+=128),a.audioDisable&&(e+=8),a.videoDisable&&(e+=16),a.screenDisable&&(e+=256);let t=e.toString(16);for(;t.length<16;)t="0"+t;return t}static parseStatus(a){let e=parseInt(a,16);return{micOpen:!!(1&e),micInterrupted:!!(2&e),cameraOpen:!!(4&e),screenShare:!!(128&e),audioDisable:!!(8&e),videoDisable:!!(16&e),screenDisable:!!(256&e),backgroundMode:!!(32&e),accompanyPlaying:!!(64&e)}}}var kt=(s=>(s.pre="pre",s.prod="prod",s))(kt||{}),Pt=(s=>(s.AliRtcSdkCommunication="communication",s.AliRtcSdkInteractiveLive="interactive_live",s.AliRtcSdkInteractiveWithLowLatencyLive="cdn_live",s))(Pt||{}),Nt=(s=>(s.AliRtcSdkInteractive="interactive",s.AliRtcSdkLive="live",s))(Nt||{}),At=(s=>(s[s.AliEngineLocalDeviceTypeUnknown=0]="AliEngineLocalDeviceTypeUnknown",s[s.AliEngineLocalDeviceTypeMic=1]="AliEngineLocalDeviceTypeMic",s[s.AliEngineLocalDeviceTypeSpeaker=2]="AliEngineLocalDeviceTypeSpeaker",s[s.AliEngineLocalDeviceTypeAudioDevice=3]="AliEngineLocalDeviceTypeAudioDevice",s[s.AliEngineLocalDeviceTypeCamera=4]="AliEngineLocalDeviceTypeCamera",s[s.AliEngineLocalDeviceTypeDisplay=5]="AliEngineLocalDeviceTypeDisplay",s[s.AliEngineLocalDeviceTypeVideoDevice=6]="AliEngineLocalDeviceTypeVideoDevice",s))(At||{}),Ue=(s=>(s[s.AliEngineLocalDeviceExceptionTypeUnknown=0]="AliEngineLocalDeviceExceptionTypeUnknown",s[s.AliEngineLocalDeviceExceptionTypeMicOpenFail=1]="AliEngineLocalDeviceExceptionTypeMicOpenFail",s[s.AliEngineLocalDeviceExceptionTypeMicInterrupt=2]="AliEngineLocalDeviceExceptionTypeMicInterrupt",s[s.AliEngineLocalDeviceExceptionTypeMicAuthFail=3]="AliEngineLocalDeviceExceptionTypeMicAuthFail",s[s.AliEngineLocalDeviceExceptionTypeMicNotAvailable=4]="AliEngineLocalDeviceExceptionTypeMicNotAvailable",s[s.AliEngineLocalDeviceExceptionTypeSpeakerOpenFail=5]="AliEngineLocalDeviceExceptionTypeSpeakerOpenFail",s[s.AliEngineLocalDeviceExceptionTypeSpeakerInterrupt=6]="AliEngineLocalDeviceExceptionTypeSpeakerInterrupt",s[s.AliEngineLocalDeviceExceptionTypeSpeakerNotAvailable=7]="AliEngineLocalDeviceExceptionTypeSpeakerNotAvailable",s[s.AliEngineLocalDeviceExceptionTypeAudioDeviceException=8]="AliEngineLocalDeviceExceptionTypeAudioDeviceException",s[s.AliEngineLocalDeviceExceptionTypeCameraOpenFail=9]="AliEngineLocalDeviceExceptionTypeCameraOpenFail",s[s.AliEngineLocalDeviceExceptionTypeCameraInterrupt=10]="AliEngineLocalDeviceExceptionTypeCameraInterrupt",s[s.AliEngineLocalDeviceExceptionTypeCameraAuthFail=11]="AliEngineLocalDeviceExceptionTypeCameraAuthFail",s[s.AliEngineLocalDeviceExceptionTypeDisplayException=12]="AliEngineLocalDeviceExceptionTypeDisplayException",s[s.AliEngineLocalDeviceExceptionTypeVideoDeviceException=13]="AliEngineLocalDeviceExceptionTypeVideoDeviceException",s))(Ue||{}),ne=(s=>(s[s.AliRtcConnectionStatusInit=0]="AliRtcConnectionStatusInit",s[s.AliRtcConnectionStatusDisconnected=1]="AliRtcConnectionStatusDisconnected",s[s.AliRtcConnectionStatusConnecting=2]="AliRtcConnectionStatusConnecting",s[s.AliRtcConnectionStatusConnected=3]="AliRtcConnectionStatusConnected",s[s.AliRtcConnectionStatusReconnecting=4]="AliRtcConnectionStatusReconnecting",s[s.AliRtcConnectionStatusFailed=5]="AliRtcConnectionStatusFailed",s))(ne||{}),Rt=(s=>(s[s.AliRtcConnectionChangedDummyReason=0]="AliRtcConnectionChangedDummyReason",s[s.AliRtcConnectionMediaPathChanged=1]="AliRtcConnectionMediaPathChanged",s[s.AliRtcConnectionSignalingHeartbeatTimeout=2]="AliRtcConnectionSignalingHeartbeatTimeout",s[s.AliRtcConnectionSignalingHeartbeatAlive=3]="AliRtcConnectionSignalingHeartbeatAlive",s[s.AliRtcConnectionSignalingHttpDnsResolved=4]="AliRtcConnectionSignalingHttpDnsResolved",s[s.AliRtcConnectionSignalingHttpDnsFailure=5]="AliRtcConnectionSignalingHttpDnsFailure",s[s.AliRtcConnectionSignalingGslbFailure=6]="AliRtcConnectionSignalingGslbFailure",s[s.AliRtcConnectionSignalingGslbSuccess=7]="AliRtcConnectionSignalingGslbSuccess",s[s.AliRtcConnectionSignalingJoinRoomFailure=8]="AliRtcConnectionSignalingJoinRoomFailure",s[s.AliRtcConnectionSignalingJoinRoomSuccess=9]="AliRtcConnectionSignalingJoinRoomSuccess",s[s.AliRtcConnectionSignalingLeaveRoom=10]="AliRtcConnectionSignalingLeaveRoom",s[s.AliRtcConnectionSignalingConnecting=11]="AliRtcConnectionSignalingConnecting",s[s.AliRtcConnectionChangedNetworkInterrupted=12]="AliRtcConnectionChangedNetworkInterrupted",s))(Rt||{}),Rr=(s=>(s[s.AliRtcUserOfflineQuit=0]="AliRtcUserOfflineQuit",s[s.AliRtcUserOfflineDropped=1]="AliRtcUserOfflineDropped",s[s.AliRtcUserOfflineBecomeAudience=2]="AliRtcUserOfflineBecomeAudience",s))(Rr||{}),Jt=(s=>(s[s.AliRtcAudioTrackNo=0]="AliRtcAudioTrackNo",s[s.AliRtcAudioTrackMic=1]="AliRtcAudioTrackMic",s[s.AliRtcAudioTrackDual=2]="AliRtcAudioTrackDual",s))(Jt||{}),oe=(s=>(s[s.AliRtcVideoTrackNo=0]="AliRtcVideoTrackNo",s[s.AliRtcVideoTrackCamera=1]="AliRtcVideoTrackCamera",s[s.AliRtcVideoTrackScreen=2]="AliRtcVideoTrackScreen",s[s.AliRtcVideoTrackBoth=3]="AliRtcVideoTrackBoth",s))(oe||{}),ie=(s=>(s[s.AliRtcStatePublishIdle=0]="AliRtcStatePublishIdle",s[s.AliRtcStateNoPublish=1]="AliRtcStateNoPublish",s[s.AliRtcStatePublishing=2]="AliRtcStatePublishing",s[s.AliRtcStatePublished=3]="AliRtcStatePublished",s))(ie||{}),me=(s=>(s[s.AliRtcStateSubscribeIdle=0]="AliRtcStateSubscribeIdle",s[s.AliRtcStateNoSubscribe=1]="AliRtcStateNoSubscribe",s[s.AliRtcStateSubscribing=2]="AliRtcStateSubscribing",s[s.AliRtcStateSubscribed=3]="AliRtcStateSubscribed",s))(me||{}),ze=(s=>(s[s.AliRtcVideoStreamTypeNone=0]="AliRtcVideoStreamTypeNone",s[s.AliRtcVideoStreamTypeHigh=1]="AliRtcVideoStreamTypeHigh",s[s.AliRtcVideoStreamTypeLow=2]="AliRtcVideoStreamTypeLow",s))(ze||{}),ui=(s=>(s[s.CAMERA_INVALID=-1]="CAMERA_INVALID",s[s.CAMERA_REAR=0]="CAMERA_REAR",s[s.CAMERA_FRONT=1]="CAMERA_FRONT",s))(ui||{});const C=(s,a)=>(e,t,i)=>{const r=i.value;return i.value=function(...n){var l;const c=`[${((l=e.constructor)==null?void 0:l.logName)||""}]`,o=Date.now();let d=[];if(s)try{d=s(n)}catch(p){}V.interface(c,t,...d);const h=r.apply(this,n);return Promise.resolve(h).then(p=>p).catch(p=>p).then(p=>{var b;let u="";const f=p instanceof Error,m=f&&((b=e.constructor)==null?void 0:b.logError);if(a||f){if(m)u=p;else if(f)u=p.message||"";else{if(!a)return;if(p===void 0)u="";else try{u=a(p)}catch(S){}}V.interfaceResult(c,t,!(f&&m),Date.now()-o+"ms",u)}}),h},i},H=s=>s,$a="customVideoProfile",Ka="customScreenProfile",_r={width:1280,height:720,frameRate:30,maxBitrate:2e3},Ja={width:1920,height:1080,frameRate:30,maxBitrate:2600};var pi=(s=>(s[s.ERROR_DEVICE_UNKNOWNERROR=1e4]="ERROR_DEVICE_UNKNOWNERROR",s[s.ERROR_DEVICE_AUDIODEVICE_NOTFOUND=10001]="ERROR_DEVICE_AUDIODEVICE_NOTFOUND",s[s.ERROR_DEVICE_AUDIODEVICE_NOTALLOWED=10002]="ERROR_DEVICE_AUDIODEVICE_NOTALLOWED",s[s.ERROR_DEVICE_AUDIODEVICE_NOTREADABLE=10003]="ERROR_DEVICE_AUDIODEVICE_NOTREADABLE",s[s.ERROR_DEVICE_VIDEODEVICE_NOTFOUND=10004]="ERROR_DEVICE_VIDEODEVICE_NOTFOUND",s[s.ERROR_DEVICE_VIDEODEVICE_NOTALLOWED=10005]="ERROR_DEVICE_VIDEODEVICE_NOTALLOWED",s[s.ERROR_DEVICE_VIDEODEVICE_NOTREADABLE=10006]="ERROR_DEVICE_VIDEODEVICE_NOTREADABLE",s[s.ERROR_SCREENSHARE_NOTSUPPORT=10010]="ERROR_SCREENSHARE_NOTSUPPORT",s[s.ERROR_SCREENSHARE_NOTALLOWED=10011]="ERROR_SCREENSHARE_NOTALLOWED",s[s.ERROR_SCREENSHARE_ENDED=10012]="ERROR_SCREENSHARE_ENDED",s[s.ERROR_SCREENSHARE_NOPERMISSION=10013]="ERROR_SCREENSHARE_NOPERMISSION",s[s.ERROR_SCREENSHARE_SAFARI_INVALIDACCESS=10014]="ERROR_SCREENSHARE_SAFARI_INVALIDACCESS",s[s.ERROR_SCREENSHARE_UNKNOWNERRO=10019]="ERROR_SCREENSHARE_UNKNOWNERRO",s[s.ERROR_DEVICE_NOTALLOWED=10021]="ERROR_DEVICE_NOTALLOWED",s[s.ERROR_DEVICE_NOTSUPPORT=2e4]="ERROR_DEVICE_NOTSUPPORT",s))(pi||{});const Bo={1e4:Ue.AliEngineLocalDeviceExceptionTypeUnknown,2e4:Ue.AliEngineLocalDeviceExceptionTypeUnknown,10001:Ue.AliEngineLocalDeviceExceptionTypeMicNotAvailable,10002:Ue.AliEngineLocalDeviceExceptionTypeMicAuthFail,10003:Ue.AliEngineLocalDeviceExceptionTypeMicOpenFail,10005:Ue.AliEngineLocalDeviceExceptionTypeCameraAuthFail,10004:Ue.AliEngineLocalDeviceExceptionTypeVideoDeviceException,10006:Ue.AliEngineLocalDeviceExceptionTypeCameraOpenFail,10010:Ue.AliEngineLocalDeviceExceptionTypeDisplayException,10011:Ue.AliEngineLocalDeviceExceptionTypeDisplayException,10012:Ue.AliEngineLocalDeviceExceptionTypeDisplayException,10013:Ue.AliEngineLocalDeviceExceptionTypeDisplayException,10014:Ue.AliEngineLocalDeviceExceptionTypeDisplayException,10019:Ue.AliEngineLocalDeviceExceptionTypeDisplayException};var ot=(s=>(s.CREATE_ENGINE="create_engine",s.JOIN="join",s.WANT_INSERT_PUB_TASK="wantInsertPubTask",s.INSERT_PUB_TASK="InsertPubTask",s.HANDLE_PUB_TASK="HandlePubTask",s.RECV_NOTIFY_PUBLISH="RecvNotifyPublish",s.INSERT_SUB_TASK="InsertSubTask",s.HANDLE_SUB_TASK="HandleSubTask",s.FIRST_REMOTE="first_remote",s))(ot||{}),ht=(s=>(s.START="start",s.SEND_SIG="send_sig",s.RECV_RST="recv_rst",s.END="end",s.RECEIVED="received",s.DECODED="decoded",s.PLAYED="played",s))(ht||{}),U=(s=>(s[s.ERR_JOIN_ALREADY_JOINED=16843521]="ERR_JOIN_ALREADY_JOINED",s[s.ERR_JOIN_BAD_APPID=33620481]="ERR_JOIN_BAD_APPID",s[s.ERR_JOIN_INVALID_APPID=33620482]="ERR_JOIN_INVALID_APPID",s[s.ERR_JOIN_BAD_CHANNEL=33620484]="ERR_JOIN_BAD_CHANNEL",s[s.ERR_JOIN_INVALID_CHANNEL=33620483]="ERR_JOIN_INVALID_CHANNEL",s[s.ERR_JOIN_BAD_TOKEN=33620485]="ERR_JOIN_BAD_TOKEN",s[s.ERR_JOIN_TIMEOUT=16908804]="ERR_JOIN_TIMEOUT",s[s.ERR_JOIN_ERR_JOIN_BAD_PARAMBAD=16974081]="ERR_JOIN_ERR_JOIN_BAD_PARAMBAD",s[s.ERR_JOIN_CHANNEL_FAILED=16974338]="ERR_JOIN_CHANNEL_FAILED",s[s.ERR_LOG_ALREADY_INIT=16974085]="ERR_LOG_ALREADY_INIT",s[s.ERR_LOG_ROOT_PATH_ERROR=16974086]="ERR_LOG_ROOT_PATH_ERROR",s[s.ERR_MIC_OPEN_FAIL=17040388]="ERR_MIC_OPEN_FAIL",s[s.ERR_SPEAKER_OPEN_FAIL=17040389]="ERR_SPEAKER_OPEN_FAIL",s[s.ERR_MIC_INTERRUPT=17040390]="ERR_MIC_INTERRUPT",s[s.ERR_SPEAKER_INTERRUPT=17040391]="ERR_SPEAKER_INTERRUPT",s[s.ERR_MIC_AUTH_FAIL=17040392]="ERR_MIC_AUTH_FAIL",s[s.ERR_MIC_NOT_AVAILABLE=17040393]="ERR_MIC_NOT_AVAILABLE",s[s.ERR_SPEAKER_NOT_AVAILABLE=17040400]="ERR_SPEAKER_NOT_AVAILABLE",s[s.ERR_CAMERA_OPEN_FAIL=17039620]="ERR_CAMERA_OPEN_FAIL",s[s.ERR_CAMERA_AUTH_FAIL=17039621]="ERR_CAMERA_AUTH_FAIL",s[s.ERR_CAMERA_INTERRUPT=17039622]="ERR_CAMERA_INTERRUPT",s[s.ERR_CAMERA_NOT_AVAILABLE=17039623]="ERR_CAMERA_NOT_AVAILABLE",s[s.ERR_VIDEO_DISPLAY_OPEN_FAIL=17039873]="ERR_VIDEO_DISPLAY_OPEN_FAIL",s[s.ERR_VIDEO_DISPLAY_INTERRUPT=1064992]="ERR_VIDEO_DISPLAY_INTERRUPT",s[s.ERR_ICE_CONNECTION_CONNECT_FAIL=17105409]="ERR_ICE_CONNECTION_CONNECT_FAIL",s[s.ERR_ICE_CONNECTION_RECONNECT_FAI=17105410]="ERR_ICE_CONNECTION_RECONNECT_FAI",s[s.ERR_ICE_CONNECTION_MOBILITY_FAIL=17105411]="ERR_ICE_CONNECTION_MOBILITY_FAIL",s[s.ERR_ICE_CONNECTION_HEARTBEAT_TIMEOUT=16908812]="ERR_ICE_CONNECTION_HEARTBEAT_TIMEOUT",s[s.ERR_LATENCY_LIVE_COMMUNICATION_FAILED=17235971]="ERR_LATENCY_LIVE_COMMUNICATION_FAILED",s[s.ERR_LATENCY_LIVE_MEIDASETTING_FAILED=17235972]="ERR_LATENCY_LIVE_MEIDASETTING_FAILED",s[s.ERR_LATENCY_LIVE_NONE_BROADCASTER=17235973]="ERR_LATENCY_LIVE_NONE_BROADCASTER",s[s.ERR_LATENCY_LIVE_NEED_RESTART=17235974]="ERR_LATENCY_LIVE_NEED_RESTART",s[s.ERR_LATENCY_LIVE_NEED_RESTART_AGAIN_LATER=17235975]="ERR_LATENCY_LIVE_NEED_RESTART_AGAIN_LATER",s[s.ERR_LATENCY_LIVE_SERVICE_UNAVAILABLE=17235976]="ERR_LATENCY_LIVE_SERVICE_UNAVAILABLE",s[s.ERR_LATENCY_LIVE_MEDIACONNECTION_INTERRUPTION=17235977]="ERR_LATENCY_LIVE_MEDIACONNECTION_INTERRUPTION",s[s.ERR_SDK_PUBLISH_INVAILD=16974597]="ERR_SDK_PUBLISH_INVAILD",s[s.ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL=16843782]="ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL",s[s.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED=16843856]="ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED",s[s.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED=16843857]="ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED",s[s.ERR_SDK_PUBLISH_DUAL_STREAM_FAILED=16843858]="ERR_SDK_PUBLISH_DUAL_STREAM_FAILED",s[s.ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED=16843859]="ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED",s[s.ERR_SDK_PUBLISH_SCREEN_SHARE_CONFIG_ERROR=16843860]="ERR_SDK_PUBLISH_SCREEN_SHARE_CONFIG_ERROR",s[s.ERR_SDK_SUBSCRIBE_INVAILD=16974852]="ERR_SDK_SUBSCRIBE_INVAILD",s[s.ERR_SDK_SUBSCRIBE_NOT_JOIN_CHANNEL=16844112]="ERR_SDK_SUBSCRIBE_NOT_JOIN_CHANNEL",s[s.ERR_SDK_SUBSCRIBE_AUDIO_STREAM_FAILED=16844113]="ERR_SDK_SUBSCRIBE_AUDIO_STREAM_FAILED",s[s.ERR_SDK_SUBSCRIBE_VIDEO_STREAM_FAILED=16844114]="ERR_SDK_SUBSCRIBE_VIDEO_STREAM_FAILED",s[s.ERR_SDK_SUBSCRIBE_DUAL_STREAM_FAILED=16844115]="ERR_SDK_SUBSCRIBE_DUAL_STREAM_FAILED",s[s.ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED=16844116]="ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED",s[s.ERR_SDK_SUBSCRIBE_DATA_FAILED=16844117]="ERR_SDK_SUBSCRIBE_DATA_FAILED",s[s.ERR_SDK_SUBSCRIBE_DATA_ERROR=16844118]="ERR_SDK_SUBSCRIBE_DATA_ERROR",s[s.ERR_SDK_INVALID_STATE=16974340]="ERR_SDK_INVALID_STATE",s[s.ERR_INVALID_ARGUMENTS=16974083]="ERR_INVALID_ARGUMENTS",s[s.ERR_SESSION_REMOVED=33620229]="ERR_SESSION_REMOVED",s[s.ERR_SDK_UPDATE_ROLE_CHANNEL=16908801]="ERR_SDK_UPDATE_ROLE_CHANNEL",s[s.ERR_INNER=-1]="ERR_INNER",s[s.ERR_SDK_MPU_TASK_PUBLISH_OK=0]="ERR_SDK_MPU_TASK_PUBLISH_OK",s[s.ERR_SDK_MPU_TASK_STREAM_NOT_FOUND=17825793]="ERR_SDK_MPU_TASK_STREAM_NOT_FOUND",s[s.ERR_SDK_MPU_TASK_STREAM_ALREADY_EXIST=17825794]="ERR_SDK_MPU_TASK_STREAM_ALREADY_EXIST",s[s.ERR_SDK_MPU_TASK_INVALID_PARAM=17825795]="ERR_SDK_MPU_TASK_INVALID_PARAM",s[s.ERR_SDK_MPU_TASK_INTERNAL_ERROR=17825796]="ERR_SDK_MPU_TASK_INTERNAL_ERROR",s[s.ERR_SDK_MPU_TASK_RTMP_SERVER_ERROR=17825797]="ERR_SDK_MPU_TASK_RTMP_SERVER_ERROR",s[s.ERR_SDK_MPU_TASK_RTMP_STREAM_URL_ERROR=17825798]="ERR_SDK_MPU_TASK_RTMP_STREAM_URL_ERROR",s[s.ERR_SDK_MPU_TASK_PUBLISH_TIMEOUT=17825799]="ERR_SDK_MPU_TASK_PUBLISH_TIMEOUT",s[s.ERR_SDK_MPU_TASK_NOT_AUTHORIZED=17825800]="ERR_SDK_MPU_TASK_NOT_AUTHORIZED",s[s.ERR_SDK_CHANNEL_RELAY_STATE_ERROR=18874369]="ERR_SDK_CHANNEL_RELAY_STATE_ERROR",s[s.ERR_SDK_CHANNEL_RELAY_SRC_NOT_ALLOW=18874370]="ERR_SDK_CHANNEL_RELAY_SRC_NOT_ALLOW",s[s.ERR_SDK_CHANNEL_RELAY_JOIN_DEST_FAILED=18874371]="ERR_SDK_CHANNEL_RELAY_JOIN_DEST_FAILED",s[s.ERR_SDK_CHANNEL_RELAY_TOKEN_INVALID=18874372]="ERR_SDK_CHANNEL_RELAY_TOKEN_INVALID",s[s.ERR_SDK_CHANNEL_RELAY_ROLE_ERROR=18874373]="ERR_SDK_CHANNEL_RELAY_ROLE_ERROR",s[s.ERR_SDK_CHANNEL_RELAY_INVALID_PARAM=18874374]="ERR_SDK_CHANNEL_RELAY_INVALID_PARAM",s[s.ERR_SDK_CHANNEL_RELAY_TO_SELF_ERROR=18874375]="ERR_SDK_CHANNEL_RELAY_TO_SELF_ERROR",s))(U||{});class O extends Error{constructor(e,t,i){super(t);g(this,"_code");g(this,"_extra");this._code=e,this._extra=i}static fromRtsError(e){return e instanceof O?e:new O((e==null?void 0:e.errorCode)||-1,(e==null?void 0:e.message)||(e==null?void 0:e.errorCodeName)||"rts error",e)}static fromError(e,t=-1,i=""){return new O(t,(e==null?void 0:e.message)||(e==null?void 0:e.reason)||i||"error",e)}get code(){return this._code}set code(e){this._code=e}get reason(){return this.message}get extra(){return this._extra}}function Ga(s){var a;if(((a=s==null?void 0:s.nodeName)==null?void 0:a.toLowerCase())==="video")return s.setAttribute("playsinline",""),s;if(typeof s=="string"){let e=document.getElementById(s);if(e){if(e.nodeName.toLocaleLowerCase()==="video")return e.setAttribute("playsinline",""),e;throw new O(U.ERR_INVALID_ARGUMENTS,"element should be HtmlVideoElement")}throw new O(U.ERR_INVALID_ARGUMENTS,"element not founded")}throw new O(U.ERR_INVALID_ARGUMENTS,"element id should be string")}function wr(s){var e;const a=[];if(Array.isArray(s))s.forEach(t=>{try{a.push(Ga(t))}catch(i){}});else if(typeof s=="string"||((e=s==null?void 0:s.nodeName)==null?void 0:e.toLowerCase())==="video")try{a.push(Ga(s))}catch(t){}return a}function xt(s){return new Promise(a=>setTimeout(a,s))}function qa(s,a,e=1e3,t=i=>!0){return I(this,null,function*(){let i=0;for(;i<a;)try{return yield s(i)}catch(r){if(i++,i>=a||!t(r))throw r||void 0;yield new Promise(n=>setTimeout(n,e))}})}function Er(s,a){let e=a;return typeof window.__ali_prefer_media_server=="string"&&window.__ali_prefer_media_server!==""&&(e=window.__ali_prefer_media_server),e?`${s}&ali_prefer_media_server=${e}`:s}function ri(s,a){var e;try{const{archCfgs:t}=s;if(!t||!Array.isArray(t))return;const i=t.find(r=>r.arch==="grtn");return i?(e=i.user_specified)==null?void 0:e[a]:void 0}catch(t){return}}function si(s,a){try{const{config:e}=s;return e?e==null?void 0:e[a]:void 0}catch(e){return}}const Xa=(s,a,e=!1)=>{const t=()=>(s.muted=!0,Promise.race([xt(500),s._playPromise||Promise.resolve()]).catch(()=>{}).then(()=>{let i;return e&&s.srcObject===a?i=Promise.resolve():(s.load(),s.srcObject=a,i=s.play(),s._playPromise=i),i}));return new Promise(i=>{if(X.AliRTS.BrowserUtil.isMicroMessenger){const r=window.top!==window.self,n=window.WeixinJSBridge||window.top.WeixinJSBridge;n?n.invoke("getNetworkType",{},()=>{i(t())}):(r?window.top.document:document).addEventListener("WeixinJSBridgeReady",()=>{n.invoke("getNetworkType",{},()=>{i(t())})}),setTimeout(()=>{i(t())},1e3)}else setTimeout(()=>{i(t())},0)})},_t=s=>{Promise.race([xt(100),s._playPromise||Promise.resolve()]).catch(()=>{}).then(()=>{s.srcObject=null,s._playPromise=void 0})};var Tr=(s=>(s[s.AliEngineDataMsgNone=0]="AliEngineDataMsgNone",s[s.AliEngineDataMsgMusicProgress=1]="AliEngineDataMsgMusicProgress",s[s.AliEngineDataMsgCustom=2]="AliEngineDataMsgCustom",s))(Tr||{});class Bi{constructor(a,e,t,i=0){g(this,"msgType");g(this,"msgId");g(this,"protocolVersion");g(this,"tlvVersion");this.msgType=a,this.msgId=e,this.protocolVersion=t,this.tlvVersion=i}build(){const a=new Uint8Array(4);return a.set(Uint8Array.from([this.protocolVersion,this.tlvVersion<<4|15&this.msgType]),0),a.set(Uint16Array.from([this.msgId]),2),a}static parse(a){const e=new DataView(a),t=e.getUint8(0),i=e.getUint8(1)>>4,r=15&e.getUint8(1),n=e.getUint16(2);return new Bi(r,n,t,i)}}class Hi{constructor(a,e,t){g(this,"_byteArray");if(this._byteArray=new Uint8Array(0),a!==void 0&&e!==void 0&&t!==void 0){const i=new Bi(a,e,t).build();this._byteArray=new Uint8Array(i.byteLength+this._byteArray.byteLength),this._byteArray.set(i,0)}}write(a,e){const t=this._byteArray,i=new ArrayBuffer(5),r=new DataView(i);r.setUint8(0,a),r.setUint32(1,e.byteLength);const n=new Uint8Array(t.byteLength+5+e.byteLength);n.set(t,0),n.set(new Uint8Array(i),t.byteLength),n.set(new Uint8Array(e),t.byteLength+5),this._byteArray=n}static parse(a){const e={},t=new DataView(a);let i=0;for(;i<a.byteLength;){const r=t.getUint8(i),n=t.getUint32(i+1);if(!(i+5+n<=a.byteLength))break;{const c=a.slice(i+5,i+5+n);e[r]=c,i+=5+n}}return e}get buffer(){return this._byteArray.buffer}}class mi{constructor(a=0,e=!0,t=1,i=!1,r=0,n=!1,c=!1,o=3){g(this,"_fin",!0);g(this,"_hasExtension",!1);g(this,"_version",0);g(this,"_frameType",1);g(this,"_isEncrypted",!1);g(this,"_isCompressed",!1);g(this,"_signalType",3);g(this,"_payloadLength",0);this._fin=e,this._hasExtension=i,this._version=r,this._frameType=t,this._isEncrypted=n,this._isCompressed=c,this._signalType=o,this._payloadLength=a}get fin(){return this._fin}get hasExtension(){return this._hasExtension}get version(){return this._version}get frameType(){return this._frameType}get isEncrypted(){return this._isEncrypted}get isCompressed(){return this._isCompressed}get signalType(){return this._signalType}get payloadLength(){return this._payloadLength}toBuffer(){const a=new ArrayBuffer(4),e=new DataView(a);return e.setUint8(0,(this._fin?1:0)<<7|(this._hasExtension?1:0)<<6|this._version<<4|15&this._frameType),e.setUint8(1,(this._isEncrypted?1:0)<<7|(this._isCompressed?1:0)<<6|15&this._signalType),e.setUint16(2,this._payloadLength),a}static parse(a){const e=new DataView(a),t=e.getUint8(0)>>7==1,i=(64&e.getUint8(0))>>6==1,r=(48&e.getUint8(0))>>4,n=15&e.getUint8(0),c=e.getUint8(1)>>7==1,o=(64&e.getUint8(1))>>6==1,d=15&e.getUint8(1),h=e.getUint16(2);return new mi(h,t,n,i,r,c,o,d)}}class Fi{constructor(a,e){g(this,"_body");g(this,"_header",new mi);this._header=a,this._body=e}get header(){return this._header}get isFin(){return this._header.fin}get body(){return this._body}toGRTNBuffer(){const a=this._header.toBuffer(),e=this._body,t=new ArrayBuffer(4);new DataView(t).setUint8(0,1*Math.pow(2,4));const i=new Uint8Array(t.byteLength+a.byteLength+e.byteLength);return i.set(new Uint8Array(t),0),i.set(new Uint8Array(a),t.byteLength),i.set(new Uint8Array(e),t.byteLength+a.byteLength),i.buffer}static parse(a){const e=a.slice(0,4),t=mi.parse(e);let i=new ArrayBuffer(0);return a.byteLength-4>=t.payloadLength&&(i=a.slice(4,4+t.payloadLength)),new Fi(t,i)}}const Ir=s=>{const a=s.byteLength,e=new DataView(s);let t=0;for(let i=0;i<a;i++)t=256*t+e.getUint8(i);return t};let Ya=0;class Vt{constructor(a,e=0,t=0,i=0){g(this,"data");g(this,"networkTime");g(this,"futureOrProgress");g(this,"type");this.data=a,this.type=e,this.networkTime=t,this.futureOrProgress=i}toBuffer(){const a=new Hi(0,0,0);a.write(1,Uint8Array.from([0]).buffer),a.write(2,Uint16Array.from([0]).buffer),Ya++,a.write(3,Uint32Array.from([Ya]).buffer);const e=new Hi;return e.write(1,Uint8Array.from([0]).buffer),e.write(2,Uint8Array.from([this.type]).buffer),e.write(3,Uint32Array.from([this.futureOrProgress]).buffer),e.write(4,Uint32Array.from([Number(this.networkTime>>32&4294967295),Number(4294967295&this.networkTime)]).buffer),e.write(5,this.data),a.write(30,e.buffer),a.buffer}static parse(a){if(!a||a.byteLength<4)return;Bi.parse(a.slice(0,4));const e=Hi.parse(a.slice(4))[30];if(!e)return;const t=Hi.parse(e),i=t[2],r=t[3],n=t[4],c=t[5];return c.byteLength!==0?new Vt(c,Ir(i),Ir(n),Ir(r)):void 0}}var Ho=Object.defineProperty,Fo=Object.getOwnPropertyDescriptor,De=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?Fo(a,e):a,n=s.length-1;n>=0;n--)(i=s[n])&&(r=(t?i(a,e,r):i(r))||r);return t&&r&&Ho(a,e,r),r};class gi extends se{constructor(){super();g(this,"_state");g(this,"time");this._state=ie.AliRtcStatePublishIdle,this.time=Date.now()}get state(){return this._state}setState(e){const t=this._state,i=this.time;this._state=e,this.time=Date.now(),this.emit("change",t,e,Math.floor((this.time-i)/1e3))}}const Ce=(Tt=class extends za{constructor(e){const{rtsManager:t,localStreamManager:i,slsReporter:r,signalingManager:n,audioVolumeIndicationInterval:c,parameter:o}=e;super("","",t,c);g(this,"_url","");g(this,"joinTime",0);g(this,"publishPromise",Promise.resolve({traceId:"",l1ip:void 0}));g(this,"previewElements",[]);g(this,"screenPreviewElements",[]);g(this,"streamManager");g(this,"dc");g(this,"streamTracks");g(this,"publishId",dt());g(this,"signalingManager");g(this,"shouldPublish",!1);g(this,"traceId","");g(this,"monitorTimerId");g(this,"monitorDataCache",{});g(this,"trackTraceIdMap",{});g(this,"candidateDataCache",[]);g(this,"pcMediaStatsMap",{});g(this,"slsReporter");g(this,"audioPubState");g(this,"videoPubState");g(this,"videoSmallPubState");g(this,"screenPubState");g(this,"dataPubState");g(this,"parameter",{});g(this,"onTrackEnd",e=>{this.emit(e)});this.streamManager=i,this.signalingManager=n,this.slsReporter=r,this.parameter=o,this.streamManager.on("trackended",d=>{this.onTrackEnd(d)}),this.streamManager.on("publishupdate",()=>{this.publishUpdate()}),this.audioPubState=new gi,this.audioPubState.on("change",(d,h,l)=>{this.emit("audioPublishStateChanged",d,h,l)}),this.videoPubState=new gi,this.videoPubState.on("change",(d,h,l)=>{this.emit("videoPublishStateChanged",d,h,l)}),this.videoSmallPubState=new gi,this.videoSmallPubState.on("change",(d,h,l)=>{this.emit("dualStreamPublishStateChanged",d,h,l)}),this.screenPubState=new gi,this.screenPubState.on("change",(d,h,l)=>{this.emit("screenPublishStateChanged",d,h,l)}),this.dataPubState=new gi,this.dataPubState.on("change",(d,h,l)=>{this.emit("dataPublishStateChanged",d,h,l)}),this.startStreamMonitor()}get url(){return this._url}set url(e){this._url=e,this.rtsManager.updateAuth(e)}get joined(){return!!this.uid}get isPublishing(){return this.rtsManager.publishingTracks.length>0}get publishStreams(){return this.streamManager.publishStreams}get cameraTrack(){return this.streamManager.cameraStreamInfo.originVideoTrack}get screenTrack(){return this.streamManager.screenStreamInfo.originVideoTrack}get audioTrack(){return this.streamManager.cameraStreamInfo.originAudioTrack}get hasCamera(){return!!this.streamManager.cameraStreamInfo.originVideoTrack}get hasMicrophone(){return!!this.streamManager.cameraStreamInfo.originAudioTrack}get hasScreenShare(){return!!this.streamManager.screenStreamInfo.originVideoTrack}get hasCameraTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:r})=>i==="video"&&t&&r===M.VideoLarge))}get hasCameraDualTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:r})=>i==="video"&&t&&r===M.VideoSmall))}get hasScreenTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:r})=>i==="video"&&t&&r===M.Screen))}get hasAudioTrackInMS(){var e;return!!((e=this.streamTracks)!=null&&e.find(({ssrc:t,type:i,msid:r})=>i==="audio"&&t&&r===M.Audio))}get cameraDirection(){var e,t;return(t=(e=this.streamManager.cameraStreamInfo)==null?void 0:e.cameraVideoConstraints)==null?void 0:t.facingMode}get audioCaptureDisabled(){return this.streamManager.audioCaptureDisabled}get cameraCaptureDisabled(){return this.streamManager.cameraCaptureDisabled}get publishLocalVideoStreamEnabled(){return this.streamManager.publishLocalVideoStreamEnabled}get publishLocalAudioStreamEnabled(){return this.streamManager.publishLocalAudioStreamEnabled}get publishLocalScreenStreamEnabled(){return this.streamManager.publishLocalScreenStreamEnabled}setPublishLocalAudioStreamEnabled(e){this.streamManager.publishLocalAudioStreamEnabled=e}setPublishLocalVideoStreamEnabled(e){this.streamManager.publishLocalVideoStreamEnabled=e}setPublishLocalScreenStreamEnabled(e){this.streamManager.publishLocalScreenStreamEnabled=e}initInfo(e,t){this.joinTime=Date.now(),this.rtsManager.localJoinTime=this.joinTime,this.setUserInfo(e.userId,e.userId),this.url=t,this.callId=e.sessionId||nt.createCallid(),this.updatePubId()}setVideoProfile(e){return I(this,null,function*(){yield this.streamManager.setVideoProfile($a,e)})}setVideoContentHint(e){this.streamManager.setVideoContentHint(e)}setScreenContentHint(e){this.streamManager.setScreenContentHint(e)}setAudioProfile(e){return I(this,null,function*(){yield this.streamManager.setAudioProfile(e)})}setScreenProfile(e){return I(this,null,function*(){yield this.streamManager.setScreenProfile(Ka,e)})}setCameraDirection(e){if(e===ui.CAMERA_FRONT)this.streamManager.setCameraVideoConstraints({facingMode:"user"});else{if(e!==ui.CAMERA_REAR)throw new O(U.ERR_CAMERA_OPEN_FAIL,`camera direction set to ${e} failed`);this.streamManager.setCameraVideoConstraints({facingMode:"environment"})}}setCameraDeviceId(e){this.streamManager.setCameraVideoConstraints({deviceId:e})}muteLocalCamera(e){this.streamManager.setCameraMuted(e),this.slsReporter.reportMute(this.callId,!e,"video")}muteLocalMic(e){this.streamManager.setAudioMuted(e),this.slsReporter.reportMute(this.callId,!e,"audio")}muteLocalScreen(e){this.streamManager.setScreenMuted(e),this.slsReporter.reportMute(this.callId,!e,"screen")}setMicrophoneDeviceId(e){this.streamManager.setMicAudioConstraints({deviceId:e})}setMicrophoneConstraints(e){this.streamManager.setMicAudioConstraints(e)}updatePubId(){this.publishId=dt()}clearPublishState(){this.streamTracks=void 0}leave(){return I(this,null,function*(){this.shouldPublish=!1,this.isPublishing&&(yield this.unPublish()),this.joinTime=0,this.dc=void 0})}clear(){return I(this,null,function*(){Yr(Tt.prototype,this,"clear").call(this),this.stopPreview(),this.resetPreviewElements(),this.resetSecondayPreviewElements(),this.clearStream(),yield this.leave(),this.streamManager.cameraCaptureDisabled=!1})}resetElement(e){this.previewElements.includes(e)&&(_t(e),this.previewElements.splice(this.previewElements.indexOf(e),1)),this.screenPreviewElements.includes(e)&&(_t(e),this.screenPreviewElements.splice(this.screenPreviewElements.indexOf(e),1))}setPreviewElement(e){const{videoElement:t,screen:i}=e;i?this.screenPreviewElements.includes(t)||(this.screenPreviewElements.push(t),this.preview(e)):this.previewElements.includes(t)||(this.previewElements.push(t),this.preview(e))}startDefaultCameraAndMic(e){return I(this,null,function*(){const{hasCamera:t,cameraCaptureDisabled:i,publishLocalVideoStreamEnabled:r}=this,{hasMicrophone:n,audioCaptureDisabled:c,publishLocalAudioStreamEnabled:o}=this,d=!t&&!e&&!i&&r,h=!n&&!c&&o;try{d&&h?yield this.startCameraAndMic():d?yield this.startCameraCapture():h&&(yield this.startAudioCapture())}catch(l){const p=l.errorCode;let u=U.ERR_CAMERA_OPEN_FAIL;throw d?((p===pi.ERROR_DEVICE_VIDEODEVICE_NOTALLOWED||pi.ERROR_DEVICE_NOTALLOWED)&&(u=U.ERR_CAMERA_AUTH_FAIL),u=U.ERR_CAMERA_OPEN_FAIL):((p===pi.ERROR_DEVICE_AUDIODEVICE_NOTALLOWED||pi.ERROR_DEVICE_NOTALLOWED)&&(u=U.ERR_MIC_AUTH_FAIL),u=U.ERR_MIC_OPEN_FAIL),new O(u,`auto open fail: ${l.message}`)}})}setViewConfig(e,t){if(e){if(![oe.AliRtcVideoTrackCamera,oe.AliRtcVideoTrackScreen].includes(t))throw new O(U.ERR_INVALID_ARGUMENTS,"set view config invalid track",{track:t});e.forEach(i=>{this.setPreviewElement({videoElement:i,screen:t===oe.AliRtcVideoTrackScreen})})}else t===oe.AliRtcVideoTrackCamera?this.stopPreview({primary:!0,screen:!1}):this.stopPreview({primary:!1,screen:!0})}startCameraCapture(){return I(this,null,function*(){return this.streamManager.cameraCaptureDisabled=!1,yield this.createLocalStream({video:!0})})}stopCameraCapture(){return I(this,null,function*(){this.streamManager.cameraCaptureDisabled=!0,yield this.stopLocalStream({video:!0})})}startAudioCapture(){return I(this,null,function*(){return this.streamManager.audioCaptureDisabled=!1,yield this.createLocalStream({audio:!0})})}stopAudioCapture(){return I(this,null,function*(){this.streamManager.audioCaptureDisabled=!0,yield this.stopLocalStream({audio:!0})})}startCameraAndMic(){return I(this,null,function*(){return this.streamManager.cameraCaptureDisabled=!1,this.streamManager.audioCaptureDisabled=!1,yield this.createLocalStream({video:!0,audio:!0})})}preview(e){return I(this,null,function*(){const{videoElement:t,screen:i}=e!=null?e:{};try{let r=i?this.streamManager.screenStreamInfo.previewStream:this.streamManager.cameraStreamInfo.previewStream;if(!t)throw new O(U.ERR_INVALID_ARGUMENTS,"no video element found",{videoElement:t});return r?(Xa(t,r.mediaStream),this.setPreviewElement(e),r.mediaStream):void V.info(`[${Tt.logName}]`,"preview no stream founded")}catch(r){const n=U.ERR_INNER;throw O.fromError(r,n,"preview failed")}})}previewAll(e){return I(this,null,function*(){const{primary:t=!0,screen:i=!0}=e!=null?e:{};if(t&&this.previewElements.length)for(let r=0;r<this.previewElements.length;r++){const n=this.previewElements[r];yield this.preview({videoElement:n})}if(i&&this.screenPreviewElements.length)for(let r=0;r<this.screenPreviewElements.length;r++){const n=this.screenPreviewElements[r];yield this.preview({videoElement:n,screen:!0})}})}stopPreview(e){const{videoElement:t,primary:i=!0,screen:r=!0}=e||{};if(t){const n=this.previewElements.findIndex(c=>c===t);if(n>=0)this.previewElements.splice(n,1),_t(t);else{const c=this.screenPreviewElements.findIndex(o=>o===t);c>=0&&(this.screenPreviewElements.splice(c,1),_t(t))}}else i&&(this.previewElements.forEach(n=>{_t(n)}),this.previewElements=[]),r&&(this.screenPreviewElements.forEach(n=>{_t(n)}),this.screenPreviewElements=[])}resumePublish(){return I(this,null,function*(){this.shouldPublish&&(yield this.startPublish(!0))})}createLocalStream(e){return I(this,null,function*(){try{if(e.video)for(let i=0;i<this.previewElements.length;i++){const r=this.previewElements[i];_t(r)}else if(e.screen)for(let i=0;i<this.screenPreviewElements.length;i++){const r=this.screenPreviewElements[i];_t(r)}const t=yield this.streamManager.createLocalStream(e);return t!=null&&t.audioTrack&&this.audioVolumeIndicationInterval>0&&this.audioLevelMonitor.start(t.audioTrack,this.audioVolumeIndicationInterval),e.video?this.previewAll({primary:!0}):e.screen&&this.previewAll({screen:!0}),t}catch(t){const i=Bo[t.errorCode];throw i&&(e.audio?this.emit("localDeviceException",At.AliEngineLocalDeviceTypeMic,i,""):e.video?this.emit("localDeviceException",At.AliEngineLocalDeviceTypeCamera,i,""):e.screen?this.emit("localDeviceException",At.AliEngineLocalDeviceTypeDisplay,i,""):this.emit("localDeviceException",At.AliEngineLocalDeviceTypeUnknown,i,"")),t}})}stopLocalStream(e){return I(this,null,function*(){e.audio&&this.audioLevelMonitor.stop(),yield this.streamManager.stopLocalStream(e)})}compareAndPublish(e,t,i){return I(this,null,function*(){var n,c;if(!e&&!t)return;if(e&&!t){const o={};return i===M.Audio?o.audio=!0:i===M.VideoLarge||i===M.VideoSmall?(o.video=!0,o.vMsid=i):i===M.Screen&&(o.screen=!0),yield this.publishDeleteTracks(o)}const r={};if(t!=null&&t.hasVideo&&(r.isScreen=i===M.Screen,r.vMsid=i),t!=null&&t.hasAudio&&(r.aMsid=i),!e&&t)return yield this.publishAdd(t,r,!1);if(e&&t&&e.trackId!==(((n=t.videoTrack)==null?void 0:n.id)||((c=t.audioTrack)==null?void 0:c.id)))return yield this.publishReplace(t,r)})}reportAudioProfile(){const e=this.streamManager.cameraStreamInfo.audioProfile||"standard",t=X.AliRTS.AudioProfileMap.get(e);this.slsReporter.reportPublishProfile(M.Audio,{a_profile:e,bits:(t==null?void 0:t.maxBitrate)||0,samplerate:(t==null?void 0:t.sampleRate)||0,channel:(t==null?void 0:t.channelCount)||0})}reportVideoProfile(){const e=this.streamManager.cameraStreamInfo.videoProfile||"",t=X.AliRTS.VideoProfileMap.get(e);t&&this.slsReporter.reportPublishProfile(M.VideoLarge,{v_profile:e,wdth:(t==null?void 0:t.width)||0,hgt:(t==null?void 0:t.height)||0,fps:(t==null?void 0:t.frameRate)||0,bitrate:(t==null?void 0:t.maxBitrate)||0})}reportScreenProfile(){const e=this.streamManager.screenStreamInfo.videoProfile||"",t=X.AliRTS.VideoProfileMap.get(e);t&&this.slsReporter.reportPublishProfile(M.Screen,{v_profile:e,wdth:(t==null?void 0:t.width)||0,hgt:(t==null?void 0:t.height)||0,fps:(t==null?void 0:t.frameRate)||0,bitrate:(t==null?void 0:t.maxBitrate)||0})}updateDataChannel(e){var t;e&&(((t=this.dc)==null?void 0:t.datachannel)!==(e==null?void 0:e.datachannel)&&(e.ssrc=`web_${Date.now()}_${(e==null?void 0:e.datachannel.id)||"0"}`),this.dc=e,this.dc.datachannel&&(this.dc.datachannel.binaryType="arraybuffer"))}publishDataChannel(){return I(this,null,function*(){if(this.dataPubState.state!==ie.AliRtcStatePublishing){this.dataPubState.setState(ie.AliRtcStatePublishing);try{const e=yield this.rtsManager.publishAddDataChannel(this.url);e?(this.updateDataChannel(e),this.dataPubState.setState(ie.AliRtcStatePublished)):(this.dataPubState.setState(ie.AliRtcStateNoPublish),this.emit("publishDataError",new O(U.ERR_INNER,"publishDataError")))}catch(e){V.error("[LocalUser]","publishDataChannel error",e),this.dataPubState.setState(ie.AliRtcStateNoPublish)}}})}startPublish(){return I(this,arguments,function*(e=!1,t=yt.MANUAL){var d;if(!this.joined)return;this.shouldPublish=!0;const i=this.streamManager.publishStreams,{audio:r,video:n,videoSmall:c,screen:o}=i;if(r||n||c||o){this.createCallId();try{const h=new Date().getTime();r&&this.audioPubState.setState(ie.AliRtcStatePublishing),n&&this.videoPubState.setState(ie.AliRtcStatePublishing),c&&this.videoSmallPubState.setState(ie.AliRtcStatePublishing),o&&this.screenPubState.setState(ie.AliRtcStatePublishing),this.publishPromise=this.rtsManager.publish(this.url,this.callId,e,t);const{traceId:l,l1ip:p}=yield this.publishPromise;this.streamTracks=this.rtsManager.publishingTracks,this.traceId=l;const u={type:Lt.Add,userid:this.userId,sessionid:"",displayname:this.name,pubid:this.publishId,resume:e,subscribe:{signal:"",pullstreamurl:this.url},l1ip:this.parameter.reportL1IP?p:void 0,callid:this.callId,tracks:this.streamTracks,traceid:l};(d=this.parameter.data)!=null&&d.enablePubDataChannel&&this.publishDataChannel().then(()=>{this.syncPublishToRoomServer(u,i,h)}),r&&(this.trackTraceIdMap[M.Audio]=l,this.reportAudioProfile()),c&&(this.trackTraceIdMap[M.VideoSmall]=l),n&&(this.trackTraceIdMap[M.VideoLarge]=l,this.reportVideoProfile()),o&&(this.trackTraceIdMap[M.Screen]=l,this.reportScreenProfile()),yield this.syncPublishToRoomServer(u,i,h),r&&this.audioPubState.setState(ie.AliRtcStatePublished),n&&this.videoPubState.setState(ie.AliRtcStatePublished),c&&this.videoSmallPubState.setState(ie.AliRtcStatePublished),o&&this.screenPubState.setState(ie.AliRtcStatePublished)}catch(h){throw r&&this.audioPubState.setState(ie.AliRtcStateNoPublish),n&&this.videoPubState.setState(ie.AliRtcStateNoPublish),c&&this.videoSmallPubState.setState(ie.AliRtcStateNoPublish),o&&this.screenPubState.setState(ie.AliRtcStateNoPublish),h}}else V.event(`[${Tt.logName}]`,"startPublish no stream founded")})}updateStreams(){return I(this,null,function*(){yield this.streamManager.updateStreams()})}publishUpdate(e){return I(this,null,function*(){var n,c,o,d,h,l;if(V.info(`[${Tt.logName}]`,"publishUpdate",e||"-",this.shouldPublish),!this.shouldPublish)return;if(!this.rtsManager.isConnecting&&!this.rtsManager.isConnected)return void(yield this.startPublish());yield this.publishPromise;const t=this.streamManager.publishStreams;let i;const r=new Date().getTime();try{const p=(n=this.streamTracks)==null?void 0:n.find(({ssrc:w,type:y,msid:A})=>y==="audio"&&w&&A===M.Audio),u=yield this.compareAndPublish(p,t.audio,M.Audio);u&&(i=u);const f=(c=this.streamTracks)==null?void 0:c.find(({ssrc:w,type:y,msid:A})=>y==="video"&&w&&A===M.VideoLarge),m=yield this.compareAndPublish(f,t.video,M.VideoLarge);m&&(i=m);const b=(o=this.streamTracks)==null?void 0:o.find(({ssrc:w,type:y,msid:A})=>y==="video"&&w&&A===M.VideoSmall),S=yield this.compareAndPublish(b,t.videoSmall,M.VideoSmall);S&&(i=S);const v=(d=this.streamTracks)==null?void 0:d.find(({ssrc:w,type:y,msid:A})=>y==="video"&&w&&A===M.Screen),_=yield this.compareAndPublish(v,t.screen,M.Screen);if(_&&(i=_),!i){if(!(e===yt.RECONNECT&&this.rtsManager.publishingTracks.length>0))return;{if((h=this.parameter.data)!=null&&h.enablePubDataChannel){const A=this.rtsManager.getDatachannelByMsid({url:this.url,msid:M.Data});this.updateDataChannel(A)}const w=this.rtsManager.publishingTracks.find(({type:A})=>A==="video"),y=this.rtsManager.publishingTracks.find(({type:A})=>A==="audio");(w||y)&&(yield this.rtsManager.waitPublishSender(this.url,!w,w?w.msid:y==null?void 0:y.msid)),i={type:Lt.Add,userid:this.userId,sessionid:"",displayname:this.name,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.rtsManager.publishingTracks,traceid:this.traceId}}}(l=this.parameter.data)!=null&&l.enablePubDataChannel&&!this.dc&&(yield this.publishDataChannel()),yield this.syncPublishToRoomServer(i,t,r)}catch(p){const{code:u}=p!=null?p:{},f=this.url;throw u===403&&f&&(yield this.refreshPushStreamUrl(),i=yield this.publishUpdate()),p}return i})}syncPublishToRoomServer(e,t,i){return I(this,null,function*(){var o;if(!e)throw new O(U.ERR_INNER,"sync publish to room server failed because no publishInfo");let r=e;if(this.dc){const c=e,{tracks:d}=c,h=jt(c,["tracks"]);r=vt(G({},h),{tracks:[...d,{type:"data",msid:M.Data,ssrc:((o=this.dc)==null?void 0:o.ssrc)||"web_sophon_data",codec:"text"}]})}const n=yield this.signalingManager.publish(r);e.signaltid=n.tid})}refreshPushStreamUrl(){return I(this,null,function*(){const e=new O(U.ERR_INNER,"refresh push stream url error"),t=this.url;if(!t)throw e;const i=yield this.signalingManager.refreshUrl({pushstreamurl:t});if(!(i!=null&&i.pushstreamurl))throw e;this.url=i.pushstreamurl})}publishAdd(e,t,i=!1,r=0){return I(this,null,function*(){this.createCallId();const n=(t==null?void 0:t.aMsid)===M.Audio,c=(t==null?void 0:t.vMsid)===M.VideoLarge,o=(t==null?void 0:t.vMsid)===M.VideoSmall,d=(t==null?void 0:t.vMsid)===M.Screen;n&&this.audioPubState.setState(ie.AliRtcStatePublishing),c&&this.videoPubState.setState(ie.AliRtcStatePublishing),o&&this.videoSmallPubState.setState(ie.AliRtcStatePublishing),d&&this.screenPubState.setState(ie.AliRtcStatePublishing);try{const h=yield this.rtsManager.publishAdd(this.url,e,this.callId,t,!1,!0);n&&(this.audioPubState.setState(ie.AliRtcStatePublished),this.reportAudioProfile(),this.trackTraceIdMap[M.Audio]=h),c&&(this.videoPubState.setState(ie.AliRtcStatePublished),this.reportVideoProfile(),this.trackTraceIdMap[M.VideoLarge]=h),o&&(this.videoSmallPubState.setState(ie.AliRtcStatePublished),this.trackTraceIdMap[M.VideoSmall]=h),d&&(this.screenPubState.setState(ie.AliRtcStatePublished),this.reportScreenProfile(),this.trackTraceIdMap[M.Screen]=h),this.streamTracks=this.rtsManager.publishingTracks;const l={type:Lt.Add,userid:this.userId,sessionid:"",displayname:this.name,pubid:this.publishId,resume:i,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.streamTracks,traceid:h};return this.reportSelfDeviceStatus(),this.monitorTimerId||this.startStreamMonitor(),l}catch(h){let l=U.ERR_SDK_PUBLISH_INVAILD;if(n&&(this.audioPubState.setState(ie.AliRtcStateNoPublish),l=U.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED),c&&(this.videoPubState.setState(ie.AliRtcStateNoPublish),l=U.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED),o&&(this.videoSmallPubState.setState(ie.AliRtcStateNoPublish),l=U.ERR_SDK_PUBLISH_DUAL_STREAM_FAILED),d&&(this.screenPubState.setState(ie.AliRtcStateNoPublish),l=U.ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED),h.errorCode===15006&&r<3)return this.publishAdd(e,t,i,r+1);throw O.fromError(h,l,"publish add failed")}})}publishReplace(e,t){return I(this,null,function*(){try{yield this.rtsManager.publishReplace(this.url,e,t),this.streamTracks=this.rtsManager.publishingTracks;const i=(t==null?void 0:t.vMsid)===M.VideoLarge,r=(t==null?void 0:t.vMsid)===M.Screen;i&&this.streamManager.setVideoProfile(void 0,void 0,!0),r&&this.streamManager.setScreenProfile(void 0,void 0);const n={type:Lt.Replace,userid:this.userId,sessionid:"",pubid:this.publishId,displayname:this.name,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.streamTracks};return this.reportSelfDeviceStatus(),n}catch(i){throw O.fromError(i,U.ERR_INNER,`publish replace failed, vMsid: ${t==null?void 0:t.vMsid} aMsid: ${t==null?void 0:t.aMsid}`)}})}publishDeleteTracks(e){return I(this,null,function*(){const t={type:Lt.Delete,userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};try{return yield this.rtsManager.publishDelete(this.url,e),this.streamTracks=this.rtsManager.publishingTracks,e.audio&&this.audioPubState.setState(ie.AliRtcStateNoPublish),e.video&&(e.vMsid===M.VideoSmall?this.videoSmallPubState.setState(ie.AliRtcStateNoPublish):this.videoPubState.setState(ie.AliRtcStateNoPublish)),e.screen&&this.screenPubState.setState(ie.AliRtcStateNoPublish),t.tracks=this.streamTracks,this.reportSelfDeviceStatus(),t}catch(i){throw O.fromError(i,U.ERR_INNER,"publish delete tracks failed")}})}publishStop(){return I(this,null,function*(){V.info(`[${Tt.logName}]`,"publishStop",{url:this.url});const e=new Date().getTime();try{const t=this.hasAudioTrackInMS,i=this.hasCameraTrackInMS,r=this.hasCameraDualTrackInMS,n=this.hasScreenTrackInMS;yield this.rtsManager.publishStop(this.url),t&&this.audioPubState.setState(ie.AliRtcStateNoPublish),i&&this.videoPubState.setState(ie.AliRtcStateNoPublish),r&&this.videoSmallPubState.setState(ie.AliRtcStateNoPublish),n&&this.screenPubState.setState(ie.AliRtcStateNoPublish),this.traceId="",Object.keys(this.monitorDataCache).forEach(o=>{this.reportPublishMonitor(o)}),this.streamTracks=[];const c={type:Lt.Stop,userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};return this.syncPublishToRoomServer(c,{},e),c}catch(t){throw O.fromError(t,U.ERR_INNER,"publish stop failed")}})}unPublish(){return I(this,null,function*(){this.shouldPublish=!1;const e=new Date().getTime();let t={type:Lt.UnPublish,userid:this.userId,sessionid:"",displayname:this.displayname,callid:this.callId,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},tracks:[]};try{if(this.isPublishing){const i=this.hasAudioTrackInMS,r=this.hasCameraTrackInMS,n=this.hasCameraDualTrackInMS,c=this.hasScreenTrackInMS;yield this.rtsManager.unpublish(),this.streamTracks=[],this.stopStreamMonitor(),i&&this.audioPubState.setState(ie.AliRtcStateNoPublish),r&&this.videoPubState.setState(ie.AliRtcStateNoPublish),n&&this.videoSmallPubState.setState(ie.AliRtcStateNoPublish),c&&this.screenPubState.setState(ie.AliRtcStateNoPublish),this.traceId="",this.clearStream()}return this.dc&&(this.rtsManager.publishStopDataChannel(this.url,this.dc),this.dataPubState.setState(ie.AliRtcStateNoPublish),this.dc=void 0),this.slsReporter.reportUnpublish(this.callId||"",e,0,""),t}catch(i){throw O.fromError(i,U.ERR_INNER,"unpublish failed")}})}reportSelfDeviceStatus(){this.emit(Ye.Local,this.getDeviceStatus())}getDeviceStatus(){var t,i,r,n;let e={micOpen:!1,micInterrupted:!1,cameraOpen:!1,screenShare:!1,audioDisable:!0,videoDisable:!0,screenDisable:!0,backgroundMode:!1,accompanyPlaying:!1};return e.cameraOpen=this.hasCameraTrackInMS,e.videoDisable=this.hasCamera&&!((t=this.streamManager.cameraStreamInfo.originVideoTrack)!=null&&t.enabled),e.micOpen=this.hasAudioTrackInMS,e.audioDisable=this.hasMicrophone&&!((i=this.streamManager.cameraStreamInfo.originAudioTrack)!=null&&i.enabled),e.screenShare=this.hasScreenTrackInMS,e.screenDisable=this.hasScreenShare&&!((n=(r=this.streamManager.screenStreamInfo)==null?void 0:r.originVideoTrack)!=null&&n.enabled),Wa.getCurrentStatus(e)}resetPreviewElements(){this.previewElements.forEach(e=>{e.srcObject=null,e._playPromise=void 0},[]),this.previewElements=[]}resetSecondayPreviewElements(){this.screenPreviewElements.forEach(e=>{e.srcObject=null,e._playPromise=void 0},[]),this.screenPreviewElements=[]}getMediaStats(e){return this.pcMediaStatsMap[e]}reportPublishMonitor(e){if(!e)return;let t;try{t=e===M.Audio?this.rtsManager.getStreamByMsid({url:this.url,aMsid:e}).audioTrack:this.rtsManager.getStreamByMsid({url:this.url,vMsid:e}).videoTrack}catch(i){}this.slsReporter.reportPublishMonitor(this.callId,this.trackTraceIdMap[e]||"",e,t,this.monitorDataCache[e]),this.monitorDataCache[e]=[]}reportNetwork(){this.slsReporter.reportNetworkMonitor(this.candidateDataCache),this.candidateDataCache=[]}startStreamMonitor(){this.monitorTimerId||(this.monitorTimerId=window.setInterval(()=>I(this,null,function*(){var e,i;try{const r=yield this.rtsManager.getPCStats();let n,c;if(r==null||r.forEach(d=>{d.type==="media-source"||d.type==="media-playout"?d.id&&(this.pcMediaStatsMap[d.id]=d):d.type==="candidate-pair"&&d.state==="succeeded"&&(n=d)}),((e=this.candidateDataCache)==null?void 0:e.length)>0){const d=this.candidateDataCache[this.candidateDataCache.length-1]||{},t=d,{_last:h}=t;c=jt(t,["_last"])}((i=this.candidateDataCache)==null?void 0:i.length)>=30&&this.reportNetwork(),n&&(n._last=c,this.candidateDataCache.push(n));let o=Object.keys(this.monitorDataCache).filter(d=>{var h;return((h=this.monitorDataCache[d])==null?void 0:h.length)>0});(this.streamTracks||[]).forEach(d=>{const h=d.msid;if(!h)return;let l;o.includes(h)&&(o=o.filter(p=>p!==h)),l=h===M.Audio?this.rtsManager.getPublishAudioStats(this.url):this.rtsManager.getPublishVideoStats(this.url,h),l.then(p=>{if(!p.timestamp)return;this.monitorDataCache[h]||(this.monitorDataCache[h]=[]);const u=this.getMediaStats(p.mediaSourceId);p._source=u;const f=this.monitorDataCache[h];let m;if((f==null?void 0:f.length)>0){const S=f[f.length-1]||{},b=S,{_last:v}=b;m=jt(b,["_last"])}(f==null?void 0:f.length)>=30&&this.reportPublishMonitor(h),p._last=m,p._codec=d.codec||"",this.monitorDataCache[h].push(p)})}),o.forEach(d=>{this.reportPublishMonitor(d)})}catch(r){}}),1e3))}stopStreamMonitor(){this.monitorTimerId&&(clearInterval(this.monitorTimerId),this.monitorTimerId=void 0),Object.keys(this.monitorDataCache).forEach(e=>{this.reportPublishMonitor(e)})}clearStream(){this.streamManager.stop(),this.audioPubState.setState(ie.AliRtcStatePublishIdle),this.videoPubState.setState(ie.AliRtcStatePublishIdle),this.videoSmallPubState.setState(ie.AliRtcStatePublishIdle),this.screenPubState.setState(ie.AliRtcStatePublishIdle)}getCurrentCameraDeviceId(){var e;return(e=this.streamManager.cameraStreamInfo.originVideoTrack)==null?void 0:e.getSettings().deviceId}getCurrentMicDeviceId(){var e;return(e=this.streamManager.cameraStreamInfo.originAudioTrack)==null?void 0:e.getSettings().deviceId}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.audioLevelMonitor.stop(),e>0&&this.streamManager.cameraStreamInfo.originAudioTrack&&this.audioLevelMonitor.start(this.streamManager.cameraStreamInfo.originAudioTrack,e),this.audioVolumeIndicationInterval=e)}sendSEI(e,t,i){return I(this,null,function*(){if(!this.url)return;let r=0;return r=!t||t<1?1:t-1,this.rtsManager.sendSEI(this.url,e,r,i)})}sendDataChannelMessage(e){var i;if(!((i=this.parameter.data)!=null&&i.enablePubDataChannel))throw new O(U.ERR_INNER,"data channel publish is not enabled");if(!this.dc)throw new O(U.ERR_INNER,"data channel is not ready");const t=function(r,n){let c=0;const o=[];for(;c<r.byteLength;){const d=Math.min(n,r.byteLength-c),h=r.slice(c,c+d);o.push(h),c+=d}return o}(e.toBuffer(),1156);t.forEach((r,n)=>{const c=new Fi(new mi(r.byteLength,n===t.length-1,n===0?1:0),r);this.dc.send(c.toGRTNBuffer())})}getStats(){return I(this,null,function*(){const e=[];if(this.hasAudioTrackInMS){const n=yield this.rtsManager.getPublishAudioStats(this.url);n&&e.push({stats:n,track:Jt.AliRtcAudioTrackMic})}const t=[];if(this.hasCameraTrackInMS){const n=yield this.rtsManager.getPublishVideoStats(this.url,M.VideoLarge);n&&t.push({track:oe.AliRtcVideoTrackCamera,streamType:ze.AliRtcVideoStreamTypeHigh,stats:n})}if(this.hasCameraDualTrackInMS){const n=yield this.rtsManager.getPublishVideoStats(this.url,M.VideoSmall);n&&t.push({track:oe.AliRtcVideoTrackCamera,streamType:ze.AliRtcVideoStreamTypeLow,stats:n})}if(this.hasScreenTrackInMS){const n=yield this.rtsManager.getPublishVideoStats(this.url,M.Screen);n&&t.push({track:oe.AliRtcVideoTrackScreen,stats:n})}let i;const r=yield this.rtsManager.getPCStats();return r==null||r.forEach(n=>{n.type==="candidate-pair"&&n.state==="succeeded"&&(i=n)}),{audio:e,video:t,candidate:i}})}},g(Tt,"logName","LocalUser"),Tt);De([C()],Ce.prototype,"clearPublishState",1),De([C()],Ce.prototype,"clear",1),De([C(H)],Ce.prototype,"startDefaultCameraAndMic",1),De([C()],Ce.prototype,"setViewConfig",1),De([C()],Ce.prototype,"startCameraCapture",1),De([C()],Ce.prototype,"stopCameraCapture",1),De([C()],Ce.prototype,"startAudioCapture",1),De([C()],Ce.prototype,"stopAudioCapture",1),De([C()],Ce.prototype,"startCameraAndMic",1),De([C()],Ce.prototype,"stopPreview",1),De([C()],Ce.prototype,"resumePublish",1),De([C()],Ce.prototype,"createLocalStream",1),De([C()],Ce.prototype,"stopLocalStream",1),De([C(H)],Ce.prototype,"startPublish",1),De([C()],Ce.prototype,"updateStreams",1),De([C(([s])=>[s])],Ce.prototype,"syncPublishToRoomServer",1),De([C()],Ce.prototype,"refreshPushStreamUrl",1),De([C(([s,a,e])=>[JSON.stringify(e)])],Ce.prototype,"publishAdd",1),De([C(([s,a])=>[JSON.stringify(a)])],Ce.prototype,"publishReplace",1),De([C(H)],Ce.prototype,"publishDeleteTracks",1),De([C()],Ce.prototype,"publishStop",1),De([C()],Ce.prototype,"unPublish",1),De([C(([s,a,e])=>[s.length,a,e])],Ce.prototype,"sendSEI",1);let jo=Ce;var lt=(s=>(s.OPUS="opus",s.H264="H264",s.H265="H265",s.AV1="AV1",s.UNKNOWN="",s))(lt||{}),ce=(s=>(s[s.NotSubscribe=0]="NotSubscribe",s[s.Subscribing=1]="Subscribing",s[s.Subscribed=2]="Subscribed",s))(ce||{}),Gt=(s=>(s.VideoTrackEnded="videoTrackEnded",s.AudioTrackEnded="audioTrackEnded",s.ScreenTrackEnded="screenTrackEnded",s))(Gt||{});const Qa=s=>I(this,null,function*(){return yield X.AliRTS.createStream({custom:!0,mediaStream:s})}),fi=s=>I(this,null,function*(){const a=(e=>{const t=new MediaStream;return t.addTrack(e),t})(s);return yield Qa(a)});var zo=Object.defineProperty,Wo=Object.getOwnPropertyDescriptor;class ji extends se{constructor(){super();g(this,"audioInfo",{subscribeState:ce.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:lt.UNKNOWN});g(this,"videoLargeInfo",{subscribeState:ce.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:lt.UNKNOWN});g(this,"videoSmallInfo",{subscribeState:ce.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:lt.UNKNOWN});g(this,"screenInfo",{subscribeState:ce.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:lt.UNKNOWN});g(this,"dataInfo",{subscribeState:ce.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:lt.UNKNOWN});g(this,"audioVolume",1);g(this,"audioMuted",!1);g(this,"userStatus")}getAudioInfo(){return this.audioInfo}getVideoSmallInfo(){return this.videoSmallInfo}getVideoLargeInfo(){return this.videoLargeInfo}getScreenInfo(){return this.screenInfo}getDataInfo(){return this.dataInfo}get subscribingInfos(){return[this.audioInfo,this.videoLargeInfo,this.videoSmallInfo,this.screenInfo].filter(e=>e.msid&&e.subscribeState===ce.Subscribed)}get hasTrack(){return this.hasAudio||this.hasVideo||this.hasScreen||this.hasData}get hasAudio(){return this.audioInfo.ssrc!==""}get hasVideo(){return this.videoLargeInfo.ssrc!==""||this.videoSmallInfo.ssrc!==""}get hasVideoLarge(){return this.videoLargeInfo.ssrc!==""}get hasVideoSmall(){return this.videoSmallInfo.ssrc!==""}get hasScreen(){return this.screenInfo.ssrc!==""}get hasData(){return this.dataInfo.ssrc!==""}get isAudioSubscribed(){return this.audioInfo.subscribeState===ce.Subscribed}get isAudioSubscribing(){return this.audioInfo.subscribeState===ce.Subscribing}get isVideoSubscribed(){return this.isVideoLargeSubscribed||this.isVideoSmallSubscribed}get isVideoSubscribing(){return this.isVideoLargeSubscribing||this.isVideoSmallSubscribing}get isVideoLargeSubscribed(){return this.videoLargeInfo.subscribeState===ce.Subscribed}get isVideoLargeSubscribing(){return this.videoLargeInfo.subscribeState===ce.Subscribing}get isVideoSmallSubscribed(){return this.videoSmallInfo.subscribeState===ce.Subscribed}get isVideoSmallSubscribing(){return this.videoSmallInfo.subscribeState===ce.Subscribing}get isScreenSubscribed(){return this.screenInfo.subscribeState===ce.Subscribed}get isScreenSubscribing(){return this.screenInfo.subscribeState===ce.Subscribing}get isDataSubscribed(){return this.dataInfo.subscribeState===ce.Subscribed}get isDataSubscribing(){return this.dataInfo.subscribeState===ce.Subscribing}get audioCodec(){return this.audioInfo.codec}get videoCodec(){return this.hasVideoLarge?this.videoLargeInfo.codec:this.hasVideoSmall?this.videoSmallInfo.codec:this.hasScreen?this.screenInfo.codec:lt.UNKNOWN}get audioTrackInfo(){return this.hasAudio?Jt.AliRtcAudioTrackMic:Jt.AliRtcAudioTrackNo}get videoTrackInfo(){return this.hasVideo&&this.hasScreen?oe.AliRtcVideoTrackBoth:this.hasVideo?oe.AliRtcVideoTrackCamera:this.hasScreen?oe.AliRtcVideoTrackScreen:oe.AliRtcVideoTrackNo}updateTracks(e){let t="",i="",r="",n="",c="";return e?(e.forEach(o=>{var p;let d=lt.UNKNOWN;const h=((p=o==null?void 0:o.attr)==null?void 0:p.reason)==="reconnect";if(o.userdata){const{codec:u}=JSON.parse(o.userdata);u&&(d=u)}var l;(l=o.msid)===M.Audio||l===Ar.Audio?(t=o.ssrc,this.audioInfo.msid=o.msid,this.audioInfo.codec=d,(h||this.audioInfo.ssrc!==t)&&(this.audioInfo.subscribeState=ce.NotSubscribe)):(u=>u===M.VideoSmall)(o.msid)?(r=o.ssrc,this.videoSmallInfo.msid=o.msid,this.videoSmallInfo.codec=d,(h||this.videoSmallInfo.ssrc!==r)&&(this.videoSmallInfo.subscribeState=ce.NotSubscribe)):(u=>u===M.VideoLarge||u===Ar.VideoLarge)(o.msid)?(i=o.ssrc,this.videoLargeInfo.msid=o.msid,this.videoLargeInfo.codec=d,(h||this.videoLargeInfo.ssrc!==i)&&(this.videoLargeInfo.subscribeState=ce.NotSubscribe)):(u=>u===M.Screen)(o.msid)?(n=o.ssrc,this.screenInfo.msid=o.msid,this.screenInfo.codec=d,(h||this.screenInfo.ssrc!==n)&&(this.screenInfo.subscribeState=ce.NotSubscribe)):(u=>u===M.Data)(o.msid)&&(c=o.ssrc,this.dataInfo.msid=o.msid,this.dataInfo.codec=d,(h||this.dataInfo.ssrc!==c)&&(this.dataInfo.subscribeState=ce.NotSubscribe))}),this.updateRemoteTrackSsrc(t,i,r,n,c)):this.updateRemoteTrackSsrc(t,i,r,n,c),{}}updateRemoteTrackSsrc(e,t,i,r,n){this.audioInfo.ssrc=e,this.videoSmallInfo.ssrc=i,this.videoLargeInfo.ssrc=t,this.screenInfo.ssrc=r,this.dataInfo.ssrc=n}markRemoteTrackSubscribing(e){return e.video&&(e.vMsid===this.videoSmallInfo.msid&&(this.videoSmallInfo.subscribeState=ce.Subscribing),e.vMsid!==this.videoLargeInfo.msid&&e.vMsid||(this.videoLargeInfo.subscribeState=ce.Subscribing)),e.screen&&(this.screenInfo.subscribeState=ce.Subscribing),e.audio&&(this.audioInfo.subscribeState=ce.Subscribing),e.data&&(this.dataInfo.subscribeState=ce.Subscribing),{videoLargeInfo:this.videoLargeInfo,videoSmallInfo:this.videoSmallInfo}}updateRemoteTrackSubState(e){return e.video!==void 0&&(e.vMsid!==this.videoSmallInfo.msid&&e.vMsid||(this.videoSmallInfo.subscribeState=e.video?ce.Subscribed:ce.NotSubscribe),e.vMsid!==this.videoLargeInfo.msid&&e.vMsid||(this.videoLargeInfo.subscribeState=e.video?ce.Subscribed:ce.NotSubscribe)),e.screen!==void 0&&(this.screenInfo.subscribeState=e.screen?ce.Subscribed:ce.NotSubscribe),e.audio!==void 0&&(this.audioInfo.subscribeState=e.audio?ce.Subscribed:ce.NotSubscribe),e.data!==void 0&&(this.dataInfo.subscribeState=e.data?ce.Subscribed:ce.NotSubscribe),{audioInfo:this.audioInfo,videoLargeInfo:this.videoLargeInfo,videoSmallInfo:this.videoSmallInfo,screenInfo:this.screenInfo,dataInfo:this.dataInfo}}updateRemoteUserDeviceStatus(e){let t=Wa.parseStatus(e);const{audioDisable:i,videoDisable:r,screenDisable:n}=t;return this.userStatus?(this.userStatus.audioDisable!=i&&(this.userStatus.audioDisable=i,this.emit(Ye.Remote,i?Ee.MuteAudio:Ee.UnmuteAudio)),this.userStatus.videoDisable!=r&&(this.userStatus.videoDisable=r,this.emit(Ye.Remote,r?Ee.MuteVideo:Ee.UnmuteVideo)),this.userStatus.screenDisable!=n&&(this.userStatus.screenDisable=n,this.emit(Ye.Remote,n?Ee.MuteScreen:Ee.UnmuteScreen))):(this.userStatus=t,this.emit(Ye.Remote,i?Ee.MuteAudio:Ee.UnmuteAudio),this.emit(Ye.Remote,r?Ee.MuteVideo:Ee.UnmuteVideo),this.emit(Ye.Remote,n?Ee.MuteScreen:Ee.UnmuteScreen)),!1}}g(ji,"logName","RemoteStreamInfo"),((s,a,e,t)=>{for(var i,r=t>1?void 0:t?Wo(a,e):a,n=s.length-1;n>=0;n--)(i=s[n])&&(r=(t?i(a,e,r):i(r))||r);t&&r&&zo(a,e,r)})([C()],ji.prototype,"updateRemoteTrackSubState",1);class Za{constructor(a){g(this,"remoteUser");this.remoteUser=a}get userId(){return this.remoteUser.userId}get displayName(){return this.remoteUser.displayname}get isMuteAudioPlaying(){return this.remoteUser.getAudioMuted()}get hasAudio(){return this.remoteUser.hasAudioTrack}get hasCamera(){return this.remoteUser.hasVideoTrack}get hasCameraLarge(){return this.remoteUser.hasVideoLargeTrack}get hasCameraSmall(){return this.remoteUser.hasVideoSmallTrack}get hasScreenShare(){return this.remoteUser.hasScreenTrack}get isAudioSubscribing(){return this.remoteUser.isAudioSubscribing}get isVideoSubscribing(){return this.remoteUser.isVideoSubscribing}get isVideoLargeSubscribing(){return this.remoteUser.isVideoLargeSubscribing}get isVideoSmallSubscribing(){return this.remoteUser.isVideoSmallSubscribing}get isScreenSubscribing(){return this.remoteUser.isScreenSubscribing}get audioElement(){return this.remoteUser.getAudioElement()}}var $o=Object.defineProperty,Ko=Object.getOwnPropertyDescriptor,Ke=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?Ko(a,e):a,n=s.length-1;n>=0;n--)(i=s[n])&&(r=(t?i(a,e,r):i(r))||r);return t&&r&&$o(a,e,r),r};class ai extends se{constructor(){super();g(this,"state");g(this,"time");g(this,"_enabled");this.state=me.AliRtcStateSubscribeIdle,this.time=Date.now(),this._enabled=!0}setState(e){if(this.state===e)return;const t=this.state,i=this.time;this.state=e,this.time=Date.now(),this.emit("change",t,e,Math.floor((this.time-i)/1e3))}get currentState(){return this.state}getEnabled(){return this._enabled}setEnabled(e){this._enabled=e}}const We=(Qe=class extends za{constructor(e){var u;const{userId:t,displayName:i,rtsManager:r,usersViewMap:n,slsReporter:c,signalingManager:o,localUser:d,audioVolumeIndicationInterval:h,playoutVolume:l,parameter:p}=e;super(t,i,r,h);g(this,"remoteCallid","");g(this,"remoteUserInfo");g(this,"localUser");g(this,"lastPubId","");g(this,"stream");g(this,"screenStream");g(this,"viewMap");g(this,"audioTrack");g(this,"audioElement");g(this,"subscribed",!1);g(this,"mediaStream");g(this,"secondaryMediaStream");g(this,"prevSubConfig");g(this,"signalingManager");g(this,"slsReporter");g(this,"wantSubAudio",!1);g(this,"wantSubVideo",!1);g(this,"wantSubScreen",!1);g(this,"defaultVideoStreamType",ze.AliRtcVideoStreamTypeHigh);g(this,"audioMuted",!1);g(this,"playoutVolume",1);g(this,"playoutGainNode");g(this,"audioSubState");g(this,"videoSubState");g(this,"videoLargeSubState",new ai);g(this,"videoSmallSubState",new ai);g(this,"screenSubState");g(this,"dataSubState");g(this,"dc");g(this,"dcMsgWaitingPieces",[]);g(this,"streamInfo");g(this,"_streamUrl","");g(this,"parameter",{});g(this,"monitorTimerId");g(this,"monitorDataCache",{});g(this,"trackTraceIdMap",{});g(this,"handleAudioContextSuspended",e=>{e.target.state==="suspended"&&this.emit("remoteAudioPlayError",this.uid,"AudioContext suspended")});g(this,"onDataChannelMessage",e=>{var r;const t=Fi.parse(e.slice(4));let i;if(t.body){if(!t.isFin)return t.header.frameType===1&&(this.dcMsgWaitingPieces=[]),void this.dcMsgWaitingPieces.push(t.body);if(this.dcMsgWaitingPieces.length>0){const n=this.dcMsgWaitingPieces.reduce((c,o)=>c+o.byteLength,t.body.byteLength);try{const c=new ArrayBuffer(n);let o=0;for(let d=0;d<this.dcMsgWaitingPieces.length;d++){const h=this.dcMsgWaitingPieces[d];new Uint8Array(c,o,h.byteLength).set(new Uint8Array(h)),o+=h.byteLength}new Uint8Array(c,o,t.body.byteLength).set(new Uint8Array(t.body)),i=Vt.parse(c)}catch(c){}this.dcMsgWaitingPieces=[],i||(i=Vt.parse(t.body))}else i=Vt.parse(t.body);i||V.event(`[${Qe.logName}]`,`parse data channel message fail, piece count: ${this.dcMsgWaitingPieces.length+1}`)}i&&(V.event(`[${Qe.logName}]`,`receive dc message, length(${(r=i.data)==null?void 0:r.byteLength})`),this.emit("remoteDataChannelMessage",this.uid,i))});g(this,"onDataChannelError",e=>{this.emit("occurError",O.fromError(e,U.ERR_SDK_SUBSCRIBE_DATA_ERROR))});g(this,"dataChannelConnected",e=>{e&&(this.dc=e,this.dc.datachannel&&(this.dc.datachannel.binaryType="arraybuffer"),this.dc.off("message",this.onDataChannelMessage),this.dc.off("error",this.onDataChannelError),this.dc.on("message",this.onDataChannelMessage),this.dc.on("error",this.onDataChannelError))});g(this,"handleAudioPaused",()=>{this.emit("remoteAudioPlayError",this.uid,"paused")});this.streamInfo=new ji,this.remoteUserInfo=new Za(this),this.parameter=p,this.streamInfo.on(Ye.Remote,f=>{this.emit(Ye.Remote,f,this.userId)}),this.signalingManager=o,this.viewMap=(u=n[t])!=null?u:{cameraViews:[],screenViews:[]},n[t]=this.viewMap,this.slsReporter=c,this.localUser=d,this.audioSubState=new ai,this.audioSubState.on("change",(f,m,b)=>{this.emit("audioSubscribeStateChanged",this.uid,f,m,b)}),this.videoSubState=new ai,this.videoSubState.on("change",(f,m,b)=>{this.emit("videoSubscribeStateChanged",this.uid,f,m,b)}),this.screenSubState=new ai,this.screenSubState.on("change",(f,m,b)=>{this.emit("screenSubscribeStateChanged",this.uid,f,m,b)}),this.dataSubState=new ai,this.dataSubState.on("change",(f,m,b)=>{this.emit("dataSubscribeStateChanged",this.uid,f,m,b)}),this.playoutVolume=l}get streamUrl(){return this._streamUrl}set streamUrl(e){this._streamUrl=e,this.rtsManager.updateAuth(e)}isWantSubAudio(){return this.wantSubAudio}setWantSubAudio(e){this.wantSubAudio=e}isWantSubVideo(){return this.wantSubVideo}setWantSubVideo(e){this.wantSubVideo=e}isWantSubScreen(){return this.wantSubScreen}setWantSubScreen(e){this.wantSubScreen=e}setRemoteDefaultVideoStreamType(e){e!==this.defaultVideoStreamType&&(this.defaultVideoStreamType=e,this.updateSubscribe(be.User))}setAudioMuted(e){this.audioMuted=e,this.toggleAudio(!e)}getAudioElement(){return this.audioElement}setPlayoutVolume(e){if(this.playoutVolume=e,this.audioElement)if(this.parameter.enableAudioContextPlayoutVolume)if(this.playoutGainNode)this.playoutGainNode.gain.value=e;else{const t=this.audioElement.srcObject;if(t){const i=Kt.getInstance();i.addEventListener("statechange",this.handleAudioContextSuspended);const r=i.createMediaStreamSource(t);this.audioElement.muted=!0,this.playoutGainNode=i.createGain(),r.connect(this.playoutGainNode),this.playoutGainNode.gain.value=e,this.playoutGainNode.connect(i.destination)}}else this.audioElement.volume=e}getAudioMuted(){return this.audioMuted}get hasAudioTrack(){var e;return!!((e=this.streamInfo)!=null&&e.hasAudio)}get hasVideoTrack(){var e;return!!((e=this.streamInfo)!=null&&e.hasVideo)}get hasVideoLargeTrack(){var e;return!!((e=this.streamInfo)!=null&&e.hasVideoLarge)}get hasVideoSmallTrack(){var e;return!!((e=this.streamInfo)!=null&&e.hasVideoSmall)}get hasScreenTrack(){var e;return!!((e=this.streamInfo)!=null&&e.hasScreen)}get isAudioSubscribing(){var e,t;return!!((e=this.streamInfo)!=null&&e.isAudioSubscribed)||!!((t=this.streamInfo)!=null&&t.isAudioSubscribing)}get isVideoSubscribing(){var e,t;return!!((e=this.streamInfo)!=null&&e.isVideoSubscribed)||!!((t=this.streamInfo)!=null&&t.isVideoSubscribing)}get isVideoLargeSubscribing(){var e,t;return!!((e=this.streamInfo)!=null&&e.isVideoLargeSubscribed)||!!((t=this.streamInfo)!=null&&t.isVideoLargeSubscribing)}get isVideoSmallSubscribing(){var e,t;return!!((e=this.streamInfo)!=null&&e.isVideoSmallSubscribed)||!!((t=this.streamInfo)!=null&&t.isVideoSmallSubscribing)}get isScreenSubscribing(){var e,t;return!!((e=this.streamInfo)!=null&&e.isScreenSubscribed)||!!((t=this.streamInfo)!=null&&t.isScreenSubscribing)}get isDataSubscribing(){var e,t;return!!((e=this.streamInfo)!=null&&e.isDataSubscribed)||!!((t=this.streamInfo)!=null&&t.isDataSubscribing)}get audioEnabled(){var e,t;return!!((t=(e=this.stream)==null?void 0:e.audioTrack)!=null&&t.enabled)}get videoEnabled(){var e,t;return!!((t=(e=this.stream)==null?void 0:e.videoTrack)!=null&&t.enabled)}get screenEnabled(){var e,t;return!!((t=(e=this.screenStream)==null?void 0:e.videoTrack)!=null&&t.enabled)}get getAudioTrack(){return this.audioTrack}get getCameraStream(){return this.stream}get getScreenStream(){return this.screenStream}setViewConfig(e,t){if(t!==oe.AliRtcVideoTrackScreen&&t!==oe.AliRtcVideoTrackCamera)throw new O(U.ERR_INVALID_ARGUMENTS,"track is not AliRtcVideoTrackScreen or AliRtcVideoTrackCamera");e?wr(e).forEach(i=>{i.setAttribute("playsinline",""),X.AliRTS.BrowserUtil.isMicroMessenger&&(i.setAttribute("x5-video-player-type","h5-page"),i.setAttribute("x5-playsinline",""),X.AliRTS.SystenUtil.isAndroid||X.AliRTS.SystenUtil.isIos&&i.setAttribute("x-webkit-airplay","allow")),t===oe.AliRtcVideoTrackScreen?this.viewMap.screenViews.push(i):this.viewMap.cameraViews.push(i),this.play(i,t===oe.AliRtcVideoTrackScreen)}):(this.stopPlayAll(t===oe.AliRtcVideoTrackScreen),t===oe.AliRtcVideoTrackScreen?this.viewMap.screenViews=[]:this.viewMap.cameraViews=[])}clear(e=!0){return I(this,null,function*(){var t;this.subscribeStopDataChannel(),e&&this.doStopSubscribe(this.streamUrl),Yr(Qe.prototype,this,"clear").call(this),this.stopPlayAudio(),this.clearStream(),this.clearScreenStream(),this.playoutGainNode&&(this.playoutGainNode.disconnect(),this.playoutGainNode=void 0,Kt.getInstance().removeEventListener("statechange",this.handleAudioContextSuspended)),(t=this.streamInfo)==null||t.removeAllListeners(Ye.Remote)})}updateRemoteUserDeviceStatus(e){var t;(t=this.streamInfo)==null||t.updateRemoteUserDeviceStatus(e)}updateRemoteTracks(e,t,i,r){return I(this,null,function*(){var c;return this.remoteCallid=e,this.streamUrl&&this.streamInfo.hasTrack||(this.streamUrl=t),this.callId=e!=null?e:"",this.streamInfo||(this.streamInfo=new ji),(c=this.streamInfo)==null?void 0:c.updateTracks(r)})}subscribe(r,n){return I(this,arguments,function*(e,t,i=Date.now()){var u,f;let c=e;if(!c){const{hasAudio:m,hasVideo:b,hasScreen:S,hasData:v}=(u=this.streamInfo)!=null?u:{};c={audio:this.wantSubAudio&&m,video:this.wantSubVideo&&b,screen:this.wantSubScreen&&S,data:((f=this.parameter.data)==null?void 0:f.enableSubDataChannel)&&v}}this.streamInfo.markRemoteTrackSubscribing(c);const{screen:o,audio:d,video:h,vMsid:l}=c,p=[];(h||d)&&p.push({audio:d,video:h,vMsid:l}),o&&p.push({screen:o}),(p.length!==0||e!=null&&e.data)&&(yield Promise.all(p.map(m=>this.subscribeProxy(m,t||be.User,i))),e!=null&&e.data&&this.subscribeDataChannel())})}subscribeProxy(e,t,i){return I(this,null,function*(){var c,o,d,h;let r=new Date().getTime(),n="";try{e.audio&&this.audioSubState.setState(me.AliRtcStateSubscribing),e.video&&(this.videoSubState.currentState!==me.AliRtcStateSubscribeIdle&&this.videoSubState.currentState!==me.AliRtcStateNoSubscribe||this.videoSubState.setState(me.AliRtcStateSubscribing)),e.screen&&this.screenSubState.setState(me.AliRtcStateSubscribing);const l=yield this.rtsManager.subscribe({remoteUser:this,options:e},t,((c=this.localUser)==null?void 0:c.callId)||"",this.callId,i);this.streamInfo.updateRemoteTrackSubState(e),n=l.traceId||"";const{stream:p}=l;if(e.audio){this.trackTraceIdMap[M.Audio]=n;const f=p.audioTrack;f&&(this.audioTrack=f,(o=p.mediaStream)==null||o.removeTrack(f),this.playAudio(),this.audioVolumeIndicationInterval&&this.audioLevelMonitor.start(f,this.audioVolumeIndicationInterval)),this.audioSubState.getEnabled()||this.toggleAudio(!1),this.audioSubState.setState(me.AliRtcStateSubscribed)}e.video&&(this.updateStream(p,this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing),this.videoSubState.getEnabled()||this.toggleVideo(!1),this.videoSubState.setState(me.AliRtcStateSubscribed),e.vMsid===M.VideoSmall?(this.trackTraceIdMap[M.VideoSmall]=n,this.videoSmallSubState.setState(me.AliRtcStateSubscribed)):(this.trackTraceIdMap[M.VideoLarge]=n,this.videoLargeSubState.setState(me.AliRtcStateSubscribed))),e.screen&&(this.trackTraceIdMap[M.Screen]=n,this.updateScreenStream(p),this.videoSubState.getEnabled()||this.toggleScreen(!1),this.screenSubState.setState(me.AliRtcStateSubscribed));const u=new Date().getTime()-r;this.slsReporter.reportSubscribe(((d=this.localUser)==null?void 0:d.callId)||"",this.callId,!!e.video&&e.vMsid===M.VideoLarge,!!e.video&&e.vMsid===M.VideoSmall,!!e.screen,!!e.audio,0,"",u,{pctid:this.rtsManager.pcTraceId,subtid:n,ajsub:t===be.Join?1:0,url:this.streamUrl,est:r}),this.startStreamMonitor(),l.isHTTP&&l.statsCheckPromise&&(yield Promise.race([l.statsCheckPromise,xt(1500)]))}catch(l){const p=new Date().getTime()-r;e.audio&&this.audioSubState.setState(me.AliRtcStateNoSubscribe),e.video&&this.videoSubState.setState(me.AliRtcStateNoSubscribe),e.screen&&this.screenSubState.setState(me.AliRtcStateNoSubscribe),l&&(l.message=`user(${this.uid}) subscribe error, ${(l==null?void 0:l.message)||""}`);let u=U.ERR_INNER;e.audio&&(u=U.ERR_SDK_SUBSCRIBE_AUDIO_STREAM_FAILED),e.video&&(u=e.vMsid===M.VideoSmall?U.ERR_SDK_SUBSCRIBE_DUAL_STREAM_FAILED:U.ERR_SDK_SUBSCRIBE_VIDEO_STREAM_FAILED),e.screen&&(u=U.ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED),this.slsReporter.reportSubscribe(((h=this.localUser)==null?void 0:h.callId)||"",this.callId,!!e.video&&e.vMsid===M.VideoLarge,!!e.video&&e.vMsid===M.VideoSmall,!!e.screen,!!e.audio,u,"",p,{pctid:this.rtsManager.pcTraceId,subtid:"",ajsub:t===be.Join?1:0,url:this.streamUrl,est:r});const f=O.fromError(l,u);throw this.emit("remoteSubscribeError",f),f}})}subscribeDeleteTracks(e){return I(this,null,function*(){const{audio:t,video:i,screen:r,data:n,vMsid:c}=e,o=[];(t||i||n)&&o.push({audio:t,video:i,vMsid:c}),r&&o.push({screen:r}),o.length!==0&&(yield Promise.all(o.map(d=>this.subscribeDeleteProxy(d))),e.data&&this.subscribeStopDataChannel())})}subscribeDeleteProxy(e){return I(this,null,function*(){try{const t=yield this.rtsManager.subscribeDelete({remoteUser:this,options:e}),{stream:i}=t!=null?t:{},r={};e.audio===!0&&(r.audio=!1,this.audioSubState.setState(me.AliRtcStateNoSubscribe)),e.video===!0&&(r.video=!1,e.vMsid===M.VideoSmall?(this.videoSmallSubState.setState(me.AliRtcStateNoSubscribe),this.videoLargeSubState.currentState!==me.AliRtcStateNoSubscribe&&this.videoLargeSubState.currentState!==me.AliRtcStateSubscribeIdle||this.videoSubState.setState(me.AliRtcStateNoSubscribe)):(this.videoLargeSubState.setState(me.AliRtcStateNoSubscribe),this.videoSmallSubState.currentState!==me.AliRtcStateNoSubscribe&&this.videoSmallSubState.currentState!==me.AliRtcStateSubscribeIdle||this.videoSubState.setState(me.AliRtcStateNoSubscribe))),e.screen===!0&&(r.screen=!1,this.screenSubState.setState(me.AliRtcStateNoSubscribe));const{callId:n,remoteCallid:c}=this,o={callid:n,remoteCallid:c,remoteStream:i};return e.audio&&(this.audioLevelMonitor.stop(),this.stopPlayAudio(),this.audioTrack=void 0),this.streamInfo.updateRemoteTrackSubState({audio:e.audio!==!0&&void 0,video:e.video!==!0&&void 0,screen:e.screen!==!0&&void 0,vMsid:e.vMsid}),o}catch(t){throw O.fromError(t,U.ERR_INNER,"subscribe delete failed")}})}restore(){this.callId="",this.clearStream(),this.clearScreenStream(),this.audioTrack=void 0,this.streamInfo.updateRemoteTrackSubState({audio:!1,video:!1,screen:!1,data:!1}),this.audioElement&&this.audioElement.removeEventListener("pause",this.handleAudioPaused)}resumeAudio(){return I(this,null,function*(){const e=Kt.getInstance();return e.state!=="running"&&e.resume(),this.audioElement?this.audioElement.play():this.playAudio()})}resumeVideo(e){return I(this,null,function*(){return e&&e!==oe.AliRtcVideoTrackCamera&&e!==oe.AliRtcVideoTrackBoth?e&&e!==oe.AliRtcVideoTrackScreen&&e!==oe.AliRtcVideoTrackBoth?void 0:this.playAll(!0):this.playAll()})}resumePlay(){this.playAudio(),this.playAll(),this.playAll(!0)}stopSubscribe(e){return I(this,null,function*(){var i,r;let t=new Date().getTime();try{let n;n=e?yield this.subscribeDeleteTracks(e):yield this.doStopSubscribe(this.streamUrl),this.slsReporter.reportUnsubscribe(((i=this.localUser)==null?void 0:i.callId)||(n==null?void 0:n.callid)||"",this.callId,new Date().getTime()-t,0,"")}catch(n){throw this.slsReporter.reportUnsubscribe(((r=this.localUser)==null?void 0:r.callId)||"",this.callId,new Date().getTime()-t,0,""),n}})}doStopSubscribe(e){return I(this,null,function*(){var r,n,c,o;const{callId:t,remoteCallid:i}=this;if((this.isAudioSubscribing||this.isVideoSubscribing||this.isScreenSubscribing)&&e)try{this.stopStreamMonitor(),yield this.rtsManager.subscribeStop(e),this.restore();const d={callid:t,remoteCallid:i,remoteStream:this.stream};return this.callId="",d}catch(d){if(((o=(c=(n=(r=d==null?void 0:d.extraInfo)==null?void 0:r.parsedData)==null?void 0:n.streams)==null?void 0:c[0])==null?void 0:o.res_code)!==404)throw O.fromError(d,U.ERR_INNER,"subscribe stop failed")}})}updateStream(e,t=!1){return I(this,null,function*(){this.stream&&this.stream.videoTrack&&e.mediaStream&&t&&(yield new Promise(i=>{let r,n;if(e.mediaStream){n=document.createElement("video");const c=()=>{V.event(`uid: ${this.userId} new mediaStream canplay`),n&&n.removeEventListener("canplaythrough",c,!1),n=void 0,clearTimeout(r),i(!0)};n.addEventListener("canplaythrough",c,!1),(n._playPromise||Promise.resolve()).then(()=>{n&&e.mediaStream&&(n.srcObject=e.mediaStream)})}else i(!0);r=window.setTimeout(()=>{V.event(`uid: ${this.userId} new mediaStream timeout`),n=void 0,i(!0)},3e3)}),this.updateSubscribe(be.User)),this.stream=e,this.playAll(!1,t),!this.subscribed&&e&&(this.subscribed=!0),e.hasAudio&&this.isAudioSubscribing&&e.enableAudio(),e.hasVideo&&this.isVideoSubscribing&&e.enableVideo()})}updateScreenStream(e){this.screenStream=e,this.playAll(!0),!this.subscribed&&e&&(this.subscribed=!0),e.hasVideo&&this.isScreenSubscribing&&e.enableVideo()}clearStream(){var e;(e=this.stream)==null||e.stop(),this.stream=void 0}clearScreenStream(){var e;(e=this.screenStream)==null||e.stop(),this.screenStream=void 0}subscribeDataChannel(){if(this.dc)try{this.dc.dispose(),this.dcMsgWaitingPieces=[],this.dc.off("message",this.onDataChannelMessage),this.dc=void 0}catch(e){}(this.streamInfo.hasAudio||this.streamInfo.hasVideo||this.streamInfo.hasScreen)&&(this.dataSubState.setState(me.AliRtcStateSubscribing),this.rtsManager.subscribeAddDataChannel(this.streamUrl).then(e=>{if(e)return this.dataChannelConnected(e),this.dataSubState.setState(me.AliRtcStateSubscribed),void this.streamInfo.updateRemoteTrackSubState({data:!0});throw new Error("no dc founded")}).catch(e=>{const t=O.fromError(e,U.ERR_INNER,"subscribe data failed");this.emit("remoteSubscribeError",t),this.dataSubState.setState(me.AliRtcStateNoSubscribe)}))}subscribeStopDataChannel(){if(this.dc){try{this.rtsManager.subscribeStopDatachannel(this.streamUrl,this.dc)}catch(e){}this.dcMsgWaitingPieces=[],this.dc.off("message",this.onDataChannelMessage),this.dc.off("error",this.onDataChannelError),this.dataSubState.setState(me.AliRtcStateNoSubscribe),this.dc=void 0,this.streamInfo.updateRemoteTrackSubState({data:!1})}}getRetryOptions(){var i,r,n,c,o,d,h;const e={};this.wantSubAudio&&((i=this.streamInfo)!=null&&i.hasAudio)&&(e.audio=!0,e.aMsid=((r=this.streamInfo.getAudioInfo())==null?void 0:r.msid)||M.Audio),this.wantSubVideo&&((n=this.streamInfo)!=null&&n.hasVideo)&&(this.defaultVideoStreamType===ze.AliRtcVideoStreamTypeLow&&((c=this.streamInfo)!=null&&c.hasVideoSmall)?(e.video=!0,e.vMsid=M.VideoSmall):(o=this.streamInfo)!=null&&o.hasVideoLarge&&(e.video=!0,e.vMsid=((d=this.streamInfo.getVideoLargeInfo())==null?void 0:d.msid)||M.VideoLarge)),this.wantSubScreen&&((h=this.streamInfo)!=null&&h.hasScreen)&&(e.screen=!0);let t={};if(e.audio||e.video)t={audio:e.audio,video:e.video},this.streamInfo.updateRemoteTrackSubState({screen:!1,data:!1});else{if(!e.screen)return;t={screen:e.screen},this.streamInfo.updateRemoteTrackSubState({data:!1})}return{remoteUser:this,options:t}}updateSubscribe(e){var n,c,o,d,h,l,p,u,f,m,b,S,v,_,w,y,A;const t=Date.now(),i={},r={};if(this.wantSubAudio&&!this.isAudioSubscribing&&((n=this.streamInfo)!=null&&n.hasAudio)?(i.audio=!0,i.aMsid=((c=this.streamInfo.getAudioInfo())==null?void 0:c.msid)||M.Audio):this.wantSubAudio&&((o=this.streamInfo)!=null&&o.hasAudio)||!this.isAudioSubscribing||(r.audio=!0,r.aMsid=((d=this.streamInfo.getAudioInfo())==null?void 0:d.msid)||M.Audio),this.wantSubVideo&&((h=this.streamInfo)!=null&&h.hasVideo)?(this.defaultVideoStreamType===ze.AliRtcVideoStreamTypeLow&&!this.isVideoSmallSubscribing&&((l=this.streamInfo)!=null&&l.hasVideoSmall)?(i.video=!0,i.vMsid=M.VideoSmall):this.isVideoLargeSubscribing||!((p=this.streamInfo)!=null&&p.hasVideoLarge)||this.defaultVideoStreamType===ze.AliRtcVideoStreamTypeLow&&this.isVideoSmallSubscribing||(i.video=!0,i.vMsid=((u=this.streamInfo.getVideoLargeInfo())==null?void 0:u.msid)||M.VideoLarge),this.defaultVideoStreamType===ze.AliRtcVideoStreamTypeLow&&this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing&&this.streamInfo.hasVideoSmall?(r.video=!0,r.vMsid=M.VideoLarge):this.defaultVideoStreamType===ze.AliRtcVideoStreamTypeHigh&&this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing&&(r.video=!0,r.vMsid=M.VideoSmall)):this.wantSubVideo&&((f=this.streamInfo)!=null&&f.hasVideo)||!this.isVideoSubscribing||(r.video=!0,r.vMsid=this.streamInfo.isVideoSmallSubscribed||this.streamInfo.isVideoSmallSubscribing?M.VideoSmall:((m=this.streamInfo.getVideoLargeInfo())==null?void 0:m.msid)||M.VideoLarge),this.wantSubScreen&&!this.isScreenSubscribing&&((b=this.streamInfo)!=null&&b.hasScreen)?i.screen=!0:this.wantSubScreen&&((S=this.streamInfo)!=null&&S.hasScreen)||!this.isScreenSubscribing||(r.screen=!0),(v=this.parameter.data)!=null&&v.enableSubDataChannel&&!this.isDataSubscribing&&((_=this.streamInfo)!=null&&_.hasData)?i.data=!0:(w=this.parameter.data)!=null&&w.enableSubDataChannel&&((y=this.streamInfo)!=null&&y.hasData)||!this.isDataSubscribing||(r.data=!0),this.dc&&i.data&&this.subscribeStopDataChannel(),(i.audio||i.video||i.screen||i.data)&&(this.createCallId(),this.subscribe(i,e,t)),(r.audio||r.video||r.screen)&&this.subscribeDeleteTracks(r),e===be.Reconnect){if(V.event(`[${Qe.logName}]`,"reconnect, try to resume"),this.streamInfo.hasData&&!i.data){const R=this.rtsManager.getDatachannelByMsid({url:this.streamUrl,msid:this.streamInfo.getDataInfo().msid||M.Data});this.dataChannelConnected(R)}if(this.streamInfo.hasAudio&&!i.audio){const R=this.rtsManager.getStreamByMsid({url:this.streamUrl,aMsid:this.streamInfo.getAudioInfo().msid||M.Audio});R&&R.audioTrack&&(this.audioTrack=R.audioTrack,this.audioVolumeIndicationInterval>0&&(this.audioLevelMonitor.stop(),this.audioLevelMonitor.start(this.audioTrack,this.audioVolumeIndicationInterval)),this.playAudio())}if(this.streamInfo.hasVideo&&!i.video){const R=this.rtsManager.getStreamByMsid({url:this.streamUrl,vMsid:this.streamInfo.isVideoSmallSubscribed||this.streamInfo.isVideoSmallSubscribing?M.VideoSmall:((A=this.streamInfo.getVideoLargeInfo())==null?void 0:A.msid)||M.VideoLarge});R&&R.mediaStream&&(this.stream=R,this.playAll(!1))}if(this.streamInfo.hasScreen&&!i.screen){const R=this.rtsManager.getStreamByMsid({url:this.streamUrl,vMsid:this.streamInfo.getScreenInfo().msid||M.Screen});R&&R.mediaStream&&(this.screenStream=R,this.playAll(!0))}}return{addOption:i,deleteOption:r}}handleAutoPlayFailed(){V.event(`[${Qe.logName}]`,"auto play failed"),this.emit("remoteAudioAutoPlayFail",this.uid);const e=()=>{this.resumeAudio().then(()=>{document.removeEventListener("click",e,!1),document.removeEventListener("touchstart",e,!1)})};document.addEventListener("click",e,!1),document.addEventListener("touchstart",e,!1)}handleVideoPlayFailded(e,t){this.emit("remoteVideoAutoPlayFail",this.uid,t);const i=()=>{var n;const r=(n=t===oe.AliRtcVideoTrackScreen?this.screenStream:this.stream)==null?void 0:n.mediaStream;e.srcObject===r&&this.play(e,t===oe.AliRtcVideoTrackScreen),document.removeEventListener("click",i,!1),document.removeEventListener("touchstart",i,!1)};document.addEventListener("click",i,!1),document.addEventListener("touchstart",i,!1)}playAudio(){return I(this,null,function*(){var e,t;if(this.audioTrack){if(this.toggleAudio(!this.audioMuted),this.audioElement||(V.event(`[${Qe.logName}]`,this.userId,"create audio element"),this.audioElement=document.createElement("audio"),this.audioElement.setAttribute("autoplay","autoplay"),this.audioElement.addEventListener("pause",this.handleAudioPaused),this.setPlayoutVolume(this.playoutVolume)),((t=(e=this.audioElement.srcObject)==null?void 0:e.getAudioTracks())==null?void 0:t[0])!==this.audioTrack){let i=this.audioElement.srcObject;i?i.getAudioTracks().forEach(r=>{i.removeTrack(r)}):(i=new MediaStream,this.audioElement.srcObject=i),i.addTrack(this.audioTrack)}if(X.AliRTS.SystenUtil.isIos&&parseInt(X.AliRTS.SystenUtil.systemVersion)<=13){V.event(`[${Qe.logName}]`,"play audio for iOS 13-");const i=this.audioElement;i.setAttribute("autoplay","");const r=()=>{i.removeEventListener("playing",r),i.pause(),i.play().catch(()=>{this.handleAutoPlayFailed()})};this.audioElement.addEventListener("playing",r)}else(()=>{var i;V.event(`[${Qe.logName}]`,"try play audio"),(i=this.audioElement)==null||i.play().then(()=>{V.event(`[${Qe.logName}]`,"play audio success")}).catch(()=>{this.handleAutoPlayFailed()})})()}else V.event(`[${Qe.logName}]`,this.userId,"audio track is null")})}stopPlayAudio(){this.audioElement&&(this.audioElement.pause(),this.audioElement.removeEventListener("pause",this.handleAudioPaused))}playAll(e=!1,t=!1){e?(this.viewMap.screenViews||[]).forEach(i=>{this.play(i,e,t)}):(this.viewMap.cameraViews||[]).forEach(i=>{this.play(i,e,t)})}play(e,t=!1,i=!1){const r=t?this.screenStream:this.stream;e&&r&&r.mediaStream&&Xa(e,r.mediaStream,i).catch(n=>{n.code!==20&&n.name!=="AbortError"&&this.handleVideoPlayFailded(e,t?oe.AliRtcVideoTrackScreen:oe.AliRtcVideoTrackCamera)})}stopPlayAll(e=!1){e?this.viewMap.screenViews.forEach(t=>{_t(t)}):this.viewMap.cameraViews.forEach(t=>{_t(t)})}toggleAudio(e=!0){this.audioSubState.setEnabled(e),this.audioElement&&(this.audioElement.muted=!e)}toggleVideo(e=!0){this.videoSubState.setEnabled(e),this.stream&&(e?this.stream.enableVideo():this.stream.disableVideo())}toggleScreen(e=!0){this.screenSubState.setEnabled(e),this.screenStream&&(e?this.screenStream.enableVideo():this.screenStream.disableVideo())}getStats(){return I(this,null,function*(){var i,r,n,c,o;const e=[];if(this.isAudioSubscribing){const d=yield this.rtsManager.getSubscribeAudioStats(this.streamUrl);d&&e.push({uid:this.uid,track:Jt.AliRtcAudioTrackMic,stats:d})}const t=[];if((i=this.streamInfo)!=null&&i.isVideoLargeSubscribed){const d=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,((r=this.streamInfo.getVideoLargeInfo())==null?void 0:r.msid)||M.VideoLarge);d&&t.push({uid:this.uid,track:oe.AliRtcVideoTrackCamera,streamType:ze.AliRtcVideoStreamTypeHigh,stats:d})}if((n=this.streamInfo)!=null&&n.isVideoSmallSubscribed){const d=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,((c=this.streamInfo.getVideoSmallInfo())==null?void 0:c.msid)||M.VideoSmall);d&&t.push({uid:this.uid,track:oe.AliRtcVideoTrackCamera,streamType:ze.AliRtcVideoStreamTypeLow,stats:d})}if(this.isScreenSubscribing){const d=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,((o=this.streamInfo.getScreenInfo())==null?void 0:o.msid)||M.Screen);d&&t.push({uid:this.uid,track:oe.AliRtcVideoTrackScreen,stats:d})}return{audio:e,video:t}})}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.audioLevelMonitor.stop(),e>0&&this.audioTrack&&this.audioLevelMonitor.start(this.audioTrack,e),this.audioVolumeIndicationInterval=e)}reportSubscribeMonitor(e){var t;e&&(this.slsReporter.reportSubscribeMonitor(((t=this.localUser)==null?void 0:t.callId)||"",this.callId,this.trackTraceIdMap[e]||"",e,this.monitorDataCache[e]),this.monitorDataCache[e]=[])}startStreamMonitor(){this.monitorTimerId||(this.monitorTimerId=window.setInterval(()=>I(this,null,function*(){try{if(this.streamInfo.subscribingInfos.length===0)return void this.stopStreamMonitor();let e=Object.keys(this.monitorDataCache).filter(t=>{var i;return((i=this.monitorDataCache[t])==null?void 0:i.length)>0});this.streamInfo.subscribingInfos.forEach(t=>{const i=t.msid;if(!i)return;let r;e.includes(i)&&(e=e.filter(c=>c!==i));const n=i===M.Audio;r=n?this.rtsManager.getSubscribeAudioStats(this.streamUrl):this.rtsManager.getSubscribeVideoStats(this.streamUrl,i),r.then(c=>{var l;if(!c.timestamp)return;this.monitorDataCache[i]||(this.monitorDataCache[i]=[]);const o=this.monitorDataCache[i];let d;if((o==null?void 0:o.length)>0){const p=o[o.length-1]||{},h=p,{_last:u}=h;d=jt(h,["_last"])}(o==null?void 0:o.length)>=30&&this.reportSubscribeMonitor(i),c._last=d,c._codec=t.codec,n&&(c._source=(l=this.localUser)==null?void 0:l.getMediaStats(c.playoutId)),this.monitorDataCache[i].push(c)})}),e.forEach(t=>{this.reportSubscribeMonitor(t)})}catch(e){}}),1e3))}stopStreamMonitor(){this.monitorTimerId&&(clearInterval(this.monitorTimerId),this.monitorTimerId=void 0),Object.keys(this.monitorDataCache).forEach(e=>{this.reportSubscribeMonitor(e)})}},g(Qe,"logName","RemoteUser"),Qe);Ke([C()],We.prototype,"clear",1),Ke([C()],We.prototype,"updateRemoteUserDeviceStatus",1),Ke([C()],We.prototype,"updateRemoteTracks",1),Ke([C(H)],We.prototype,"subscribe",1),Ke([C()],We.prototype,"subscribeProxy",1),Ke([C(H)],We.prototype,"subscribeDeleteProxy",1),Ke([C()],We.prototype,"restore",1),Ke([C(H)],We.prototype,"resumeAudio",1),Ke([C(H)],We.prototype,"stopSubscribe",1),Ke([C(H)],We.prototype,"doStopSubscribe",1),Ke([C()],We.prototype,"clearStream",1),Ke([C()],We.prototype,"clearScreenStream",1),Ke([C()],We.prototype,"updateSubscribe",1),Ke([C()],We.prototype,"playAudio",1),Ke([C()],We.prototype,"stopPlayAudio",1),Ke([C((s,a,e)=>[typeof s=="string"?s:s==null?void 0:s.nodeType,a||"-",e||"-"])],We.prototype,"play",1),Ke([C()],We.prototype,"stopPlayAll",1);let Jo=We;var Ot=(s=>(s[s.AliRtcPluginErrorCodeSuccess=0]="AliRtcPluginErrorCodeSuccess",s[s.AliRtcPluginErrorCodeFailed=-1]="AliRtcPluginErrorCodeFailed",s[s.AliRtcPluginErrorNoFindPlugin=-2]="AliRtcPluginErrorNoFindPlugin",s[s.AliRtcPluginErrorParameterError=-3]="AliRtcPluginErrorParameterError",s[s.AliRtcPluginErrorLoadError=-4]="AliRtcPluginErrorLoadError",s[s.AliRtcPluginErrorCreateError=-5]="AliRtcPluginErrorCreateError",s[s.AliRtcPluginErrorInitError=-6]="AliRtcPluginErrorInitError",s[s.AliRtcPluginErrorInitTokenError=-7]="AliRtcPluginErrorInitTokenError",s))(Ot||{});class Go extends se{constructor(){super(...arguments);g(this,"plugins",new Map)}add(e,t){if(this.plugins.has(e.name))throw new O(Ot.AliRtcPluginErrorCreateError,`Plugin ${e.name} already exists`);this.plugins.set(e.name,e),t&&e.setOptions(t),this.emit("added",e),e.on("enabled",()=>this.emit("added",e)),e.on("disabled",()=>this.emit("removed",e)),e.on("updated",()=>this.emit("updated",e))}remove(e){const t=this.plugins.get(e);if(!t)throw new O(Ot.AliRtcPluginErrorNoFindPlugin,`Plugin ${e} not founded`);this.plugins.delete(e),t.removeAllListeners(),this.emit("removed",t)}removeAll(){this.plugins.forEach(e=>{this.remove(e.name)})}get(e){return this.plugins.get(e)}has(e){return!!this.plugins.get(e)}getAll(){return Array.from(this.plugins.values())}}var qo=Object.defineProperty,Xo=Object.getOwnPropertyDescriptor,Be=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?Xo(a,e):a,n=s.length-1;n>=0;n--)(i=s[n])&&(r=(t?i(a,e,r):i(r))||r);return t&&r&&qo(a,e,r),r};const zi=([s])=>{const{remoteUser:a,options:e}=s;return[`user(${a.userId})`,e]},xe=(Te=class extends se{constructor(e,t,i){super();g(this,"rts");g(this,"encodedInsertableStreams",!0);g(this,"audioRedEnabled",!1);g(this,"localStreamManager");g(this,"slsReporter");g(this,"_rtsPeerConnectionType","publish");g(this,"connecting",!1);g(this,"connected",!1);g(this,"rtsDisconnected",!1);g(this,"_pcTraceId","");g(this,"_localJoinTime",0);g(this,"connectionResolve");g(this,"connectingPromise");g(this,"dcResolve");g(this,"dcReject");g(this,"dcConnectingPromise");g(this,"_publishingTracks",[]);g(this,"parameter",{});g(this,"preferredPubL1Ip");g(this,"preferredSubL1Ip");this.localStreamManager=e,this.slsReporter=t,this.parameter=i,this.rts=X.AliRTS.createClient({singlePcConfig:{usePcReconnect:!0},datachannelDelayOpen:!0}),this.addRTSListener()}addRTSListener(){this.rts.on("connectStatusChange",e=>{var t,i,r,n;if(V.event(`[${Te.logName}]`,"rts connectStatusChange to:",e.status),e.status===X.EConnectStatus.CONNECT_STATUS_DISCONNECTED)this.dcReject&&this.dcReject(),this.setConnected(!1),this.rtsDisconnected=!0,this.slsReporter.reportWarning("rts disconnected"),this.emit("disconnected");else if(e.status===X.EConnectStatus.CONNECT_STATUS_CONNECTED){if(this.rtsDisconnected){const c=(n=(r=(i=(t=this.rts.commonController)==null?void 0:t.peerCore)==null?void 0:i.getSignal())==null?void 0:r.getDatachannelCore())==null?void 0:n.readyState;V.event(`[${Te.logName}]`,"dcReadyState:",c),c==="open"&&this.dcResolve&&this.dcResolve(!0)}this.rtsDisconnected=!1,this.setConnected(!0)}}),this.rts.on("reconnectFinish",()=>{V.event(`[${Te.logName}]`,"rts reconnectFinish");try{this.emit("connected",!0,this._rtsPeerConnectionType)}catch(e){V.error(`[${Te.logName}]`,"emit connected error:",e)}}),this.rts.on("datachannelStatusChange",e=>{V.event(`[${Te.logName}]`,"rts datachannelStatusChange to:",e.status),e.status===X.EDatachannelStatus.DATACHANNEL_STATUS_OPEN?this.dcResolve&&this.dcResolve(!0):e.status===X.EDatachannelStatus.DATACHANNEL_STATUS_CLOSE&&(this.dcReject&&this.dcReject(),this.dcConnectingPromise=new Promise((t,i)=>{this.dcResolve=t,this.dcReject=i}))}),this.rts.on("receivedSEI",e=>{var t;if(this.emit("seimessage",e.url,e.sei.payloadType,e.sei.data),e.sei.payloadType===99)try{const i=JSON.parse(new TextDecoder().decode(e.sei.data));this.slsReporter.reportLoopAudioDelay(((t=this.publishingTracks.find(r=>r.type==="audio"))==null?void 0:t.ssrc)||"",i)}catch(i){}}),this.rts.on("onError",e=>{V.event(`[${Te.logName}]`,"rts onError event:",e)}),this.rts.on("reconnect",e=>{V.event(`[${Te.logName}]`,"rts reconnect event:",e)})}updateAuth(e){this.rts.updateAuth(e)}get pcTraceId(){return this._pcTraceId}set localJoinTime(e){this._localJoinTime=e}setEncodedInsertableStreams(e){this.encodedInsertableStreams=e}setReceiverPreferredVideoCodecH265(){var r;let e=(r=RTCRtpReceiver.getCapabilities("video"))==null?void 0:r.codecs;if(!e||e.length===0)return;const t=e.filter(n=>n.mimeType.toLowerCase()!=="video/rtx");let i=t.findIndex(n=>n.mimeType==="video/H265");if(i+1){let n=t[i];t.splice(i,1),t.unshift(n),this.rts.setReceiverCodecPreferences({video:t})}}setSenderPreferredVideoCodecH265(){var r;let e=(r=RTCRtpSender.getCapabilities("video"))==null?void 0:r.codecs;if(!e||e.length===0)return;const t=e.filter(n=>n.mimeType.toLowerCase()!=="video/rtx");let i=t.findIndex(n=>n.mimeType==="video/H265");if(i+1){let n=t[i];t.splice(i,1),t.unshift(n),this.rts.setSenderCodecPreferences({video:t})}}supportVideoCodec(e){var t,i,r;return e===lt.H265?(t=RTCRtpSender.getCapabilities("video"))==null?void 0:t.codecs.some(n=>n.mimeType==="video/H265"):e===lt.H264?(i=RTCRtpSender.getCapabilities("video"))==null?void 0:i.codecs.some(n=>n.mimeType==="video/H264"):e===lt.AV1&&((r=RTCRtpSender.getCapabilities("video"))==null?void 0:r.codecs.some(n=>n.mimeType==="video/AV1"))}changeVideoCodec(e){this.supportVideoCodec(e)?(V.info(`[${Te.logName}]`,"changeVideoCodec to:",e),lt.H265===e&&(this.setSenderPreferredVideoCodecH265(),this.setReceiverPreferredVideoCodecH265())):V.warn(`[${Te.logName}]`,`not support video codec: ${e}`)}setAudioRedEnabled(e){var t;if(e!==this.audioRedEnabled){try{const i=[...((t=RTCRtpReceiver.getCapabilities("audio"))==null?void 0:t.codecs)||[]];if(i.length>0){if(e){const r=i.findIndex(c=>c.mimeType==="audio/red"),n=i.findIndex(c=>c.mimeType==="audio/opus");if(r>-1&&n>-1&&r>n){const c=i[n];i[n]=i[r],i[r]=c}}this.rts.setSenderCodecPreferences({audio:i}),this.rts.setReceiverCodecPreferences({audio:i})}}catch(i){}this.audioRedEnabled=e}}clear(){this.setConnected(!1),this.rtsDisconnected=!1,this._publishingTracks=[];try{this.rts.removeAllListeners(),this.rts.unpublish(),this.rts.unsubscribe()}catch(e){}this.rts=X.AliRTS.createClient(),this.addRTSListener()}startConnect(){this.connecting=!0,this.connectingPromise=new Promise(e=>{this.connectionResolve=e}),this.dcConnectingPromise=new Promise((e,t)=>{this.dcResolve=e,this.dcReject=t})}setConnected(e){var t;this.connected=e,this.connecting=!1,(t=this.connectionResolve)==null||t.call(this,!0)}get isConnecting(){return this.connecting}get isConnected(){return this.connected}get publishingTracks(){return this._publishingTracks}getPubMsid(e,t){const{aMsid:i,vMsid:r}=t!=null?t:{},n={};return e.hasAudio&&(n.aMsid=[i!=null?i:M.Audio]),e.hasScreen&&(n.vMsid=[M.Screen]),e.hasVideo&&(n.vMsid=[r!=null?r:t!=null&&t.isScreen?M.Screen:M.VideoLarge]),n}updatePublishingTracks(e){e&&(this._publishingTracks=e.map(({msid:t,from:i,ssrc:r,codec:n,type:c,trackId:o})=>({msid:t,from:i,type:c,ssrc:`${r}`,codec:n!=null?n:"",trackId:o})))}httpPublish(n,c){return I(this,arguments,function*(e,t,i=!1,r=yt.MANUAL){let o;const d=Date.now();this.startConnect();const{publishStream:h,videoSmallStream:l,screenStream:p,vMsid:u}=yield this.localStreamManager.createHTTPPublishStream();if(!h)return V.warn(`[${Te.logName}]`,"publishStream is null"),{traceId:"",l1ip:o};const f=this.getPubMsid(h,{vMsid:u});f.answerSdpHook=_=>{const w=/\d+\.\d+\.\d+\.\d+(?=\s+1106|\s+8000)/.exec(_);return w!=null&&w[0]&&(o=w[0]),_},this.handleHTTPConfig(f),this._rtsPeerConnectionType="publish";let m=!h.hasVideo,b=u,S="";const v=Date.now();try{S=yield this.rts.publish(Er(e,this.preferredPubL1Ip),h,f)}catch(_){this.setConnected(!1);const w=2e3-(Date.now()-v);throw w<=0?this.emit("disconnected"):setTimeout(()=>{this.emit("disconnected")},w),this.slsReporter.reportPublish(i,e,t,h.hasVideo&&(!u||u===M.VideoLarge),h.hasVideo&&u===M.VideoSmall,h.hasVideo&&u===M.Screen,h.hasAudio,(_==null?void 0:_.errorCode)||-1,this.pcTraceId,"",v),O.fromRtsError(_)}V.event(`[${Te.logName}]`,"rts publish success",S),this.slsReporter.reportPublish(i,e,t,h.hasVideo&&(!u||u===M.VideoLarge),h.hasVideo&&u===M.VideoSmall,h.hasVideo&&u===M.Screen,h.hasAudio,0,S,S,v),this.slsReporter.reportConnectionLatencyEvent(ot.HANDLE_PUB_TASK,ht.START,t,S,d),this.slsReporter.reportConnectionLatencyEvent(ot.HANDLE_PUB_TASK,ht.END,t,S,Date.now());try{const _=Date.now();return this._pcTraceId=S,this.setConnected(!0),this._publishingTracks=this.rts.getPublishTrackInfoList(),l&&(yield this.publishAdd(e,l,t,{vMsid:M.VideoSmall},i),m=!1,b=M.VideoSmall),p&&(yield this.publishAdd(e,p,t,{vMsid:M.Screen},i),m=!1,b=M.Screen),yield this.waitPublishSender(e,m,b),this.slsReporter.reportPublishFirstPacket(i,t,v,_,this._localJoinTime,m?M.Audio:f.vMsid,S||"",S||"",r),{traceId:S,l1ip:o}}catch(_){throw this.setConnected(!1),O.fromError(_)}})}waitPublishSender(e,t=!1,i){return I(this,null,function*(){return Promise.race([xt(1e3),((r,n)=>{let c=0;const o=()=>(t?this.rts.getPublishAudioStats(e,i):this.rts.getPublishVideoStats(e,i)).then(d=>!(d.bytesSent>0)&&c<r?(c++,new Promise(h=>setTimeout(()=>h(o()),n))):Promise.resolve());return o()})(5,100)]).catch(()=>{})})}getPublishVideoStats(e,t){return I(this,null,function*(){return yield this.rts.getPublishVideoStats(e,t)})}getPublishAudioStats(e,t){return I(this,null,function*(){return yield this.rts.getPublishAudioStats(e,t)})}publishAdd(d,h,l,p){return I(this,arguments,function*(e,t,i,r,n=!1,c=!1,o=yt.MANUAL){var m,b,S,v,_,w,y,A;yield this.dcConnectingPromise;const u=Date.now(),f=this.getPubMsid(t,r);try{const R=yield qa(E=>I(this,null,function*(){return E>0&&V.event(`[${Te.logName}]`,`publishAdd retry times: ${E}`),this.isConnected?(yield this.dcConnectingPromise,this.rts.publishAdd([G({url:e,stream:t,updateSourceStream:!1},f)])):Promise.reject(new O(U.ERR_INNER,"rts not connected"))}),10,0,E=>(E==null?void 0:E.errorCode)===15006);if(R){const E=Date.now(),[T]=R;return this.slsReporter.reportPublish(!1,e,i,((m=f.vMsid)==null?void 0:m[0])===M.VideoLarge,((b=f.vMsid)==null?void 0:b[0])===M.VideoSmall,((S=f.vMsid)==null?void 0:S[0])===M.Screen,((v=f.aMsid)==null?void 0:v[0])===M.Audio,0,this.pcTraceId,T.traceId||"",u),this.updatePublishingTracks(T.trackInfoList),c&&(yield this.waitPublishSender(e,!t.hasVideo,t.hasVideo?r==null?void 0:r.vMsid:r==null?void 0:r.aMsid)),this.slsReporter.reportPublishFirstPacket(n,i,u,E,this._localJoinTime,(t.hasVideo?r==null?void 0:r.vMsid:r==null?void 0:r.aMsid)||"",this.pcTraceId,T.traceId||"",o),T.traceId||""}}catch(R){throw this.slsReporter.reportPublish(!1,e,i,((_=f.vMsid)==null?void 0:_[0])===M.VideoLarge,((w=f.vMsid)==null?void 0:w[0])===M.VideoSmall,((y=f.vMsid)==null?void 0:y[0])===M.Screen,((A=f.aMsid)==null?void 0:A[0])===M.Audio,(R==null?void 0:R.errorCode)||-1,this.pcTraceId,"",u),R!=null&&R.errorCode?O.fromRtsError(R):O.fromError(R)}return""})}publishDelete(e,t){return I(this,null,function*(){var d,h,l,p,u,f,m,b;yield this.dcConnectingPromise;const i=(h=(d=this.publishingTracks)==null?void 0:d.find(({msid:S})=>S===M.Audio))==null?void 0:h.msid,r=(p=(l=this.publishingTracks)==null?void 0:l.find(({msid:S})=>S===M.VideoLarge))==null?void 0:p.msid,n=(f=(u=this.publishingTracks)==null?void 0:u.find(({msid:S})=>S===M.Screen))==null?void 0:f.msid,c=[];t.screen&&n?c.push(n):t.video&&c.push(t.vMsid||r);const o=[];t.audio&&i&&o.push(i),V.event(Te.logName,"publishDelete",{streamUrl:e,aMsid:o,vMsid:c});try{const[S]=(yield this.rts.publishDeleteTracks([{url:e,aMsid:o,vMsid:c}]))||[];return V.event(Te.logName,"publishDelete",{result:S}),S&&this.updatePublishingTracks(S.trackInfoList),((b=(m=S==null?void 0:S.trackInfoList)==null?void 0:m[0])==null?void 0:b.trackId)||""}catch(S){throw O.fromRtsError(S)}})}publishReplace(e,t,i){return I(this,null,function*(){var c,o;yield this.dcConnectingPromise;const{vMsid:r,aMsid:n}=i!=null?i:{};try{const d=yield this.rts.publishReplaceTracks([{url:e,stream:t,vMsid:r,aMsid:n}]),[h]=d;return this.updatePublishingTracks(h.trackInfoList),((o=(c=h==null?void 0:h.trackInfoList)==null?void 0:c[0])==null?void 0:o.trackId)||""}catch(d){throw O.fromRtsError(d)}})}publishStop(e){return I(this,null,function*(){return yield this.rts.publishStop([{url:e}]),this._publishingTracks=[],""})}publishAddDataChannel(e){return I(this,null,function*(){yield this.dcConnectingPromise;const t=yield this.rts.publishAddDatachannel({signalUrl:e,url:Er(e,this.preferredPubL1Ip),label:M.Data,msid:M.Data}),i=t==null?void 0:t.datachannel;if(i&&i.send){const r=new ArrayBuffer(4);new DataView(r).setUint8(0,240),i.datachannel.send(r)}return i})}publishStopDataChannel(e,t){return I(this,null,function*(){return yield this.rts.publishStopDatachannel({url:e,datachannel:t})})}unpublish(){return I(this,null,function*(){yield this.rts.unpublish(),this._publishingTracks=[],this.connecting=!1,this.connected=!1})}getSubConfig(e,t){let i=t!=null?t:{};t||(i={audio:!0,video:!0,screen:!0});const r={};return i.audio&&(r.aMsid=[(e==null?void 0:e.getAudioInfo().msid)||M.Audio]),i.video?i.vMsid?r.vMsid=[i.vMsid]:r.vMsid=e!=null&&e.hasVideoLarge?[(e==null?void 0:e.getVideoLargeInfo().msid)||M.VideoLarge]:e!=null&&e.hasVideoSmall?[(e==null?void 0:e.getVideoSmallInfo().msid)||M.VideoSmall]:[M.VideoLarge]:i.screen&&(r.vMsid=[(e==null?void 0:e.getScreenInfo().msid)||M.Screen]),r}handleHTTPConfig(e){var t,i,r,n,c,o,d,h,l,p;if(this.encodedInsertableStreams&&(e.encodedInsertableStreams=!0),(i=(t=this.parameter)==null?void 0:t.net)!=null&&i.useTCP&&(e.tcpOnly=!0),(n=(r=this.parameter)==null?void 0:r.net)!=null&&n.cumuDelay&&(e.cumuDelay=!0),(o=(c=this.parameter)==null?void 0:c.net)!=null&&o.disableHeartbeat&&(e.disableHeartbeat=!0),(h=(d=this.parameter)==null?void 0:d.net)==null?void 0:h.mediaTimeout){const u=(p=(l=this.parameter)==null?void 0:l.net)==null?void 0:p.mediaTimeout;u>1e3&&u<1e5&&(e.mediaTimeout=u)}e.retryTimes=17,e.retryInterval=5e3}httpSubscribe(e){return I(this,null,function*(){var c,o;const{remoteUser:t,options:i}=e;let r=t.streamUrl;i.video||i.screen?i!=null&&i.audio||(r+="@subaudio=no"):r+="@subvideo=no";const n=this.getSubConfig(t.streamInfo,i);this.handleHTTPConfig(n),this._rtsPeerConnectionType="subscribe",(o=(c=this.parameter)==null?void 0:c.net)!=null&&o.rrtr&&(n.offerSdpHook=d=>{const h=d.replace(/(a=rtpmap:(\d+).*\r\n)/g,`$1a=rtcp-fb:$2 rrtr\r
130
130
  `);return h.includes(`a=rtcp-rsize\r
131
131
  `)?h:h.replace(/(m=(video|audio).*\r\n)/g,`$1a=rtcp-rsize\r
132
- `)});try{this.startConnect();const d=yield this.rts.subscribe(Er(r,this.preferredSubL1Ip),n);return this._pcTraceId=d.traceId,this.setConnected(!0),{traceId:d.traceId,stream:d}}catch(d){throw this.setConnected(!1),this.emit("disconnected"),O.fromRtsError(d)}})}subscribeAdd(e){return I(this,null,function*(){var n,c,o,d;const{remoteUser:t,options:i}=e,r=vt(G({url:t.streamUrl,subAudio:!!i.audio,subVideo:!(!i.screen&&!i.video)},this.getSubConfig(t.streamInfo,i)),{targetStream:i.screen?t.getScreenStream:t.getCameraStream});yield this.dcConnectingPromise;try{return(yield qa(h=>I(this,null,function*(){return yield this.dcConnectingPromise,h>0&&V.event(`[${Te.logName}]`,`subscribeAdd retry times: ${h}`),this.isConnected?this.rts.subscribeAdd([r]):Promise.reject()}),10,100,h=>{var l,p,u,f;return(h==null?void 0:h.errorCode)===15006||(h==null?void 0:h.errorCode)===15004&&((f=(u=(p=(l=h.extraInfo)==null?void 0:l.parsedData)==null?void 0:p.streams)==null?void 0:u[0])==null?void 0:f.res_code)===404}))[0]}catch(h){if(((d=(o=(c=(n=h==null?void 0:h.extraInfo)==null?void 0:n.parsedData)==null?void 0:c.streams)==null?void 0:o[0])==null?void 0:d.res_code)===508)return this.emit("subscribeexceeds"),null;throw O.fromRtsError(h)}})}subscribeDelete(e){return I(this,null,function*(){var n,c,o,d;const{remoteUser:t,options:i}=e,r=vt(G({url:t.streamUrl,subAudio:!!i.audio,subVideo:!(!i.screen&&!i.video)},this.getSubConfig(t.streamInfo,i)),{targetStream:i.screen?t.getScreenStream:t.getCameraStream});yield this.dcConnectingPromise;try{return V.event(`[${Te.logName}]`,"subscribeDeleteTracks",JSON.stringify({url:r.url,subAudio:r.subAudio,subVideo:r.subVideo,aMsid:r.aMsid,vMsid:r.vMsid})),(yield this.rts.subscribeDeleteTracks([r]))[0]}catch(h){if(((d=(o=(c=(n=h==null?void 0:h.extraInfo)==null?void 0:n.parsedData)==null?void 0:c.streams)==null?void 0:o[0])==null?void 0:d.res_code)===404)return;throw O.fromRtsError(h)}})}subscribeStop(e){return I(this,null,function*(){var t,i,r,n;try{yield this.rts.subscribeStop([{url:e}])}catch(c){if(((n=(r=(i=(t=c==null?void 0:c.extraInfo)==null?void 0:t.parsedData)==null?void 0:i.streams)==null?void 0:r[0])==null?void 0:n.res_code)===404)return;throw O.fromRtsError(c)}})}subscribeAddDataChannel(e){return I(this,null,function*(){yield this.dcConnectingPromise;const t=yield this.rts.subscribeAddDatachannel({signalUrl:e,url:e,label:M.Data,msid:M.Data}),i=t==null?void 0:t.datachannel;if(i&&i.send){const r=new ArrayBuffer(4);new DataView(r).setUint8(0,240),i.send(r)}return i})}subscribeStopDatachannel(e,t){return I(this,null,function*(){let i;try{i=yield this.rts.subscribeStopDatachannel({url:e,datachannel:t})}catch(r){}return t==null||t.dispose(),i})}publish(n,c){return I(this,arguments,function*(e,t,i=!1,r=yt.MANUAL){let o,d="";if(this.connecting&&(yield this.connectingPromise),this.connected){yield this.dcConnectingPromise;let h,l=!1;const{audio:p,video:u,videoSmall:f,screen:m}=this.localStreamManager.publishStreams;p&&(d=yield this.publishAdd(e,p,t,{aMsid:M.Audio},i),l=!0,h=M.Audio,yield xt(100)),u&&(d=yield this.publishAdd(e,u,t,{vMsid:M.VideoLarge},i),l=!1,h=M.VideoLarge,yield xt(100)),f&&(d=yield this.publishAdd(e,f,t,{vMsid:M.VideoSmall},i),l=!1,h=M.VideoSmall,yield xt(100)),m&&(d=yield this.publishAdd(e,m,t,{isScreen:!0,vMsid:M.Screen},i),l=!1,h=M.Screen),h&&(yield this.waitPublishSender(e,l,h))}else{const h=yield this.httpPublish(e,t,i,r);d=h.traceId,o=h.l1ip}return{traceId:d,l1ip:o}})}reportSubscribeLatency(e,t,i,r){const n=[];e.audio&&n.push(e.aMsid||M.Audio),e.video?n.push(e.vMsid||M.VideoLarge):e.screen&&n.push(M.Screen),n.forEach(c=>{this.slsReporter.reportConnectionLatencyEvent(ot.HANDLE_SUB_TASK,ht.START,t,c,i,0,r),this.slsReporter.reportConnectionLatencyEvent(ot.HANDLE_SUB_TASK,ht.END,t,c,Date.now(),0,r)})}subscribe(e,t,i,r,n){return I(this,null,function*(){let c=!1;const{options:o,remoteUser:d}=e;if(o.video&&o.screen)throw new O(U.ERR_INNER,"subscribe error, video and screen cannot be subscribed at the same time");let h;this.connecting&&(yield this.connectingPromise);let l=Date.now();this.connected?h=yield this.subscribeAdd(e):(c=!0,h=yield this.httpSubscribe(e)),this.reportSubscribeLatency(o,i,l,c);const p=Date.now();let u=M.VideoLarge,f=o.video||o.screen,m=o.audio;o.video&&o.vMsid?u=o.vMsid:o.screen&&(u=M.Screen);let b=0,S=0,v=0;const _=((w,y)=>{let A=0;const R=()=>{let E;return m&&!b&&(E=this.rts.getSubscribeAudioStats(d.streamUrl).then(T=>{if(T.packetsReceived>0)b=Date.now(),V.debug(`[${Te.logName}]`,d.userId,"Stats 音频首包");else if(!f)return A<w&&(A++,new Promise(k=>setTimeout(()=>k(R()),y)));return!0})),f&&!v&&(E=this.rts.getSubscribeVideoStats(d.streamUrl,u).then(T=>(!S&&T.packetsReceived>0&&(S=Date.now(),V.debug(`[${Te.logName}]`,d.userId,"Stats 视频首包")),T.framesDecoded>0?(v=Date.now(),V.debug(`[${Te.logName}]`,d.userId,"Stats 视频首帧数据"),!0):A<w?(A++,new Promise(k=>setTimeout(()=>k(R()),y))):(V.event(`[${Te.logName}]`,d.userId,"尝试获取首帧数据失败"),!1)))),Promise.resolve(E)};return R()})(20,100);return _.then(()=>{S&&this.slsReporter.reportSubscribeFirstPacket(t===be.Resume,i,r,u,{fprt:S-l,ifsprtc:v?v-l:0,ajsub:t===be.Join?1:0,pctid:this.pcTraceId,subtid:(h==null?void 0:h.traceId)||"",sstc:p-l}),v&&this.slsReporter.reportSubscribeFirstFrame(t===be.Resume,i,r,u,{fvfrt:v-l,fp2fftc:v-S,ajsub:t===be.Join?1:0,tffrtc:t===be.Join?v-this.localJoinTime:v-n,pctid:this.pcTraceId,subtid:(h==null?void 0:h.traceId)||"",fvfdtc:v-l}),b&&(this.slsReporter.reportConnectionLatencyEvent(ot.FIRST_REMOTE,ht.DECODED,i,M.Audio,b),this.slsReporter.reportSubscribeFirstPacket(t===be.Resume,i,r,M.Audio,{fprt:b-l,ifsprtc:b-l,ajsub:t===be.Join?1:0,pctid:this.pcTraceId,subtid:(h==null?void 0:h.traceId)||"",sstc:p-l}))}),h.isHTTP=c,h.statsCheckPromise=_,h})}getSubscribeVideoStats(e,t){return I(this,null,function*(){return yield this.rts.getSubscribeVideoStats(e,t)})}getSubscribeAudioStats(e,t){return I(this,null,function*(){return yield this.rts.getSubscribeAudioStats(e,t)})}getStreamByMsid(e){return this.rts.commonController.streamManager.getStreamByMsid(e)}getDatachannelByMsid(e){return this.rts.commonController.streamManager.getDatachannelByMsid(e)}getPCStats(){return I(this,null,function*(){var e,t;return(t=(e=this.rts.commonController.peerCore)==null?void 0:e.pc)==null?void 0:t.getStats()})}sendSEI(e,t,i,r){return I(this,null,function*(){return this.rts.sendSEI({url:e,vMsid:M.VideoLarge,data:t,repeatCount:i,payloadType:r})})}},g(Te,"logName","RtsManager"),Te);Be([C(H)],xe.prototype,"startConnect",1),Be([C()],xe.prototype,"updatePublishingTracks",1),Be([C(H,H)],xe.prototype,"httpPublish",1),Be([C(H,H)],xe.prototype,"waitPublishSender",1),Be([C(([s,a,e])=>[s,JSON.stringify(e)],H)],xe.prototype,"publishAdd",1),Be([C(H,H)],xe.prototype,"publishDelete",1),Be([C(([s,a,e])=>[s,JSON.stringify(e)])],xe.prototype,"publishReplace",1),Be([C(H)],xe.prototype,"publishStop",1),Be([C(H)],xe.prototype,"publishAddDataChannel",1),Be([C(H)],xe.prototype,"publishStopDataChannel",1),Be([C()],xe.prototype,"unpublish",1),Be([C(zi,({traceId:s})=>s)],xe.prototype,"httpSubscribe",1),Be([C(zi,({traceId:s})=>s)],xe.prototype,"subscribeAdd",1),Be([C(zi)],xe.prototype,"subscribeDelete",1),Be([C(H)],xe.prototype,"subscribeStop",1),Be([C(H)],xe.prototype,"subscribeAddDataChannel",1),Be([C(H)],xe.prototype,"subscribeStopDatachannel",1),Be([C(H)],xe.prototype,"publish",1),Be([C(zi)],xe.prototype,"subscribe",1),Be([C()],xe.prototype,"sendSEI",1);let Yo=xe;class Cr{constructor(a=_r){g(this,"defaultProfile");g(this,"profile");g(this,"profileMap",new Map);g(this,"audioProfile");g(this,"contentHint");this.defaultProfile=G({},a)}updateProfile(a,e){this.profileMap.set(a,G(G(G({},this.defaultProfile),this.profileMap.get(a)||{}),e||{})),this.profile=a}get videoProfile(){return this.profile}updateAudioProfile(a){this.audioProfile=a}setContentHint(a,e){e&&(this.contentHint=e),this.contentHint&&a&&(a.contentHint=this.contentHint)}setVideoProfile(a,e,t=!1){return I(this,null,function*(){if(!this.profile)return;const i=this.profileMap.get(this.profile)||(e==null?void 0:e.VideoProfileMap.get(this.profile));if(i){if(!t&&a&&a.readyState==="live"&&a.applyConstraints)try{yield a.applyConstraints(i)}catch(r){}if(e){const r=G({},i);i.maxSendFrameRate&&(r.frameRate=i.maxSendFrameRate),e==null||e.VideoProfileMap.set(this.profile,r),yield e.setVideoProfile(this.profile)}}})}}var Ve=(s=>(s[s.AliRtcSdkStreamTypeCapture=0]="AliRtcSdkStreamTypeCapture",s[s.AliRtcSdkStreamTypeScreen=1]="AliRtcSdkStreamTypeScreen",s))(Ve||{});class kr extends se{constructor(e){super();g(this,"type");g(this,"originVideoTrack");g(this,"videoSource");g(this,"_videoMuted",!1);g(this,"originAudioTrack");g(this,"audioSource");g(this,"_audioMuted",!1);g(this,"_targetVideoTrack");g(this,"_targetDualVideoTrack");g(this,"_targetAudioTrack");g(this,"_publishVideoStream");g(this,"_publishDualVideoStream");g(this,"_publishAudioStream");g(this,"_previewStream");g(this,"plugins",[]);g(this,"_profileManager");g(this,"cameraVideoConstraints");g(this,"micAudioConstraints");g(this,"onVideoTrackEnded",()=>{this.emit("videotrackended")});g(this,"onAudioTrackEnded",()=>{this.emit("audiotrackended")});this.type=e}get profileManager(){return this._profileManager}get audioProfile(){var e;return(e=this.profileManager)==null?void 0:e.audioProfile}updateSource(e,t,i){return I(this,null,function*(){var c,o,d,h,l,p;const{videoTrack:r,audioTrack:n}=e;r&&((c=this.originVideoTrack)==null||c.removeEventListener("ended",this.onVideoTrackEnded)),n&&((o=this.originAudioTrack)==null||o.removeEventListener("ended",this.onAudioTrackEnded)),this.type===Ve.AliRtcSdkStreamTypeScreen?this.stop():(r&&((d=this.originVideoTrack)==null||d.stop()),n&&((h=this.originAudioTrack)==null||h.stop())),r&&(this.originVideoTrack=r,(l=this.originVideoTrack)==null||l.addEventListener("ended",this.onVideoTrackEnded),this.videoSource=t||li.Camera,this.updateVideoTrack(r)),n&&(this.originAudioTrack=n,(p=this.originAudioTrack)==null||p.addEventListener("ended",this.onAudioTrackEnded),this.audioSource=i||Oi.Microphone,this.updateAudioTrack(n))})}get currentProfile(){var e;return(e=this.profileManager)==null?void 0:e.profile}get currentVideoTrack(){return this._targetVideoTrack}get currentDualVideoTrack(){return this._targetDualVideoTrack}get publishVideoStream(){return this._publishVideoStream}get publishDualVideoStream(){return this._publishDualVideoStream}get currentAudioTrack(){return this._targetAudioTrack}get publishAudioStream(){return this._publishAudioStream}get previewStream(){return this._previewStream}updateVideoTrack(e,t=!1){return I(this,null,function*(){(this._targetVideoTrack!==e||t)&&(this._targetVideoTrack=e)})}updateDualVideoTrack(e,t=!1){return I(this,null,function*(){(this._targetDualVideoTrack!==e||t)&&(this._targetDualVideoTrack=e)})}updateAudioTrack(e,t=!1){return I(this,null,function*(){(this._targetAudioTrack!==e||t)&&(this._targetAudioTrack=e)})}setAudioMuted(e){var t,i;this._audioMuted=e,e?(t=this.publishAudioStream)==null||t.disableAudio():(i=this.publishAudioStream)==null||i.enableAudio()}get isAudioMuted(){return this._audioMuted}setVideoMuted(e){var t,i;this._videoMuted=e,e?(t=this.publishVideoStream)==null||t.disableVideo():(i=this.publishVideoStream)==null||i.enableVideo()}get isVideoMuted(){return this._videoMuted}process(e){return I(this,null,function*(){var t,i,r,n,c,o,d,h,l,p,u,f;this._targetAudioTrack=this.originAudioTrack,this._targetVideoTrack=this.originVideoTrack;for(const m of this.plugins)try{yield m.execute(this,e)}catch(b){console.error(`error in plugin-${m.name}, error: ${b}`)}this._targetVideoTrack?((i=(t=this._publishVideoStream)==null?void 0:t.videoTrack)==null?void 0:i.id)!==this._targetVideoTrack.id&&(this._publishVideoStream=yield fi(this._targetVideoTrack),this.setVideoMuted(this._videoMuted),(r=this.profileManager)==null||r.setVideoProfile(this.originVideoTrack,this._publishVideoStream,!0),(n=this.profileManager)==null||n.setContentHint(this._targetVideoTrack),this.previewStream?(c=this.previewStream)==null||c.mergeStream(this._publishVideoStream):this._previewStream=yield fi(this._targetVideoTrack)):(this._publishVideoStream=void 0,(o=this.previewStream)==null||o.deleteTracks({video:!0})),this._targetDualVideoTrack?((h=(d=this._publishDualVideoStream)==null?void 0:d.videoTrack)==null?void 0:h.id)!==this._targetDualVideoTrack.id&&(this._publishDualVideoStream=yield fi(this._targetDualVideoTrack),this._videoMuted?this._publishDualVideoStream.disableVideo():this._publishDualVideoStream.enableVideo()):this._publishDualVideoStream=void 0,this._targetAudioTrack?((p=(l=this._publishAudioStream)==null?void 0:l.audioTrack)==null?void 0:p.id)!==this._targetAudioTrack.id&&(this._publishAudioStream=yield fi(this._targetAudioTrack),this.setAudioMuted(this._audioMuted),this.previewStream?(u=this.previewStream)==null||u.mergeStream(this._publishAudioStream):this._previewStream=yield fi(this._targetAudioTrack)):(this._publishAudioStream=void 0,(f=this.previewStream)==null||f.deleteTracks({audio:!0}))})}stopVideo(){var e,t;this.originVideoTrack&&((e=this.originVideoTrack)==null||e.removeEventListener("ended",this.onAudioTrackEnded),(t=this.originVideoTrack)==null||t.stop(),this.originVideoTrack=void 0),this.updateVideoTrack(void 0)}stopAudio(){var e,t;this.originAudioTrack&&((e=this.originAudioTrack)==null||e.removeEventListener("ended",this.onAudioTrackEnded),(t=this.originAudioTrack)==null||t.stop(),this.originAudioTrack=void 0),this.updateAudioTrack(void 0)}stop(){this.stopVideo(),this.stopAudio()}updateVideoProfile(e,t,i=!1){return I(this,null,function*(){this._profileManager||(this._profileManager=new Cr(this.type===Ve.AliRtcSdkStreamTypeScreen?Ja:_r)),e&&this._profileManager.updateProfile(e,t),yield this._profileManager.setVideoProfile(this.originVideoTrack,this._publishVideoStream,i)})}get videoProfile(){var e;return(e=this.profileManager)==null?void 0:e.videoProfile}setVideoContentHint(e){this._profileManager||(this._profileManager=new Cr(this.type===Ve.AliRtcSdkStreamTypeScreen?Ja:_r)),this._profileManager.setContentHint(this.currentVideoTrack,e)}updateAudioProfile(e){return I(this,null,function*(){this._profileManager||(this._profileManager=new Cr),this._profileManager.updateAudioProfile(e)})}cloneVideoProfile(e){return I(this,null,function*(){var t;yield(t=this.profileManager)==null?void 0:t.setVideoProfile(void 0,e)})}addPlugin(e){const t=this.plugins.findIndex(i=>i.zIndex>e.zIndex);t>-1?this.plugins.splice(t,0,e):this.plugins.push(e)}removePlugin(e){const t=this.plugins.indexOf(e);return t>-1&&(e.clear(this),this.plugins.splice(t,1),!0)}}var Qo=Object.defineProperty,Zo=Object.getOwnPropertyDescriptor,ft=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?Zo(a,e):a,n=s.length-1;n>=0;n--)(i=s[n])&&(r=(t?i(a,e,r):i(r))||r);return t&&r&&Qo(a,e,r),r};const ut=(Bt=class extends se{constructor(e,t){super();g(this,"pluginManager");g(this,"slsReporter");g(this,"publishingCameraVideoStream");g(this,"publishingScreenVideoStream");g(this,"cameraStreamInfo",new kr(Ve.AliRtcSdkStreamTypeCapture));g(this,"screenStreamInfo",new kr(Ve.AliRtcSdkStreamTypeScreen));g(this,"streamInfos",[this.cameraStreamInfo,this.screenStreamInfo]);g(this,"_audioCaptureDisabled",!1);g(this,"_cameraCaptureDisabled",!1);g(this,"_publishLocalAudioStreamEnabled",!0);g(this,"_publishLocalVideoStreamEnabled",!0);g(this,"_publishLocalScreenStreamEnabled",!0);this.screenStreamInfo.setVideoContentHint("motion"),this.pluginManager=e,this.slsReporter=t,this.cameraStreamInfo.on("videotrackended",()=>I(this,null,function*(){yield this.stopLocalStream({video:!0}),this.emit("trackended",Gt.VideoTrackEnded)})),this.cameraStreamInfo.on("audiotrackended",()=>I(this,null,function*(){yield this.stopLocalStream({audio:!0}),this.emit("trackended",Gt.AudioTrackEnded)})),this.screenStreamInfo.on("videotrackended",()=>I(this,null,function*(){yield this.stopLocalStream({screen:!0}),this.emit("trackended",Gt.ScreenTrackEnded)})),this.pluginManager.on("added",i=>I(this,null,function*(){if(V.info(`[${Bt.logName}]`,"plugin added",i.name),!i.isSupported("7.1.7"))return console.warn(`${i.name} is not supported!!!`),void i.emit("unsupported");try{yield i.init()}catch(r){i.emit("error",O.fromError(r,Ot.AliRtcPluginErrorInitError))}i.streamType===Ve.AliRtcSdkStreamTypeCapture&&(this.cameraStreamInfo.addPlugin(i),yield this.cameraStreamInfo.process(this.streamInfos)),i.streamType===Ve.AliRtcSdkStreamTypeScreen&&(this.screenStreamInfo.addPlugin(i),yield this.screenStreamInfo.process(this.streamInfos)),this.emit("publishupdate")})),this.pluginManager.on("removed",i=>I(this,null,function*(){this.cameraStreamInfo.removePlugin(i)&&(yield this.cameraStreamInfo.process(this.streamInfos)),this.screenStreamInfo.removePlugin(i)&&(yield this.screenStreamInfo.process(this.streamInfos)),this.emit("publishupdate")})),this.pluginManager.on("updated",()=>I(this,null,function*(){yield this.updateStreams()}))}get hasCamera(){return!!this.cameraStreamInfo.originVideoTrack}get audioCaptureDisabled(){return this._audioCaptureDisabled}set audioCaptureDisabled(e){this._audioCaptureDisabled=e}get cameraCaptureDisabled(){return this._cameraCaptureDisabled}set cameraCaptureDisabled(e){this._cameraCaptureDisabled=e}setAudioMuted(e){this.cameraStreamInfo.setAudioMuted(e)}get isAudioMuted(){return this.cameraStreamInfo.isAudioMuted}setCameraMuted(e){this.cameraStreamInfo.setVideoMuted(e)}get isCameraMuted(){return this.cameraStreamInfo.isVideoMuted}setScreenMuted(e){this.screenStreamInfo.setVideoMuted(e)}get isScreenMuted(){return this.screenStreamInfo.isVideoMuted}get publishLocalAudioStreamEnabled(){return this._publishLocalAudioStreamEnabled}set publishLocalAudioStreamEnabled(e){this._publishLocalAudioStreamEnabled=e}get publishLocalVideoStreamEnabled(){return this._publishLocalVideoStreamEnabled}set publishLocalVideoStreamEnabled(e){this._publishLocalVideoStreamEnabled=e}get publishLocalScreenStreamEnabled(){return this._publishLocalScreenStreamEnabled}set publishLocalScreenStreamEnabled(e){this._publishLocalScreenStreamEnabled=e}updateStreams(){return I(this,null,function*(){yield this.cameraStreamInfo.process(this.streamInfos),yield this.screenStreamInfo.process(this.streamInfos),this.emit("publishupdate")})}setAvailableCameraDeviceId(){return I(this,null,function*(){var e,t,i,r;if((e=this.cameraStreamInfo.cameraVideoConstraints)!=null&&e.deviceId){let n=(t=this.cameraStreamInfo.cameraVideoConstraints)==null?void 0:t.deviceId;const c=yield X.AliRTS.getCameraList();c.find(o=>o.deviceId===n)||(n=(r=(i=c.find(o=>!!o.deviceId))==null?void 0:i.deviceId)!=null?r:""),this.cameraStreamInfo.cameraVideoConstraints.deviceId=n}})}setAvailableMicrophoneDeviceId(){return I(this,null,function*(){var e,t,i,r;if((e=this.cameraStreamInfo.micAudioConstraints)!=null&&e.deviceId){let n=(t=this.cameraStreamInfo.micAudioConstraints)==null?void 0:t.deviceId;const c=yield X.AliRTS.getMicList();c.find(o=>o.deviceId===n)||(n=(r=(i=c.find(o=>!!o.deviceId))==null?void 0:i.deviceId)!=null?r:""),this.cameraStreamInfo.micAudioConstraints.deviceId=n}})}createLocalStream(e){return I(this,null,function*(){var l;const{screen:t,mediaStream:i,videoProfile:r,screenProfile:n}=e;let{video:c,audio:o}=e;const d=(p=>{const{audio:u,video:f,screen:m}=p;if(f&&m)throw new O(U.ERR_INNER,"create stream error, cannot create video && screen together");return!!(f||u||m)})(e);let h;if(d){i||(c===!0&&this.cameraStreamInfo.cameraVideoConstraints?(yield this.setAvailableCameraDeviceId(),c=G({},this.cameraStreamInfo.cameraVideoConstraints)):typeof c=="object"&&(yield this.setAvailableCameraDeviceId(),c=G(G({},c),this.cameraStreamInfo.cameraVideoConstraints)),o===void 0&&this.audioCaptureDisabled?o=!1:o&&(o===!0&&this.cameraStreamInfo.micAudioConstraints?(yield this.setAvailableMicrophoneDeviceId(),o=G({},this.cameraStreamInfo.micAudioConstraints)):typeof o=="object"&&(yield this.setAvailableMicrophoneDeviceId(),o=G(G({},o),this.cameraStreamInfo.micAudioConstraints)),this._audioCaptureDisabled=!1));const p=Date.now();try{h=yield X.AliRTS.createStream({audio:o,video:c,screen:t,custom:!!i,mediaStream:i,skipProfile:!0}),V.info(`[${Bt.logName}]`,"createLocalStream",{audio:o,video:c,screen:t,custom:!!i,time:Date.now()-p}),o&&!i&&this.slsReporter.reportAudio(null,Date.now()-p,((l=h==null?void 0:h.audioTrack)==null?void 0:l.label)||""),t&&!i&&this.slsReporter.reportScreen(null,Date.now()-p)}catch(u){throw o&&!i&&this.slsReporter.reportAudio(u,Date.now()-p,""),t&&!i&&this.slsReporter.reportScreen(null,Date.now()-p),u}if(t)yield this.screenStreamInfo.updateSource(h,li.Screen,Oi.Screen),yield this.setScreenProfile(n||Ka),this.setScreenContentHint(),this.publishingScreenVideoStream=void 0;else if(yield this.cameraStreamInfo.updateSource(h,li.Camera,Oi.Microphone),h.hasVideo&&(yield this.setVideoProfile(r||$a),this.setVideoContentHint(),this.publishingCameraVideoStream=void 0),h.hasAudio&&typeof o=="boolean"){const u=this.cameraStreamInfo.audioProfile;u&&(yield h.setAudioProfile(u))}}return X.AliRTS.SystenUtil.isIos&&X.AliRTS.SystenUtil.compareVersion("15.1")&&!X.AliRTS.SystenUtil.compareVersion("15.2")&&(yield xt(1e3)),yield this.updateStreams(),h})}stopLocalStream(e){return I(this,null,function*(){const{screen:t,video:i,audio:r}=e!=null?e:{};let n=!1;i&&this.cameraStreamInfo.originVideoTrack&&(n=!0,this.cameraStreamInfo.stopVideo(),this.publishingCameraVideoStream=void 0),r&&this.cameraStreamInfo.originAudioTrack&&(n=!0,this.cameraStreamInfo.stopAudio()),t&&this.screenStreamInfo.originVideoTrack&&(n=!0,this.screenStreamInfo.stop(),this.publishingScreenVideoStream=void 0,this.slsReporter.reportScreenStop(null)),n&&(yield this.updateStreams())})}get publishStreams(){const{publishLocalVideoStreamEnabled:e,publishLocalAudioStreamEnabled:t,publishLocalScreenStreamEnabled:i}=this;return{video:e?this.cameraStreamInfo.publishVideoStream:void 0,videoSmall:e?this.cameraStreamInfo.publishDualVideoStream:void 0,audio:t?this.cameraStreamInfo.publishAudioStream:void 0,screen:i?this.screenStreamInfo.publishVideoStream:void 0}}createHTTPPublishStream(){return I(this,null,function*(){var o,d,h,l;let e,t,i,r,n=!1;const c=this.publishStreams;try{if(!(c.audio||c.video||c.videoSmall||c.screen))throw V.error(`[${Bt.logName}]`,"no tracks founded"),new O(U.ERR_SDK_PUBLISH_INVAILD,"no tracks founded");const p=new MediaStream;(o=c.audio)!=null&&o.audioTrack&&p.addTrack(c.audio.audioTrack),(d=c.video)!=null&&d.videoTrack?(p.addTrack(c.video.videoTrack),i=c.videoSmall,r=c.screen):(h=c.screen)!=null&&h.videoTrack&&(t=M.Screen,p.addTrack((l=c.screen)==null?void 0:l.videoTrack),n=!0),e=yield Qa(p),n?(this.screenStreamInfo.cloneVideoProfile(e),this.publishingScreenVideoStream=e):(this.cameraStreamInfo.cloneVideoProfile(e),this.publishingCameraVideoStream=e)}catch(p){}return{publishStream:e,videoSmallStream:i,screenStream:r,vMsid:t}})}stop(){this.cameraStreamInfo.stop(),this.screenStreamInfo.stop(),this.updateStreams()}setVideoProfile(e,t,i=!1){return I(this,null,function*(){yield this.cameraStreamInfo.updateVideoProfile(e,t,i),this.publishingCameraVideoStream&&this.cameraStreamInfo.cloneVideoProfile(this.publishingCameraVideoStream)})}setVideoContentHint(e){this.cameraStreamInfo.setVideoContentHint(e)}setAudioProfile(e){return I(this,null,function*(){var t;yield this.cameraStreamInfo.updateAudioProfile(e),yield(t=this.publishingCameraVideoStream)==null?void 0:t.setAudioProfile(e)})}setScreenProfile(e,t){return I(this,null,function*(){yield this.screenStreamInfo.updateVideoProfile(e,t),this.publishingScreenVideoStream&&this.screenStreamInfo.cloneVideoProfile(this.publishingScreenVideoStream)})}setScreenContentHint(e){this.screenStreamInfo.setVideoContentHint(e)}setCameraVideoConstraints(e){var t;this.cameraStreamInfo.cameraVideoConstraints=G(G({},(t=this.cameraStreamInfo.cameraVideoConstraints)!=null?t:{}),e)}setMicAudioConstraints(e){var t;this.cameraStreamInfo.micAudioConstraints=G(G({},(t=this.cameraStreamInfo.micAudioConstraints)!=null?t:{}),e)}},g(Bt,"logName","LocalStreamManager"),Bt);ft([C(([s])=>{const{audio:a,video:e,screen:t,custom:i,skipProfile:r,videoProfile:n,screenProfile:c}=s;return[{audio:a,video:e,screen:t,custom:i,skipProfile:r,videoProfile:n,screenProfile:c}]})],ut.prototype,"createLocalStream",1),ft([C(H)],ut.prototype,"stopLocalStream",1),ft([C()],ut.prototype,"createHTTPPublishStream",1),ft([C()],ut.prototype,"stop",1),ft([C(H)],ut.prototype,"setVideoProfile",1),ft([C(H)],ut.prototype,"setVideoContentHint",1),ft([C(H)],ut.prototype,"setAudioProfile",1),ft([C(H)],ut.prototype,"setScreenProfile",1),ft([C(H)],ut.prototype,"setScreenContentHint",1),ft([C(H)],ut.prototype,"setCameraVideoConstraints",1),ft([C(H)],ut.prototype,"setMicAudioConstraints",1);let ec=ut;const tc=s=>I(this,null,function*(){const a=new X.AliRTS.SupportUtil;window.isSecureContext||console.warn("WebRTC 需要 HTTPS 安全上下文,细节可参考:https://developer.mozilla.org/zh-CN/docs/Web/Security/Secure_Contexts");let e={support:!1,detail:{isWebRTCSupported:a.checkMediaDevices()&&a.checkWebRtcSupport(),isH264DecodeSupported:!1,isH264EncodeSupported:!1,isScreenShareSupported:!1,isSendMediaExtensionMsgSupported:!1,isBrowserSupported:!0}},t=!1;try{e.detail.isWebRTCSupported?(yield a.isSupport({isReceiveVideo:!0}),t=!0):console.warn("当前浏览器不支持 WebRTC")}catch(i){t=!1,e.detail.isBrowserSupported=a.checkBrowser({errorCode:0,message:""})}if(e.support=t,a.checkWebRtcSupport()&&s!=="sendonly"){const i=yield a.checkH264Decode();e.detail.isH264DecodeSupported=i,e.support=e.support&&i}if(a.checkWebRtcSupport()&&s!=="recvonly"){const i=yield a.checkH264Encode();e.detail.isH264EncodeSupported=i,e.support=e.support&&i}return e.detail.isScreenShareSupported=a.checkWebRtcSupport()&&a.checkScreenCapture()&&!X.AliRTS.SystenUtil.isAndroid&&!X.AliRTS.SystenUtil.isIos,e.detail.isSendMediaExtensionMsgSupported=a.checkWebRtcSupport()&&a.checkEncodedTransformSupport(),e});var en=(s=>(s[s.PRE_PROCESSOR=0]="PRE_PROCESSOR",s[s.POST_PROCESSOR=1]="POST_PROCESSOR",s))(en||{}),ni=(s=>(s[s.AUDIO=0]="AUDIO",s[s.VIDEO=1]="VIDEO",s[s.BOTH=2]="BOTH",s))(ni||{});class Dt extends se{constructor(e,t=Ve.AliRtcSdkStreamTypeCapture,i=1){super();g(this,"name");g(this,"options");g(this,"type",0);g(this,"streamType");g(this,"trackType");g(this,"zIndex",1);g(this,"_isEnable",!0);g(this,"shouldCache",!0);g(this,"lastInputAudioTrack");g(this,"lastOutputAudioTrack");g(this,"lastInputVideoTrack");g(this,"lastOutputVideoTrack");g(this,"_hasCleared",!0);this.name=e,this.streamType=t,this.trackType=i,this.options=this.initOptions}get initOptions(){return{}}getOptions(){return this.options}init(){return I(this,null,function*(){})}enable(){this._isEnable||(this._isEnable=!0,this.init(),this.emit("enabled"))}disable(){this._isEnable&&(this._isEnable=!1,this.clear(),this.emit("disabled"))}get isEnable(){return this._isEnable}audioUpdated(e){var t,i;return((t=this.lastInputAudioTrack)==null?void 0:t.id)!==((i=e.currentAudioTrack)==null?void 0:i.id)}videoUpdated(e){var t,i;return((t=this.lastInputVideoTrack)==null?void 0:t.id)!==((i=e.currentVideoTrack)==null?void 0:i.id)}execute(e,t){return I(this,null,function*(){const i=this.shouldUpdate(e,t);this.lastInputAudioTrack=e.currentAudioTrack,this.lastInputVideoTrack=e.currentVideoTrack,this._hasCleared||i?(yield this.process(e,t),this._hasCleared=!1):this.shouldCache&&(!this.lastOutputAudioTrack||this.trackType!==2&&this.trackType!==0||this.lastOutputAudioTrack&&e.updateAudioTrack(this.lastOutputAudioTrack),!this.lastOutputVideoTrack||this.trackType!==2&&this.trackType!==1||this.lastOutputVideoTrack&&e.updateVideoTrack(this.lastOutputVideoTrack)),this.lastOutputAudioTrack=e.currentAudioTrack,this.lastOutputVideoTrack=e.currentVideoTrack})}clear(e){this._hasCleared=!0,this.lastInputAudioTrack=void 0,this.lastInputVideoTrack=void 0,this.lastOutputAudioTrack=void 0,this.lastOutputVideoTrack=void 0}}class ic extends Dt{constructor(){super("AliRtcScreenStandardize",Ve.AliRtcSdkStreamTypeScreen);g(this,"canvas");g(this,"lastWidth");g(this,"lastHeight");g(this,"isProcessingScreenTrack",!1);this.shouldCache=!1}get initOptions(){return{base:4}}setOptions(e){this.options=e}isSupported(){return!(typeof TransformStream=="undefined"||typeof MediaStreamTrackProcessor=="undefined"||typeof MediaStreamTrackGenerator=="undefined")}updateProcessCanvas(e,t){if(this.canvas&&this.lastWidth===e&&this.lastHeight===t)return;const i=Math.ceil(e/this.options.base)*this.options.base,r=Math.ceil(t/this.options.base)*this.options.base;if(this.canvas||(this.canvas=document.createElement("canvas")),this.canvas.width=i,this.canvas.height=r,this.lastWidth&&e>this.lastWidth||this.lastHeight&&t>this.lastHeight){const n=this.canvas.getContext("2d");n&&n.clearRect(0,0,i,r)}this.lastWidth=e,this.lastHeight=t}shouldProcess(e){var i;let t=!1;if(e.originVideoTrack&&e.videoSource===li.Screen){const r=(i=e.originVideoTrack)==null?void 0:i.getSettings();if(r){const{width:n,height:c}=r;t=!n||!c||!(n%this.options.base===0&&c%this.options.base===0)}}return t}shouldUpdate(e){return this.shouldProcess(e)!==this.isProcessingScreenTrack}handleFrame(e){return I(this,null,function*(){var n;const{displayWidth:t,displayHeight:i}=e;if(!t||!i||t%this.options.base===0&&i%this.options.base===0)return e;this.updateProcessCanvas(t,i);const r=(n=this.canvas)==null?void 0:n.getContext("2d");if(this.canvas&&r){r.drawImage(e,0,0,t,i);const c=new VideoFrame(this.canvas,{timestamp:e.timestamp});return e.close(),c}return e})}process(e){return I(this,null,function*(){var h;if(!this.shouldProcess(e))return this.clear(e),void(this.isProcessingScreenTrack=!1);if(e.originVideoTrack){const l=e.originVideoTrack.getSettings();if(l){const{width:p,height:u}=l;if(!(!p||!u||!(p%this.options.base===0&&u%this.options.base===0)))return void this.clear(e)}}const t=new MediaStreamTrackProcessor({track:e.originVideoTrack}),i=new MediaStreamTrackGenerator({kind:"video"}),r=new MediaStream([i]),n=this,c=new TransformStream({transform(l,p){return I(this,null,function*(){const u=yield n.handleFrame(l);yield p.enqueue(u),u==null||u.close()})}});t.readable.pipeThrough(c).pipeTo(i.writable);const o=(h=r.getVideoTracks())==null?void 0:h[0];e.updateVideoTrack(o),this.isProcessingScreenTrack=!0})}clear(e){this.canvas=void 0,this.lastWidth=void 0,this.lastHeight=void 0,super.clear(e)}}class rc extends Dt{constructor(){super("blankAudio",Ve.AliRtcSdkStreamTypeCapture,ni.BOTH);g(this,"hasTrack",!1);g(this,"oscillator",null);g(this,"audioTrack",null);g(this,"createAudioTrack",()=>{const e=new AudioContext;this.oscillator=e.createOscillator();const t=e.createGain();t.gain.value=0;const i=e.createMediaStreamDestination();this.oscillator.connect(t),t.connect(i),this.oscillator.start();const r=i.stream;return this.audioTrack=r.getAudioTracks()[0],this.audioTrack});this.zIndex=9}isSupported(){return!0}setOptions(){throw new Error("Method not implemented.")}shouldUpdate(e,t){return this.hasTrack!==t.some(i=>i.originVideoTrack||i.originAudioTrack)}process(e,t){return I(this,null,function*(){var r;const i=t.some(n=>n.originVideoTrack||n.originAudioTrack);this.hasTrack=i,i?this.audioTrack&&((r=this.oscillator)==null||r.stop(),this.oscillator=null,this.audioTrack.stop(),this.audioTrack=null):(this.audioTrack||(this.audioTrack=this.createAudioTrack()),e.updateAudioTrack(this.audioTrack))})}}class tn{constructor(a){g(this,"name","COMMON");this.name=a||this.name}info(...a){}warn(...a){}print(a,...e){const t=a.toLowerCase();t&&console[t](`[${a}][${this.name}]`,...e)}}g(tn,"LEVEL",0);class sc{constructor(){g(this,"logger",new tn("AudioMixer"));g(this,"audioContext",new AudioContext);g(this,"audioDestination",this.audioContext.createMediaStreamDestination());g(this,"audioTrack",(a=>a.getAudioTracks()[0])(this.audioDestination.stream));g(this,"sourceNodeMap",{})}get sourceNodeList(){return Object.values(this.sourceNodeMap).map(a=>a.sourceNode).filter(a=>!!a)}get gainNodeList(){return Object.values(this.sourceNodeMap).map(a=>a.gainNode).filter(a=>!!a)}get sourceCount(){return this.sourceNodeList.length}resume(){var a;return(a=this.audioContext)==null?void 0:a.resume()}addTrack(a){this.connectTrack(a)}hasTrack(a){return!!this.sourceNodeMap[a]}removeTrack(a){const{sourceNode:e,gainNode:t}=this.sourceNodeMap[a]||{};t==null||t.disconnect(),e==null||e.disconnect(),delete this.sourceNodeMap[a],e?this.logger.info("SourceNode disconnected. Active source node:",this.sourceNodeList.length):this.logger.warn(`SourceNode ${a} does not exit. Active source node: ${this.sourceNodeList.length}`)}getAudioTrack(){return this.audioTrack}setVolume(a,e){const{gainNode:t}=this.sourceNodeMap[e]||{};t?(this.logger.info(`Setting node(${e}) volume to ${this.scale(a)}`),t.gain.value=this.scale(a)):this.logger.warn(`GainNode ${e} does not exit.`)}reset(){this.disconnectSourceNode(),this.sourceNodeMap={}}dispose(){var a;this.reset(),(a=this.audioTrack)==null||a.stop(),this.audioDestination.disconnect(),this.audioContext.close()}connectTrack(a){if(!this.audioContext)return this.logger.warn("AudioContext not initialized");let e=new MediaStream;e.addTrack(a);const t=this.audioContext.createMediaStreamSource(e),i=this.audioContext.createGain();i.gain.value=1,t.connect(i),i.connect(this.audioDestination),this.sourceNodeMap[a.id]={track:a,sourceNode:t,gainNode:i},this.logger.info("New sourceNode connected. Active source node:",this.sourceNodeList.length)}disconnectSourceNode(){this.sourceNodeList.forEach(a=>a.disconnect()),this.gainNodeList.forEach(a=>a.disconnect())}scale(a){return a/100}}class ac extends Dt{constructor(){super("audioMixer",Ve.AliRtcSdkStreamTypeCapture,ni.AUDIO);g(this,"audioMixer");g(this,"primaryAudioTrackId");g(this,"screenAudioTrackId");g(this,"dirty",!1);this.zIndex=8}get initOptions(){return{audio:1,screen:1}}setOptions(e){Object.entries(e).forEach(([t,i])=>{this.isValidVolume(i)&&(this.options[t]=i)}),this.dirty=!0,this.emit("updated")}isSupported(){return"AudioContext"in window}shouldUpdate(e,t){var n,c;if(e.type!==Ve.AliRtcSdkStreamTypeCapture)return!1;const i=t.find(o=>o.type===Ve.AliRtcSdkStreamTypeCapture),r=t.find(o=>o.type===Ve.AliRtcSdkStreamTypeScreen);return!(this.primaryAudioTrackId===((n=i==null?void 0:i.currentAudioTrack)==null?void 0:n.id)&&this.screenAudioTrackId===((c=r==null?void 0:r.currentAudioTrack)==null?void 0:c.id)&&!this.dirty)}process(e,t){return I(this,null,function*(){var c,o;this.dirty=!1;const i=t.find(d=>d.type===Ve.AliRtcSdkStreamTypeScreen),r=e.currentAudioTrack,n=i==null?void 0:i.currentAudioTrack;if(!n&&this.options.audio===1)return this.audioMixer&&(this.audioMixer.dispose(),this.audioMixer=void 0),this.primaryAudioTrackId=r==null?void 0:r.id,void e.updateAudioTrack(r);this.audioMixer||(this.audioMixer=new sc),yield this.audioMixer.resume(),this.primaryAudioTrackId&&(r==null?void 0:r.id)!==this.primaryAudioTrackId&&((c=this.audioMixer)==null||c.removeTrack(this.primaryAudioTrackId)),r&&!this.audioMixer.hasTrack(r==null?void 0:r.id)&&this.audioMixer.addTrack(r),this.primaryAudioTrackId=r==null?void 0:r.id,this.screenAudioTrackId&&(n==null?void 0:n.id)!==this.screenAudioTrackId&&((o=this.audioMixer)==null||o.removeTrack(this.screenAudioTrackId)),n&&!this.audioMixer.hasTrack(n==null?void 0:n.id)&&this.audioMixer.addTrack(n),this.screenAudioTrackId=n==null?void 0:n.id,this.updateVolume(),e.updateAudioTrack(this.audioMixer.getAudioTrack())})}isValidVolume(e){return e!==void 0&&e>=0&&e<=4}updateVolume(){this.audioMixer&&(this.primaryAudioTrackId&&this.audioMixer.setVolume(100*this.options.audio,this.primaryAudioTrackId),this.screenAudioTrackId&&this.audioMixer.setVolume(100*this.options.screen,this.screenAudioTrackId))}clear(e){var t;(t=this.audioMixer)==null||t.dispose(),super.clear(e)}}class nc extends Dt{constructor(){super(...arguments);g(this,"hasVideoTrack",!1);g(this,"videoScaler")}get initOptions(){return{width:320,height:180,frameRate:15}}setOptions(e){var t;this.options=e,(t=this.videoScaler)==null||t.updateOptions(e)}isSupported(){return gt.isSupport()}shouldUpdate(e){return this.hasVideoTrack!==!!e.currentVideoTrack}process(e){return I(this,null,function*(){if(e.currentVideoTrack){if(this.hasVideoTrack=!0,!this.videoScaler){const i=this.options||this.initOptions;this.videoScaler=gt.getInstance(e.currentVideoTrack,i)}const t=this.videoScaler.getVideoTrack();t&&e.updateDualVideoTrack(t)}else e.updateDualVideoTrack(),this.emit("updated"),this.videoScaler&&this.videoScaler.dispose()})}clear(e){super.clear(e),this.hasVideoTrack=!1,e==null||e.updateDualVideoTrack()}}function oi(s,a,e,t){return new(e||(e=Promise))(function(i,r){function n(d){try{o(t.next(d))}catch(h){r(h)}}function c(d){try{o(t.throw(d))}catch(h){r(h)}}function o(d){var h;d.done?i(d.value):(h=d.value,h instanceof e?h:new e(function(l){l(h)})).then(n,c)}o((t=t.apply(s,a||[])).next())})}var Ut,wt;function rn(){return oi(this,void 0,void 0,function*(){let s=!1;try{s=yield(()=>I(this,null,function*(){return 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]))}))()}catch(a){s=!1}return console.log("isSupportedSIMD",s),s})}typeof SuppressedError=="function"&&SuppressedError,(wt=Ut||(Ut={}))[wt.ERROR=0]="ERROR",wt[wt.WARN=1]="WARN",wt[wt.INFO=2]="INFO",wt[wt.LOG=3]="LOG",wt[wt.DEBUG=4]="DEBUG";class ve{static error(...a){var e;ve.logLevel>=Ut.ERROR&&((e=console.error)===null||e===void 0||e.call(console,`[${ve.logTag}] `,...a))}static warn(...a){var e;ve.logLevel>=Ut.WARN&&((e=console.warn)===null||e===void 0||e.call(console,`[${ve.logTag}] `,...a))}static info(...a){var e;ve.logLevel>=Ut.INFO&&((e=console.info)===null||e===void 0||e.call(console,`[${ve.logTag}] `,...a))}static log(...a){var e;ve.logLevel>=Ut.LOG&&((e=console.log)===null||e===void 0||e.call(console,`[${ve.logTag}] `,...a))}static debug(...a){var e;ve.logLevel>=Ut.DEBUG&&((e=console.debug)===null||e===void 0||e.call(console,`[${ve.logTag}] `,...a))}}ve.logLevel=Ut.WARN,ve.logTag="aliyun-audio-3a";class oc{}class sn extends oc{static isSupported(){return function(){if(typeof window=="object"&&window!==null){const a="AudioWorklet"in window,e="WebAssembly"in window;return a&&e}return!1}()}static isSupportedSIMD(){return oi(this,void 0,void 0,function*(){return yield rn()})}static setLogger(a){ve.logLevel=a}constructor(a){super(),this.channelCount=1,this.sampleRate=48e3,this.collectDumpOutputData=[],this.collectDumpNearInputData=[],this.collectDumpFarInputData=[],this.collectDumpMetaData=[],this.statUpdateTimer=0,this.statUpdateInterval=5e3,this.options=Object.assign({aecOn:!0,ansOn:!0,agcOn:!0,hdOn:!1,ansMode:1,dumpOn:!1,aiaecOn:!1,wasmCdnPath:"https://g.alicdn.com/code/npm/@ali/aliyun-audio-3a/0.0.6/"},a||{})}initWASM(a,e,t){return oi(this,void 0,void 0,function*(){ve.log("initWASM",a,e,t);const i=n=>oi(this,void 0,void 0,function*(){try{const c=yield fetch(n,{credentials:"same-origin"});return c.ok||this.onLoadError(new Error(`Failed to fetch WASM: ${c.status}:${c.statusText}, url:${n}`)),c.arrayBuffer()}catch(c){return this.onLoadError(new Error("WASM load error")),ve.error("Error fetching WASM:",c),new Uint8Array(0)}}),r=n=>oi(this,void 0,void 0,function*(){return fetch(n).then(c=>c.text())});try{const n=yield rn(),c=this.options.wasmCdnPath+"audio_module_v2.wasm",o=this.options.wasmCdnPath+"audio_module_v2_simd.wasm",h=yield i(n?o:c),l=this.options.wasmCdnPath+"audio_module_v2.js",p=this.options.wasmCdnPath+"audio_module_v2_simd.js",u=n?p:l,f=yield r(u);a.port.postMessage(Object.assign({type:"init",channelCount:e,sampleRate:t,wasmBuffer:h,isSupportSIMD:n,audioModuleScript:f,logLevel:ve.logLevel},this.options),[h])}catch(n){ve.error("Error initializing WASM:",n),this.onLoadError(new Error("WASM init error"))}a.port.onmessage=n=>{n.data.type==="init_done"&&this.onLoadSuccess(void 0),n.data.type==="dump_output_data"&&this.onDumpOutputData(n.data.data),n.data.type==="dump_near_data"&&this.onDumpNearInputData(n.data.data),n.data.type==="dump_far_data"&&this.onDumpFarInputData(n.data.data),n.data.type==="dump_meta_data"&&this.onDumpMeatData(n.data.data),n.data.type==="output_log"&&this.onOutputLog(n.data.data),n.data.type==="apm_stat_data"&&this.onStatData(n.data.data)}})}createProcessor(a,e,t,i,r){return oi(this,void 0,void 0,function*(){this.audioContext=a,this.audioContext.resume(),this.channelCount=t,this.sampleRate=i;try{const o=new Blob(['!function(){"use strict";var Bc=Object.defineProperty,Hc=Object.defineProperties;var Fc=Object.getOwnPropertyDescriptors;var qi=Object.getOwnPropertySymbols,jc=Object.getPrototypeOf,Cn=Object.prototype.hasOwnProperty,kn=Object.prototype.propertyIsEnumerable,zc=Reflect.get;var Xr=(W,X,se)=>X in W?Bc(W,X,{enumerable:!0,configurable:!0,writable:!0,value:se}):W[X]=se,G=(W,X)=>{for(var se in X||(X={}))Cn.call(X,se)&&Xr(W,se,X[se]);if(qi)for(var se of qi(X))kn.call(X,se)&&Xr(W,se,X[se]);return W},vt=(W,X)=>Hc(W,Fc(X));var jt=(W,X)=>{var se={};for(var qe in W)Cn.call(W,qe)&&X.indexOf(qe)<0&&(se[qe]=W[qe]);if(W!=null&&qi)for(var qe of qi(W))X.indexOf(qe)<0&&kn.call(W,qe)&&(se[qe]=W[qe]);return se};var g=(W,X,se)=>(Xr(W,typeof X!="symbol"?X+"":X,se),se);var Yr=(W,X,se)=>zc(jc(W),se,X);var I=(W,X,se)=>new Promise((qe,Ii)=>{var Ci=gt=>{try{ei(se.next(gt))}catch(ti){Ii(ti)}},ki=gt=>{try{ei(se.throw(gt))}catch(ti){Ii(ti)}},ei=gt=>gt.done?qe(gt.value):Promise.resolve(gt.value).then(Ci,ki);ei((se=se.apply(W,X)).next())});function t(t,e,a,n){return new(a||(a=Promise))((function(s,i){function o(t){try{h(n.next(t))}catch(t){i(t)}}function r(t){try{h(n.throw(t))}catch(t){i(t)}}function h(t){var e;t.done?s(t.value):(e=t.value,e instanceof a?e:new a((function(t){t(e)}))).then(o,r)}h((n=n.apply(t,e||[])).next())}))}var e;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.ERROR=0]="ERROR",t[t.WARN=1]="WARN",t[t.INFO=2]="INFO",t[t.LOG=3]="LOG",t[t.DEBUG=4]="DEBUG"}(e||(e={}));class a{static error(...t){var n;a.logLevel>=e.ERROR&&(null===(n=console.error)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static warn(...t){var n;a.logLevel>=e.WARN&&(null===(n=console.warn)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static info(...t){var n;a.logLevel>=e.INFO&&(null===(n=console.info)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static log(...t){var n;a.logLevel>=e.LOG&&(null===(n=console.log)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static debug(...t){var n;a.logLevel>=e.DEBUG&&(null===(n=console.debug)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}}a.logLevel=e.WARN,a.logTag="aliyun-audio-3a";const n=Float32Array.BYTES_PER_ELEMENT,s=Uint16Array.BYTES_PER_ELEMENT;class i{constructor(t,e,a,n,s){this._channelData=[],this._name=t,this._isInitialized=!1,this._module=e,this._length=a,this._ringLength=2*a,this._maxChannelCount=s?Math.min(s,32):n,this._channelCount=n,this._allocateHeap(),this._isInitialized=!0,this._readIndex=0,this._writeIndex=0,this._framesAvailable=0,this._channelDataLocal=[];for(let t=0;t<this._channelCount;++t)this._channelDataLocal[t]=new Float32Array(this._ringLength)}_allocateHeap(){const t=this._length*n,e=this._channelCount*t;this._dataPtr=this._module._malloc(e),this._channelData=[];for(let e=0;e<this._channelCount;++e){const a=this._dataPtr+e*t,n=a+t;this._channelData[e]=this._module.HEAPF32.subarray(a>>s,n>>s)}}adaptChannel(t){t<this._maxChannelCount&&(this._channelCount=t)}get length(){return this._isInitialized?this._length:null}get numberOfChannels(){return this._isInitialized?this._channelCount:null}get maxChannelCount(){return this._isInitialized?this._maxChannelCount:null}getChannelData(t){return void 0!==t&&t>=this._channelCount?null:void 0===t?this._channelData:this._channelData[t]}getHeapAddress(){return this._dataPtr}getPointer(){return this._dataPtr}free(){this._isInitialized=!1,null!==this._dataPtr&&this._module._free(this._dataPtr),this._channelData=[]}get framesAvailable(){return this._framesAvailable}push(t){const e=t[0].length;for(let a=0;a<e;++a){for(let e=0;e<this._channelCount;++e)this._channelDataLocal[e][this._writeIndex]=t[e][a];this._writeIndex=(this._writeIndex+1)%this._ringLength}this._framesAvailable+=e,this._framesAvailable>this._ringLength&&(console.warn(this._name,"Too many frames available, overflow"),this._framesAvailable=this._ringLength,this._writeIndex=0)}pull(t){if(0===this._framesAvailable)return void console.warn(this._name,"No frames available");const e=t[0].length;for(let a=0;a<e;++a){for(let e=0;e<this._channelCount;++e)t[e][a]=this._channelDataLocal[e][this._readIndex];this._readIndex=(this._readIndex+1)%this._ringLength}this._framesAvailable-=e,this._framesAvailable<0&&(this._framesAvailable=0,this._readIndex=0)}}class o{constructor(t){this.inited=!1,this.handle=null,this.channelCount=1,this.isEnable=!0,this.dumpAudioData=!1,this.kernelBufferSize=512,this.node=t,this.onDumpOutputDataFunction=null,this.onDumpNearDataFunction=null,this.onDumpFarDataFunction=null,this.onDumpMetaDataFunction=null,this.wasmInvoker=null,this._nearAudioBuffer={},this._outputAudioBuffer={}}destructor(){this.wasmInvoker=null,this.handle=null}init(n){return t(this,void 0,void 0,(function*(){const{wasmBuffer:t,audioModuleScript:s,channelCount:o=1,sampleRate:r=44100,dumpAudioData:h=!1,logLevel:l=e.DEBUG}=n;a.logLevel=l,a.log("AudioAPM init",JSON.stringify(n)),this.channelCount=o,this.dumpAudioData=h;try{const e=new Function(`let module={};let exports={};${s}; return module`)();this.wasmInvoker=yield e.exports({wasmBinary:t})}catch(t){this.node.port.postMessage({type:"error",message:"audioModule init error"}),a.error(t)}this._nearAudioBuffer=new i("inBuffer",this.wasmInvoker,this.kernelBufferSize,2*this.channelCount,32),this._outputAudioBuffer=new i("outBuffer",this.wasmInvoker,this.kernelBufferSize,this.channelCount,32);const u=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=String.fromCharCode.apply(null,a);this.node&&this.node.port&&this.node.port.postMessage({type:"output_log",message:"output_log",data:n})}),"vii");if(this.wasmInvoker.__apm_log_callback(u),this.handle=this.wasmInvoker.__apm_create(n.aecOn?1:0,n.ansOn?1:0,n.agcOn?1:0,n.hdOn?1:0,r,o,n.dumpOn?1:0,this.kernelBufferSize),n.aiaecOn){const t=102;this.wasmInvoker.__apm_set_param(this.handle,t,7)}if(n.useHardOnly){const t=108;this.wasmInvoker.__apm_set_param(this.handle,t,1)}this.node.port.postMessage({type:"init_done",message:"init done"}),this.inited=!0}))}getStatData(){if(this.wasmInvoker&&this.isEnable){let t=this.wasmInvoker.__apm_get_stat(this.handle),e=this.wasmInvoker.UTF8ToString(t);this.wasmInvoker._free(t),this.node&&this.node.port&&this.node.port.postMessage({type:"apm_stat_data",message:"apm_stat_data",data:e})}}onOutputLog(t){console.log("[WASM_LOG]",t)}destory(){return t(this,void 0,void 0,(function*(){var t;try{null===(t=this.wasmInvoker)||void 0===t||t.__apm_destory(this.handle),this.inited=!1}catch(t){a.error(t)}finally{this.handle=null}}))}enable(){this.isEnable=!0,a.log("APM enable")}disable(){this.isEnable=!1,a.log("APM disable")}getStat(){if(null==this.wasmInvoker||null==this.handle)return"";let t=this.wasmInvoker.__apm_get_stat(this.handle),e=this.wasmInvoker.UTF8ToString(t);return this.wasmInvoker._free(t),e}startDump(){this.onDumpOutputDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_output_data",message:"dump_output_data",data:n})}),"vii"),this.onDumpNearDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_near_data",message:"dump_near_data",data:n})}),"vii"),this.onDumpFarDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_far_data",message:"dump_far_data",data:n})}),"vii"),this.onDumpMetaDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_meta_data",message:"dump_meta_data",data:n})}),"vii"),this.wasmInvoker.__apm_dump_start(this.handle,this.onDumpOutputDataFunction,this.onDumpNearDataFunction,this.onDumpFarDataFunction,this.onDumpMetaDataFunction)}stopDump(){this.wasmInvoker.__apm_dump_stop(this.handle),this.wasmInvoker&&(this.wasmInvoker.removeFunction(this.onDumpOutputDataFunction),this.wasmInvoker.removeFunction(this.onDumpNearDataFunction),this.wasmInvoker.removeFunction(this.onDumpFarDataFunction),this.wasmInvoker.removeFunction(this.onDumpMetaDataFunction))}process(t,e,a){if(!this.inited||!this.isEnable){for(let e=0;e<this.channelCount;e++){a[e].set(t[e])}return}const n=this.channelCount;let s=0;if(this.handle&&this.isEnable){const i=t[0].length,o=[];for(let a=0;a<n;a++)e[a]&&e[a].length>0&&(s=1),o.push(t[a]||new Float32Array(i).fill(0)),o.push(e[a]||new Float32Array(i).fill(0));if(this._nearAudioBuffer.push(o),this._nearAudioBuffer.framesAvailable>=this.kernelBufferSize){this._nearAudioBuffer.pull(this._nearAudioBuffer.getChannelData()),this.wasmInvoker.__apm_process_new(this.handle,this._nearAudioBuffer.getHeapAddress(),this._outputAudioBuffer.getHeapAddress(),n,s);const t=this._outputAudioBuffer.getChannelData();this._outputAudioBuffer.push(t)}this._outputAudioBuffer.pull(a)}}}class r extends AudioWorkletProcessor{constructor(){super(),this.apm=new o(this),this.port.onmessage=t=>{const e=t.data||{};switch(a.log("onmessage data",e),e.type){case"init":this.apm.init(e);break;case"destroy":this.apm.destory();break;case"enable":this.apm.enable();break;case"disable":this.apm.disable();break;case"start_dump":this.apm.startDump();break;case"stop_dump":this.apm.stopDump();break;case"get_stat_data":this.apm.getStatData();break;default:a.warn("Unknown message type:",e.type)}}}process(t,e){const a=t[0],n=t.length>1?t[1]:[],s=e[0];return this.apm.process(a,n,s),!0}}registerProcessor("aliyun-web-3a-processor",r)}();\n'],{type:"application/javascript"}),d=URL.createObjectURL(o);yield this.audioContext.audioWorklet.addModule(d)}catch(o){ve.error("Failed to add module to audio worklet:",o)}let n=new AudioWorkletNode(this.audioContext,"aliyun-web-3a-processor",{numberOfInputs:2,outputChannelCount:[t]});this.workletNode=n,e.connect(n),r&&(this.farNode=r,r.connect(n,0,1));const c=this.audioContext.createMediaStreamDestination();n.connect(c),this.targetMediaTrack=c.stream.getAudioTracks()[0],yield this.initWASM(n,t,i),this.statUpdateTimer=window.setInterval(()=>{this.getStatData()},this.statUpdateInterval)})}addFarNode(a){this.workletNode&&(this.farNode&&this.farNode.disconnect(this.workletNode),a&&(this.farNode=a,a.connect(this.workletNode,0,1)))}getStatData(){var a;try{(a=this.workletNode)===null||a===void 0||a.port.postMessage({type:"get_stat_data"})}catch(e){ve.error("Failed to post message to worklet node:",e)}}destroy(){if(this.statUpdateTimer&&window.clearInterval(this.statUpdateTimer),this.audioContext&&this.workletNode&&this.workletNode.port)try{this.workletNode.port.postMessage({type:"destroy"}),this.workletNode.port.onmessage=null,this.workletNode.disconnect(),ve.log("postMessage destroy")}catch(a){ve.error("Failed to post message to worklet node:",a)}}startDump(){var a;try{(a=this.workletNode)===null||a===void 0||a.port.postMessage({type:"start_dump"})}catch(e){ve.error("Failed to post message to worklet node:",e)}}stopDump(){var a;try{(a=this.workletNode)===null||a===void 0||a.port.postMessage({type:"stop_dump"})}catch(e){ve.error("Failed to post message to worklet node:",e)}setTimeout(()=>{this.onDumpOutputData(null,!0),this.onDumpNearInputData(null,!0),this.onDumpFarInputData(null,!0),this.onDumpMeatData(null,!0)},3e3)}onDumpOutputData(a,e=!1){if(a&&a.length>0&&this.collectDumpOutputData.push(a),e&&this.collectDumpOutputData.length>0||1024*this.collectDumpOutputData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpOutputData);this.onDumpData(t,"output_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpOutputData=[]}}onDumpNearInputData(a,e=!1){if(a&&a.length>0&&this.collectDumpNearInputData.push(a),e&&this.collectDumpNearInputData.length>0||1024*this.collectDumpNearInputData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpNearInputData);this.onDumpData(t,"near_input_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpNearInputData=[]}}onDumpFarInputData(a,e=!1){if(a&&a.length>0&&this.collectDumpFarInputData.push(a),e&&this.collectDumpFarInputData.length>0||1024*this.collectDumpFarInputData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpFarInputData);this.onDumpData(t,"far_input_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpFarInputData=[]}}onDumpMeatData(a,e=!1){if(a&&a.length>0&&this.collectDumpMetaData.push(a),e&&this.collectDumpMetaData.length>0||1024*this.collectDumpMetaData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpMetaData);this.onDumpData(t,"meta_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpMetaData=[]}}getMaxDumpBytes(){return 600*Number(this.sampleRate.toFixed(0))*Number(this.channelCount.toFixed(0))*2}enable(){var a;if(!((a=this.workletNode)===null||a===void 0)&&a.port)try{this.workletNode.port.postMessage({type:"enable"}),ve.log("postMessage enable")}catch(e){ve.error("Failed to post message to worklet node:",e)}}disable(){var a;if(!((a=this.workletNode)===null||a===void 0)&&a.port)try{ve.log("postMessage disable"),this.workletNode.port.postMessage({type:"disable"})}catch(e){ve.error("Failed to post message to worklet node:",e)}}on(a,e){a==="loaderror"&&(this.onLoadError=e),a==="loadsuccess"&&(this.onLoadSuccess=e),a==="dumpdata"&&(this.onDumpData=e),a==="outputlog"&&(this.onOutputLog=e),a==="statdata"&&(this.onStatData=e)}onLoadError(a){console.log("onLoadError",a)}onLoadSuccess(a){console.log("onLoadSuccess",a)}onDumpData(a,e){console.log("onDumpData",a,e)}onOutputLog(a){console.log("[WASM]",a)}onStatData(a){console.log("onStatData:",a)}}const Si="[AliyunAudio3A] ";class cc extends Dt{constructor(e){super("AliRtcAudioProcessPlugin",Ve.AliRtcSdkStreamTypeCapture,ni.AUDIO);g(this,"audioProcessor");g(this,"slsReporter");g(this,"enableSoft3ACheck",!1);g(this,"useHardOnly",!1);g(this,"lastDiffOutputLog","");g(this,"audioContext",new AudioContext({sampleRate:48e3}));g(this,"farNode");g(this,"createNode",e=>this.audioContext.createMediaStreamSource(new MediaStream([e])));this.options=e,this.slsReporter=e==null?void 0:e.slsReporter,this.enableSoft3ACheck=(e==null?void 0:e.enableSoft3ACheck)||!1,this.useHardOnly=(e==null?void 0:e.useHardOnly)||!1,this.zIndex=7,document.addEventListener("click",this.activeAudioContext)}activeAudioContext(){this.audioContext.resume(),document.removeEventListener("click",this.activeAudioContext)}audioUpdated(e){var t,i;return((t=this.lastInputAudioTrack)==null?void 0:t.id)!==((i=e.currentAudioTrack)==null?void 0:i.id)}videoUpdated(e){return console.log("videoUpdated",e),!1}setOptions(e){var t;!this.farNode&&e.farMediaStream&&(this.farNode=this.audioContext.createMediaStreamSource(e.farMediaStream),this.audioProcessor&&((t=this.audioProcessor)==null||t.addFarNode(this.farNode)),this.options=G(G({},this.options),e))}isSupported(){return sn.isSupported()}shouldUpdate(e){return!!(e.originAudioTrack&&!this.audioProcessor||!e.originAudioTrack&&this.audioProcessor)}process(e){return I(this,null,function*(){var t;if(!e.currentAudioTrack)return e.updateAudioTrack(),void this.clear(e);if(!this.audioProcessor){V.info(Si,"create audio processor this.options:",this.options),this.audioProcessor=new sn({aecOn:!0,ansOn:!0,agcOn:!0,dumpOn:((t=this.options)==null?void 0:t.dumpAudioData)||!1,aiaecOn:this.options.aiaecOn||!1,useHardOnly:this.useHardOnly,wasmCdnPath:this.options.wasmCdnPath||"https://g.alicdn.com/code/npm/@ali/aliyun-audio-3a/0.0.6/"}),this.audioProcessor.on("dumpdata",(r,n)=>{let c=3e3;n.includes("far")?c=5e3:n.includes("output")?c=1e4:n.includes("meta")&&(c=8e3),setTimeout(()=>{const o=URL.createObjectURL(r),d=document.createElement("a");d.href=o,d.download=n,document.body.appendChild(d),d.click(),document.body.removeChild(d)},c)}),this.audioProcessor.on("loadsuccess",()=>{var r,n;V.info(Si,"loadsuccess"),this.enableSoft3ACheck||e.updateAudioTrack((r=this.audioProcessor)==null?void 0:r.targetMediaTrack),this.options.dumpAudioData&&((n=this.audioProcessor)==null||n.startDump())}),this.audioProcessor.on("loaderror",r=>{V.error(Si,"loaderror:",r==null?void 0:r.message),this.emit("error",r)}),this.audioProcessor.on("outputlog",r=>{V.info(Si,"outputlog:",r),r!=null&&r.includes("diff")&&(this.lastDiffOutputLog=r||"")}),this.audioProcessor.on("statdata",r=>{var n;if(r)try{let c=r;if(this.lastDiffOutputLog){const o=this.extractDiffValue(this.lastDiffOutputLog),d=JSON.parse(r);o!==null&&(d.diff=o);const h=this.extractLeakValue(this.lastDiffOutputLog);h!==null&&(d.leak=h),c=JSON.stringify(d)}(n=this.slsReporter)==null||n.reportPublishAudio3A("","","",c)}catch(c){V.error(Si,"statdata error:",c)}});const i=this.createNode(e.currentAudioTrack);yield this.audioProcessor.createProcessor(this.audioContext,i,1,48e3,this.farNode)}})}extractDiffValue(e){if(!e)return null;const t=e.match(/diff\s*=\s*(-?\d+\.?\d*)/);return t?parseFloat(t[1]):null}extractLeakValue(e){if(!e)return null;const t=e.match(/leak\s*=\s*(-?\d+\.?\d*)/);return t?parseFloat(t[1]):null}clear(e){var t,i,r;this.options.dumpAudioData&&((t=this.audioProcessor)==null||t.stopDump()),super.clear(e),(i=this.audioProcessor)==null||i.destroy(),this.audioProcessor=void 0,document.removeEventListener("click",this.activeAudioContext),(r=this.farNode)==null||r.disconnect(),this.farNode=void 0}dump(){var e;(e=this.audioProcessor)==null||e.stopDump()}}var bi=(s=>(s[s.Default=0]="Default",s[s.Human=1]="Human",s[s.Robot=2]="Robot",s))(bi||{}),dc=Object.defineProperty,hc=Object.getOwnPropertyDescriptor,an=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?hc(a,e):a,n=s.length-1;n>=0;n--)(i=s[n])&&(r=(t?i(a,e,r):i(r))||r);return t&&r&&dc(a,e,r),r};const Pr=(Ht=class extends se{constructor(e){super();g(this,"self");g(this,"remoteUser");g(this,"sendReadyMsg",!1);g(this,"hasPubDataChannel",!1);g(this,"hasSubDataChannel",!1);g(this,"readyMsgSuccess",!1);g(this,"sendReadyMsgTimer");g(this,"startReadyMsgTime");g(this,"onSubscribeDataChannel",e=>{!this.remoteUser&&e&&(this.hasSubDataChannel=!0,this.remoteUser=e,this.remoteUser.on("remoteDataChannelMessage",this.onCheckReadyMsg),this.trySendReadyMsg())});g(this,"onCheckReadyMsg",(e,t)=>{var i,r;if(this.sendReadyMsg&&!this.readyMsgSuccess)try{const n=new TextDecoder().decode(t.data),c=JSON.parse(n);c.key==="aliyun_aigc"&&c.type==="ready_resp"&&((i=c.data)==null?void 0:i.ready)===!0&&(V.event(`[${Ht.logName}]`,"onCheckReadyMsg success"),this.readyMsgSuccess=!0,this.emit("dcready",e),(r=this.remoteUser)==null||r.off("remoteDataChannelMessage",this.onCheckReadyMsg),window.clearTimeout(this.sendReadyMsgTimer))}catch(n){}});g(this,"onDataPublishStateChange",(e,t)=>{t===ie.AliRtcStatePublished&&(this.hasPubDataChannel=!0,this.trySendReadyMsg())});this.self=e,this.self.on("dataPublishStateChanged",this.onDataPublishStateChange)}destory(){this.self.off("dataPublishStateChanged",this.onDataPublishStateChange),window.clearTimeout(this.sendReadyMsgTimer),this.remoteUser=void 0,this.sendReadyMsg=!1,this.hasPubDataChannel=!1,this.hasSubDataChannel=!1,this.readyMsgSuccess=!1,this.startReadyMsgTime=0}trySendReadyMsg(){V.event(`[${Ht.logName}]`,`trySendReadyMsg: pub(${this.hasPubDataChannel}, sub: ${this.hasSubDataChannel})`),this.hasPubDataChannel&&this.hasSubDataChannel&&(this.sendReadyMsg=!0,this.sendReadyMsgLoop())}sendReadyMsgLoop(e=0){return I(this,null,function*(){const t=JSON.stringify({key:"aliyun_aigc",version:"1.0",type:"ready_req",data:{ready:!0}});try{this.self.sendDataChannelMessage(new Vt(new TextEncoder().encode(t).buffer))}catch(n){}this.startReadyMsgTime||(this.startReadyMsgTime=Date.now());let i=50;const r=Date.now()-this.startReadyMsgTime;i=r<1e3?50:r<2e3?100:r<3e3?500:2e3,e>30?V.event(`[${Ht.logName}]`,"sendReadyMsgLoop fail after 30 times"):this.sendReadyMsgTimer=window.setTimeout(()=>{this.sendReadyMsgLoop(e+1)},i)})}},g(Ht,"logName","DataChannelReadyHelper"),Ht);an([C()],Pr.prototype,"destory",1),an([C()],Pr.prototype,"sendReadyMsgLoop",1);let lc=Pr;class uc{constructor(a){g(this,"_useSysEchoCancellation",!0);g(this,"_useSysNoiseSuppression",!0);g(this,"_useSysAutoGainControl",!0);g(this,"_useAIAEC",!1);g(this,"_enableSoft3A",!1);g(this,"_enableSoft3ACheck",!1);g(this,"_useHardOnly",!1);g(this,"_dumpAudioData",!1);g(this,"_useAudio3AConfigFromServer",!0);a&&Object.assign(this,a)}get useSysEchoCancellation(){return this._useSysEchoCancellation}set useSysEchoCancellation(a){this._useSysEchoCancellation=a}get useSysNoiseSuppression(){return this._useSysNoiseSuppression}set useSysNoiseSuppression(a){this._useSysNoiseSuppression=a}get useSysAutoGainControl(){return this._useSysAutoGainControl}set useSysAutoGainControl(a){this._useSysAutoGainControl=a}get useAIAEC(){return this._useAIAEC}set useAIAEC(a){this._useAIAEC=a}get enableSoft3A(){return this._enableSoft3A}set enableSoft3A(a){this._enableSoft3A=a}get enableSoft3ACheck(){return this._enableSoft3ACheck}set enableSoft3ACheck(a){this._enableSoft3ACheck=a}get useHardOnly(){return this._useHardOnly}set useHardOnly(a){this._useHardOnly=a}get dumpAudioData(){return this._dumpAudioData}set dumpAudioData(a){this._dumpAudioData=a}get useAudio3AConfigFromServer(){return this._useAudio3AConfigFromServer}set useAudio3AConfigFromServer(a){this._useAudio3AConfigFromServer=a}loadFromLocalConfig(a){var e,t,i,r,n,c,o,d,h;this.useAudio3AConfigFromServer=(e=a.useAudio3AConfigFromServer)!=null?e:this.useAudio3AConfigFromServer,this.useSysEchoCancellation=(t=a.useSysEchoCancellation)!=null?t:this.useSysEchoCancellation,this.useSysNoiseSuppression=(i=a.useSysNoiseSuppression)!=null?i:this.useSysNoiseSuppression,this.useSysAutoGainControl=(r=a.useSysAutoGainControl)!=null?r:this.useSysAutoGainControl,this.useAIAEC=(n=a.useAIAEC)!=null?n:this.useAIAEC,this.enableSoft3A=(c=a.enableSoft3A)!=null?c:this.enableSoft3A,this.dumpAudioData=(o=a.dumpAudioData)!=null?o:this.dumpAudioData,this.enableSoft3ACheck=(d=a.enableSoft3ACheck)!=null?d:this.enableSoft3ACheck,this.useHardOnly=(h=a.useHardOnly)!=null?h:this.useHardOnly}loadFromServerConfig(a){if(a&&typeof a=="object"){const e=ri(a,"enableSoft3A"),t=si(a,"enableSoft3A");if(e===!0&&t===!0&&(this.enableSoft3A=!0),this.enableSoft3A){if(a.archCfgs){const i=ri(a,"enableSoft3ACheck");i!==void 0&&(this.enableSoft3ACheck=i);const r=ri(a,"useAIAEC");r!==void 0&&(this.useAIAEC=r);const n=ri(a,"useSysNoiseSuppression");n!==void 0&&(this.useSysNoiseSuppression=n);const c=ri(a,"useSysEchoCancellation");c!==void 0&&(this.useSysEchoCancellation=c);const o=ri(a,"useSysAutoGainControl");o!==void 0&&(this.useSysAutoGainControl=o)}if(a.config){const i=si(a,"enableSoft3ACheck");i!==void 0&&(this.enableSoft3ACheck=i);const r=si(a,"useAIAEC");r!==void 0&&(this.useAIAEC=r);const n=si(a,"useSysNoiseSuppression");n!==void 0&&(this.useSysNoiseSuppression=n);const c=si(a,"useSysEchoCancellation");c!==void 0&&(this.useSysEchoCancellation=c);const o=si(a,"useSysAutoGainControl");o!==void 0&&(this.useSysAutoGainControl=o)}V.info("setAudio3AConfig:","enableSoft3A",this.enableSoft3A,", enableSoft3ACheck",this.enableSoft3ACheck,", useAIAEC",this.useAIAEC,", useSysNoiseSuppression",this.useSysNoiseSuppression,", useSysEchoCancellation",this.useSysEchoCancellation,", useSysAutoGainControl",this.useSysAutoGainControl)}}}}var pc=Object.defineProperty,mc=Object.getOwnPropertyDescriptor,tt=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?mc(a,e):a,n=s.length-1;n>=0;n--)(i=s[n])&&(r=(t?i(a,e,r):i(r))||r);return t&&r&&pc(a,e,r),r};class Ge extends se{constructor(e){super();g(this,"self");g(this,"userMap",{});g(this,"usersViewMap",{});g(this,"rtsManager");g(this,"localStreamManager");g(this,"authInfo");g(this,"signalingManager");g(this,"pluginManager");g(this,"audioMixerPlugin");g(this,"dualVideoPlugin");g(this,"blankAudioPlugin");g(this,"audioProcessorPlugin");g(this,"slsReporter");g(this,"statsMonitorId");g(this,"autoSubAudio",!0);g(this,"autoSubVideo",!0);g(this,"autoSubScreen",!0);g(this,"wantSubAudio",!0);g(this,"wantSubVideo",!0);g(this,"wantSubScreen",!0);g(this,"defaultStreamType",ze.AliRtcVideoStreamTypeHigh);g(this,"audioMuted",!1);g(this,"playoutVolume",1);g(this,"refreshUrlTimer");g(this,"audioVolumeIndicationInterval",0);g(this,"indicationTimer",0);g(this,"parameter",{});g(this,"audio3AConfig",new uc);g(this,"dcReadyHelper");const{signalingManager:t,slsReporter:i}=e;this.signalingManager=t,this.addSignalingManagerListener(),this.slsReporter=i,this.pluginManager=new Go,this.localStreamManager=new ec(this.pluginManager,this.slsReporter),this.rtsManager=new Yo(this.localStreamManager,this.slsReporter,this.parameter),this.self=new jo({rtsManager:this.rtsManager,localStreamManager:this.localStreamManager,slsReporter:this.slsReporter,signalingManager:this.signalingManager,pluginManager:this.pluginManager,audioVolumeIndicationInterval:this.audioVolumeIndicationInterval,parameter:this.parameter}),this.audioMixerPlugin=new ac,this.pluginManager.add(this.audioMixerPlugin),this.dualVideoPlugin=new nc("dualVideoPlugin"),new X.AliRTS.SupportUtil().checkScreenCapture()&&this.pluginManager.add(new ic)}addSignalingManagerListener(){this.signalingManager.on("onNotifyPublish",e=>{e.forEach(t=>{var i;(i=t==null?void 0:t.tracks)==null||i.forEach(r=>{var n;if(r.msid===M.Audio&&r.userdata)try{const c=JSON.parse(r.userdata);c.agent_instance&&((n=this.slsReporter)==null||n.setCustomFields({ageniid:c.agent_instance}))}catch(c){console.error("Failed to parse userdata:",c)}})}),this.slsReporter.reportConnectionLatencyEvent(ot.RECV_NOTIFY_PUBLISH,"","",""),V.event("[Signaling] Notify Publish ",e),e.forEach(t=>{this.onRemotePublishStateChange(t)})}),this.signalingManager.stsManager.on("onTokenUpdate",(e,t)=>{this.slsReporter.updateToken(t,e)})}isAutoSubAudio(){return this.autoSubAudio}setAutoSubAudio(e){this.autoSubAudio=e}isAutoSubVideo(){return this.autoSubVideo}setAutoSubVideo(e){this.autoSubVideo=e}isAutoSubScreen(){return this.autoSubScreen}setAutoSubScreen(e){this.autoSubScreen=e}isWantSubAudio(){return this.wantSubAudio}setWantSubAudio(e){this.wantSubAudio=e,this.remoteUsers.forEach(t=>{t.setWantSubAudio(e),t.updateSubscribe(be.User)})}isWantSubVideo(){return this.wantSubVideo}setWantSubVideo(e){this.wantSubVideo=e,this.remoteUsers.forEach(t=>{t.setWantSubVideo(e),t.updateSubscribe(be.User)})}isWantSubScreen(){return this.wantSubScreen}setWantSubScreen(e){this.wantSubScreen=e,this.remoteUsers.forEach(t=>{t.setWantSubScreen(e),t.updateSubscribe(be.User)})}setRemoteDefaultVideoStreamType(e){this.defaultStreamType=e,this.remoteUsers.forEach(t=>{t.setRemoteDefaultVideoStreamType(e)})}setRemoteUserVideoStreamType(e,t){var i;(i=this.getRemoteUser(e))==null||i.setRemoteDefaultVideoStreamType(t)}setAudioMuted(e){this.audioMuted=e,this.remoteUsers.forEach(t=>{t.setAudioMuted(e)})}setLocalViewConfig(e,t){var r;if(!e)return(r=this.publisher)==null?void 0:r.setViewConfig(null,t);const i=wr(e);i.length!==0&&i.forEach(n=>{var c,o;(c=this.publisher)==null||c.resetElement(n),Object.values(this.usersViewMap).forEach(({cameraViews:d=[],screenViews:h=[]})=>{d.includes(n)&&d.splice(d.indexOf(n),1),h.includes(n)&&h.splice(h.indexOf(n),1)}),(o=this.publisher)==null||o.setViewConfig(i,t)})}setRemoteViewConfig(e,t,i){var n,c;if(!t)return(n=this.userMap[e])==null?void 0:n.setViewConfig(null,i);const r=wr(t);r.length!==0&&(r.forEach(o=>{var d;(d=this.publisher)==null||d.resetElement(o),Object.values(this.usersViewMap).forEach(({cameraViews:h=[],screenViews:l=[]})=>{h.includes(o)&&h.splice(h.indexOf(o),1),l.includes(o)&&l.splice(l.indexOf(o),1)})}),(c=this.userMap[e])==null||c.setViewConfig(r,i))}get channel(){var e;return(e=this.authInfo)==null?void 0:e.channelId}get userId(){var e;return(e=this.authInfo)==null?void 0:e.userId}get remoteUsers(){return Object.values(this.userMap)}get publisher(){return this.self}get isSubscribing(){var e;return((e=this.remoteUsers)!=null?e:[]).some(t=>{const{isAudioSubscribing:i,isVideoSubscribing:r,isScreenSubscribing:n}=t;return i||r||n})}onRemotePublishStateChange(e,t=!0){var u;const{userid:i,callid:r,subscribe:n,pubid:c="",tracks:o}=e,d=(u=n==null?void 0:n.pullstreamurl)!=null?u:"";let h=this.getRemoteUser(i);if(!h)return;const l=h.streamInfo.audioTrackInfo,p=h.streamInfo.videoTrackInfo;h.updateRemoteTracks(r,d,c,o),l===h.streamInfo.audioTrackInfo&&p===h.streamInfo.videoTrackInfo||this.emit("remoteTrackAvailableChange",i,h.streamInfo.audioTrackInfo,h.streamInfo.videoTrackInfo),t&&h.updateSubscribe(be.Publish)}setTimeoutToUpdateAllStreamUrls(e){var r;if(!e)return;let t=354e4;const i=(r=function(n){var c,o;try{const d=new URL(n),[h,l]=d.pathname.slice(1).split("/"),p=/(\w+)(web\w{5}-\w{4}-\w{4}-\w{4}-\w{12})/.exec(l),u=p==null?void 0:p[1],f=p==null?void 0:p[2],m=new URLSearchParams(d.search);return{appId:h,channelId:u,sessionId:f,timeoutTs:1e3*parseInt((o=(c=m.get("auth_key"))==null?void 0:c.split("-")[0])!=null?o:"0")}}catch(d){return null}}(e))==null?void 0:r.timeoutTs;i&&(t=i-Date.now()-6e4),this.refreshUrlTimer=window.setTimeout(()=>I(this,null,function*(){var c;const n=yield this.signalingManager.refreshUrl({pushstreamurl:this.self.url,users:this.remoteUsers.map(o=>({userid:o.userId,subscribe:{pullstreamurl:o.streamUrl}}))});n.pushstreamurl&&(this.self.url=n.pushstreamurl),(c=n.users)==null||c.forEach(o=>{var h;const d=this.getRemoteUser(o.userid);d&&((h=o.subscribe)!=null&&h.pullstreamurl)&&(d.streamUrl=o.subscribe.pullstreamurl)}),this.setTimeoutToUpdateAllStreamUrls(n.pushstreamurl)}),t)}init(e,t,i){var r;this.authInfo=e,this.self.enableAudioVolumeIndication(this.audioVolumeIndicationInterval),this.self.initInfo(e,t.pushstreamurl),this.audio3AConfig.useAudio3AConfigFromServer&&this.audio3AConfig.loadFromServerConfig((r=t==null?void 0:t.config)==null?void 0:r.data),this.setupAudioProcessingPluginIfNeeded(),i.capabilityProfile===bi.Human&&(this.dcReadyHelper=new lc(this.self),this.dcReadyHelper.on("dcready",n=>{var c;this.emit("remoteUserSubscribedDataChannel",n),(c=this.dcReadyHelper)==null||c.destory(),this.dcReadyHelper=void 0})),this.setTimeoutToUpdateAllStreamUrls(t.pushstreamurl),t.users.forEach(n=>{this.addUser(n,be.InRoom)}),this.startStatsMonitor()}leave(){return I(this,null,function*(){var e;this.stopStatsMonitor(),this.refreshUrlTimer!==void 0&&(window.clearTimeout(this.refreshUrlTimer),this.refreshUrlTimer=void 0),Object.values(this.usersViewMap).forEach(({cameraViews:t=[],screenViews:i=[]})=>{t.forEach(r=>{r.srcObject=null,r._playPromise=void 0}),i.forEach(r=>{r.srcObject=null,r._playPromise=void 0})}),this.usersViewMap={};for(let t in this.userMap)this.userMap[t]&&(this.userMap[t].clear(),delete this.userMap[t]);this.self.leave(),(e=this.dcReadyHelper)==null||e.destory(),this.dcReadyHelper=void 0,this.localStreamManager.stop(),this.rtsManager.clear(),this.authInfo=void 0})}clear(){return I(this,null,function*(){yield this.leave(),this.self.clear(),this.pluginManager.removeAll()})}startStatsMonitor(){this.statsMonitorId=window.setInterval(()=>I(this,null,function*(){if(this.publisher){const{audio:i,video:r,candidate:n}=yield this.publisher.getStats();i&&i.length>0&&this.emit("rtcLocalAudioStats",i),r&&r.length>0&&this.emit("rtcLocalVideoStats",r),n&&this.emit("rtcStats",n)}const e=[],t=[];for(const i of this.remoteUsers){const{audio:r,video:n}=yield i.getStats();r&&r.forEach(c=>{e.push(c)}),n&&n.forEach(c=>{t.push(c)})}e.length>0&&this.emit("rtcRemoteAudioStats",e),t.length>0&&this.emit("rtcRemoteVideoStats",t)}),2e3)}stopStatsMonitor(){this.statsMonitorId&&clearInterval(this.statsMonitorId)}addUser(e,t){const i=e.userid;let r=this.userMap[i];return r||(r=this.executeAddUser(i,e.displayname||"",t),this.userMap[i]=r,this.emit("remoteUserJoin",i,0)),this.onRemotePublishStateChange(e,t!==be.InRoom),r}executeAddUser(e,t,i){const r=new Jo({userId:e,displayName:t,rtsManager:this.rtsManager,signalingManager:this.signalingManager,usersViewMap:this.usersViewMap,slsReporter:this.slsReporter,localUser:this.self,audioVolumeIndicationInterval:this.audioVolumeIndicationInterval,playoutVolume:this.playoutVolume,parameter:this.parameter});return r.on(Ye.Remote,this.onRemoteDeviceStatusChange.bind(this)),r.on(Ee.PullStreamStats,this.onRemoteStatReport.bind(this)),r.on(Ee.RtsSubscribeExceeds,this.onSubscribeExceeds.bind(this)),r.on("audioSubscribeStateChanged",(n,c,o,d)=>{this.emit("audioSubscribeStateChanged",n,c,o,d,this.channel||"")}),r.on("videoSubscribeStateChanged",(n,c,o,d)=>{this.emit("videoSubscribeStateChanged",n,c,o,d,this.channel||"")}),r.on("screenSubscribeStateChanged",(n,c,o,d)=>{this.emit("screenSubscribeStateChanged",n,c,o,d,this.channel||"")}),r.on("dataSubscribeStateChanged",(n,c,o,d)=>{var h;o===me.AliRtcStateSubscribed&&((h=this.dcReadyHelper)==null||h.onSubscribeDataChannel(this.userMap[n])),this.emit("dataSubscribeStateChanged",n,c,o,d,this.channel||"")}),r.on("remoteAudioAutoPlayFail",n=>{this.emit("remoteAudioAutoPlayFail",n)}),r.on("remoteVideoAutoPlayFail",(n,c)=>{this.emit("remoteVideoAutoPlayFail",n,c)}),r.on("remoteAudioPlayError",(n,c)=>{this.emit("remoteAudioPlayError",n,c)}),r.on("remoteVideoPlayError",(n,c)=>{this.emit("remoteVideoPlayError",n,c)}),r.on("remoteSubscribeError",n=>{this.emit("remoteSubscribeError",n,r.userId)}),r.on("occurError",n=>{this.emit("occurError",n,r.userId)}),r.on("remoteDataChannelMessage",(n,c)=>{this.emit("remoteDataChannelMessage",n,c)}),r.setWantSubAudio(this.autoSubAudio&&this.wantSubAudio),r.setWantSubVideo(this.autoSubVideo&&this.wantSubVideo),r.setWantSubScreen(this.autoSubScreen&&this.wantSubScreen),r.setRemoteDefaultVideoStreamType(this.defaultStreamType),r.setAudioMuted(this.audioMuted),(this.autoSubAudio||this.autoSubVideo||this.autoSubScreen)&&r.updateSubscribe(i),r}onRemoteDeviceStatusChange(e,t){e===Ee.MuteAudio?this.emit("userAudioMuted",t,!0):e===Ee.UnmuteAudio?this.emit("userAudioMuted",t,!1):e===Ee.MuteVideo?this.emit("userVideoMuted",t,!0):e===Ee.UnmuteVideo?this.emit("userVideoMuted",t,!1):e===Ee.MuteScreen?this.emit("userScreenMuted",t,!0):e===Ee.UnmuteScreen&&this.emit("userScreenMuted",t,!1)}onRemoteStatReport(e,t,i){this.emit(Ee.PullStreamStats,e,t,i)}onSubscribeExceeds(e,t){this.emit(Ee.RtsSubscribeExceeds,e,t)}removeLeftUser(e){return I(this,null,function*(){e.userid&&this.userMap[e.userid]&&(yield this.userMap[e.userid].clear(!1),delete this.userMap[e.userid])})}diffUsers(e){const t=[],i=[];e.forEach(n=>{n.userid&&(this.userMap[n.userid]?i.push(n):t.push(n))});const r=Object.keys(this.userMap).filter(n=>!e.find(c=>c.userid===n)).map(n=>({userid:n,reason:"",leavecode:Rr.AliRtcUserOfflineQuit}));return{joinList:t,leaveList:r,presentList:i}}getRemoteUser(e){return this.userMap[e]}updateRemoteUserDeviceStatus(e){e&&e.userid&&this.userMap[e.userid]&&this.userMap[e.userid].updateRemoteUserDeviceStatus(e.status)}updateAudioWant(e,t){const i=this.userMap[e];if(!i)throw new O(U.ERR_INNER,`no remote user(${e}) founded`);i.setWantSubAudio(t),t?i.updateSubscribe(be.User):i.stopSubscribe({audio:!0})}updateVideoWant(e,t){const i=this.userMap[e];if(!i)throw new O(U.ERR_INNER,`no remote user(${e}) founded`);i.setWantSubVideo(t),t?i.updateSubscribe(be.User):i.stopSubscribe({video:!0})}updateScreenWant(e,t){const i=this.userMap[e];if(!i)throw new O(U.ERR_INNER,`no remote user(${e}) founded`);i.setWantSubScreen(t),t?i.updateSubscribe(be.User):i.stopSubscribe({screen:!0})}stopIndication(){this.indicationTimer&&window.clearInterval(this.indicationTimer)}startIndication(e){this.stopIndication(),this.indicationTimer=window.setInterval(()=>{const t=this.remoteUsers.map(i=>({userId:i.userId,volume:i.getAudioLevel()||0}));t.unshift({userId:"",volume:this.self.getAudioLevel()||0}),this.emit("audioVolume",t)},e)}setEnableDualVideoStream(e,t){if(!this.dualVideoPlugin)return;t&&this.dualVideoPlugin.setOptions(t);const i=this.pluginManager.has(this.dualVideoPlugin.name);e?!i&&this.pluginManager.add(this.dualVideoPlugin):i&&this.pluginManager.remove(this.dualVideoPlugin.name)}setAudioVolume(e){var t;(t=this.audioMixerPlugin)==null||t.setOptions(e)}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.stopIndication(),e>0&&this.startIndication(e),this.audioVolumeIndicationInterval=e,this.remoteUsers.forEach(t=>{t.enableAudioVolumeIndication(e)}),this.self.enableAudioVolumeIndication(e))}setPlayoutVolume(e){this.playoutVolume=e,this.remoteUsers.forEach(t=>{t.setPlayoutVolume(e)})}refreshAuthInfo(e){this.authInfo&&(this.authInfo=G(G({},this.authInfo),e)),e.userId&&this.self.refreshUserInfo(e.userId)}setEnableMediaExtensionMsg(e){this.rtsManager.setEncodedInsertableStreams(e)}setAudioRedEnabled(e){this.rtsManager.setAudioRedEnabled(e)}setVideoCodec(e){this.rtsManager.changeVideoCodec(e)}setParameter(e){var i,r,n,c;const t=JSON.parse(e);Object.keys(t).forEach(o=>{const d=this.parameter[o],h=t[o];this.parameter[o]=typeof d=="object"&&typeof h=="object"?G(G({},d),h):h}),t.enableBlankAudio===!0?(this.blankAudioPlugin||(this.blankAudioPlugin=new rc),this.pluginManager.has((i=this.blankAudioPlugin)==null?void 0:i.name)||this.pluginManager.add(this.blankAudioPlugin)):t.enableBlankAudio===!1&&(this.blankAudioPlugin&&this.pluginManager.remove((r=this.blankAudioPlugin)==null?void 0:r.name),(n=this.blankAudioPlugin)==null||n.clear(),this.blankAudioPlugin=void 0),t.audio&&((c=this.audio3AConfig)==null||c.loadFromLocalConfig(t.audio))}setupAudioProcessingPluginIfNeeded(){if(this.audio3AConfig.enableSoft3A){let e=0;this.audio3AConfig.enableSoft3ACheck&&(e=1e4),setTimeout(()=>{this.audioProcessorPlugin||(this.audioProcessorPlugin=new cc({dumpAudioData:this.audio3AConfig.dumpAudioData,aiaecOn:this.audio3AConfig.useAIAEC,slsReporter:this.slsReporter,enableSoft3ACheck:this.audio3AConfig.enableSoft3ACheck,useHardOnly:this.audio3AConfig.useHardOnly})),this.audioProcessorPlugin&&!this.pluginManager.has(this.audioProcessorPlugin.name)&&(this.audioProcessorPlugin.on("error",({message:t})=>{var i;V.error("audioProcessorPlugin error:",t),(i=this.self.audioTrack)==null||i.applyConstraints({echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0})}),this.pluginManager.add(this.audioProcessorPlugin))},e)}else this.audioProcessorPlugin&&(this.pluginManager.remove(this.audioProcessorPlugin.name),this.audioProcessorPlugin=void 0);this.self.setMicrophoneConstraints({echoCancellation:this.audio3AConfig.useSysEchoCancellation,noiseSuppression:this.audio3AConfig.useSysNoiseSuppression,autoGainControl:this.audio3AConfig.useSysAutoGainControl})}getParameter(){return JSON.stringify(this.parameter)}sendDataChannelMessage(e){return this.self.sendDataChannelMessage(e)}}g(Ge,"logName","BizControl"),tt([C()],Ge.prototype,"init",1),tt([C()],Ge.prototype,"leave",1),tt([C()],Ge.prototype,"clear",1),tt([C(H)],Ge.prototype,"addUser",1),tt([C()],Ge.prototype,"removeLeftUser",1),tt([C()],Ge.prototype,"diffUsers",1),tt([C(H)],Ge.prototype,"updateAudioWant",1),tt([C(H)],Ge.prototype,"updateVideoWant",1),tt([C(H)],Ge.prototype,"updateScreenWant",1),tt([C()],Ge.prototype,"stopIndication",1),tt([C()],Ge.prototype,"startIndication",1),tt([C(H)],Ge.prototype,"setEnableDualVideoStream",1),tt([C(H)],Ge.prototype,"setAudioVolume",1),tt([C()],Ge.prototype,"enableAudioVolumeIndication",1);var vi=(s=>(s[s.LiveTranscodingSingle=0]="LiveTranscodingSingle",s[s.LiveTranscodingMix=1]="LiveTranscodingMix",s))(vi||{}),Dr=(s=>(s[s.LiveTranscodingOrigin=0]="LiveTranscodingOrigin",s[s.LiveTranscodingAudio=1]="LiveTranscodingAudio",s[s.LiveTranscodingVideo=2]="LiveTranscodingVideo",s))(Dr||{}),ci=(s=>(s[s.LiveTranscodingCamera=0]="LiveTranscodingCamera",s[s.LiveTranscodingShareScreen=1]="LiveTranscodingShareScreen",s))(ci||{});const yi={0:"camera",1:"shareScreen"};var Mr=(s=>(s[s.LiveTranscoding_Profile_1IN_1080P=0]="LiveTranscoding_Profile_1IN_1080P",s[s.LiveTranscoding_Profile_1IN_720P=1]="LiveTranscoding_Profile_1IN_720P",s[s.LiveTranscoding_Profile_1IN_360P=2]="LiveTranscoding_Profile_1IN_360P",s[s.LiveTranscoding_Profile_2IN_1080P=3]="LiveTranscoding_Profile_2IN_1080P",s[s.LiveTranscoding_Profile_2IN_720P=4]="LiveTranscoding_Profile_2IN_720P",s[s.LiveTranscoding_Profile_2IN_360P=5]="LiveTranscoding_Profile_2IN_360P",s[s.LiveTranscoding_Profile_4IN_1080P=6]="LiveTranscoding_Profile_4IN_1080P",s[s.LiveTranscoding_Profile_4IN_720P=7]="LiveTranscoding_Profile_4IN_720P",s[s.LiveTranscoding_Profile_4IN_360P=8]="LiveTranscoding_Profile_4IN_360P",s[s.LiveTranscoding_Profile_9IN_1080P=9]="LiveTranscoding_Profile_9IN_1080P",s[s.LiveTranscoding_Profile_9IN_720P=10]="LiveTranscoding_Profile_9IN_720P",s[s.LiveTranscoding_Profile_9IN_360P=11]="LiveTranscoding_Profile_9IN_360P",s[s.LiveTranscoding_Profile_12IN_1080P=12]="LiveTranscoding_Profile_12IN_1080P",s[s.LiveTranscoding_Profile_12IN_720P=13]="LiveTranscoding_Profile_12IN_720P",s[s.LiveTranscoding_Profile_12IN_360P=14]="LiveTranscoding_Profile_12IN_360P",s[s.LiveTranscoding_Profile_16IN_1080P=15]="LiveTranscoding_Profile_16IN_1080P",s[s.LiveTranscoding_Profile_16IN_720P=16]="LiveTranscoding_Profile_16IN_720P",s[s.LiveTranscoding_Profile_16IN_360P=17]="LiveTranscoding_Profile_16IN_360P",s[s.LiveTranscoding_Profile_Mixed=9999]="LiveTranscoding_Profile_Mixed",s))(Mr||{});const gc={0:"1IN_1080P",1:"1IN_720P",2:"1IN_360P",3:"2IN_1080P",4:"2IN_720P",5:"2IN_360P",6:"4IN_1080P",7:"4IN_720P",8:"4IN_360P",9:"9IN_1080P",10:"9IN_720P",11:"9IN_360P",12:"12IN_1080P",13:"12IN_720P",14:"12IN_360P",15:"16IN_1080P",16:"16IN_720P",17:"16IN_360P",9999:"Mixed_Audio"};var Wi=(s=>(s[s.LiveTranscoding_HZ_48000=48e3]="LiveTranscoding_HZ_48000",s[s.LiveTranscoding_HZ_44100=44100]="LiveTranscoding_HZ_44100",s[s.LiveTranscoding_HZ_32000=32e3]="LiveTranscoding_HZ_32000",s[s.LiveTranscoding_HZ_16000=16e3]="LiveTranscoding_HZ_16000",s[s.LiveTranscoding_HZ_8000=8e3]="LiveTranscoding_HZ_8000",s))(Wi||{}),Ai=(s=>(s[s.LiveTranscodingNoBody=0]="LiveTranscodingNoBody",s[s.LiveTranscodingBody=1]="LiveTranscodingBody",s))(Ai||{}),Ri=(s=>(s[s.NOTO_SERIF_CJKSC_REGULAR=0]="NOTO_SERIF_CJKSC_REGULAR",s[s.ALIBABA_PUHUITI_REGULAR=1]="ALIBABA_PUHUITI_REGULAR",s[s.ALIBABA_PUHUITI_BOLD=2]="ALIBABA_PUHUITI_BOLD",s[s.ALIBABA_PUHUITI_Heavy=3]="ALIBABA_PUHUITI_Heavy",s[s.ALIBABA_PUHUITI_LIGHT=4]="ALIBABA_PUHUITI_LIGHT",s[s.ALIBABA_PUHUITI_MEDIUM=5]="ALIBABA_PUHUITI_MEDIUM",s))(Ri||{}),Lr=(s=>(s[s.LiveTranscodingOrigin=0]="LiveTranscodingOrigin",s[s.LiveTranscodingCrop=1]="LiveTranscodingCrop",s[s.LiveTranscodingFill=2]="LiveTranscodingFill",s))(Lr||{}),$i=(s=>(s[s.LiveTranscodingNormal=0]="LiveTranscodingNormal",s[s.LiveTranscodingVirtualBackground=1]="LiveTranscodingVirtualBackground",s))($i||{}),Nr=(s=>(s[s.LiveTranscodingState_IDLE=0]="LiveTranscodingState_IDLE",s[s.LiveTranscodingState_CONNNECT=1]="LiveTranscodingState_CONNNECT",s[s.LiveTranscodingState_RUNNING=2]="LiveTranscodingState_RUNNING",s[s.LiveTranscodingState_RECOVERING=3]="LiveTranscodingState_RECOVERING",s[s.LiveTranscodingState_FAILURE=4]="LiveTranscodingState_FAILURE",s[s.LiveTranscodingState_END=5]="LiveTranscodingState_END",s))(Nr||{}),Et=(s=>(s[s.LiveTranscodingErrorPublishOk=0]="LiveTranscodingErrorPublishOk",s[s.LiveTranscodingErrorStreamNotFound=17825793]="LiveTranscodingErrorStreamNotFound",s[s.LiveTranscodingErrorStreamAlreadyExist=17825794]="LiveTranscodingErrorStreamAlreadyExist",s[s.LiveTranscodingErrorInvalidParam=17825795]="LiveTranscodingErrorInvalidParam",s[s.LiveTranscodingErrorInternalError=17825796]="LiveTranscodingErrorInternalError",s[s.LiveTranscodingErrorRtmpServerError=17825797]="LiveTranscodingErrorRtmpServerError",s[s.LiveTranscodingErrorRtmpStreamUrlError=17825798]="LiveTranscodingErrorRtmpStreamUrlError",s[s.LiveTranscodingErrorPublishTimeout=17825799]="LiveTranscodingErrorPublishTimeout",s[s.LiveTranscodingErrorNotAuthorized=17825800]="LiveTranscodingErrorNotAuthorized",s))(Et||{}),xr=(s=>(s[s.TrascodingPublishTaskStatusStart=0]="TrascodingPublishTaskStatusStart",s[s.TrascodingPublishTaskStatusUpdate=1]="TrascodingPublishTaskStatusUpdate",s[s.TrascodingPublishTaskStatusStop=2]="TrascodingPublishTaskStatusStop",s))(xr||{}),it=(s=>(s[s.MPU_TASK_TRANSACTION_START=0]="MPU_TASK_TRANSACTION_START",s[s.MPU_TASK_TRANSACTION_UPDATE=1]="MPU_TASK_TRANSACTION_UPDATE",s[s.MPU_TASK_TRANSACTION_STOP=2]="MPU_TASK_TRANSACTION_STOP",s[s.MPU_TASK_TRANSACTION_LIST=3]="MPU_TASK_TRANSACTION_LIST",s[s.MPU_TASK_TRANSACTION_POLLING=4]="MPU_TASK_TRANSACTION_POLLING",s[s.MPU_TASK_TRANSACTION_ACKNOWLEDGE=5]="MPU_TASK_TRANSACTION_ACKNOWLEDGE",s[s.MPU_TASK_TRANSACTION_END=6]="MPU_TASK_TRANSACTION_END",s))(it||{});const fc={0:"/libra/v1/sdk/start-task",1:"/libra/v1/sdk/update-task",2:"/libra/v1/sdk/stop-task",3:"/libra/v1/sdk/list-task",4:"/libra/v1/sdk/polling",5:"/libra/v1/sdk/acknowledge",6:"/"};class Vr{constructor(a,e,t,i,r,n,c,o){g(this,"videoWidth");g(this,"videoHeight");g(this,"videoFramerate",20);g(this,"videoBitrate",2e3);g(this,"videoGop",30);g(this,"audioSamplerate",Wi.LiveTranscoding_HZ_44100);g(this,"audioBitrate",500);g(this,"audioChannels",1);this.videoWidth=a,this.videoHeight=e,t&&(this.videoFramerate=t),i&&(this.videoBitrate=i),r&&(this.videoGop=r),n&&(this.audioSamplerate=n),c&&(this.audioBitrate=c),o&&(this.audioChannels=o)}}const Or=s=>((16711680&s)>>16)+(65280&s)+((255&s)<<16),pt=(s=0,a)=>{if(a==0)return 0;let e=s/a;return e<0&&(e=0),e>1&&(e=1),e};class Ki{constructor(a,e,t){g(this,"mixMode",vi.LiveTranscodingSingle);g(this,"singleParam");g(this,"mixParam");a&&(this.mixMode=a),e&&(this.singleParam=e),t&&(this.mixParam=t)}toJson(a,e,t,i,r){const n={appid:e.appId,channelid:e.channelId};if(a===it.MPU_TASK_TRANSACTION_POLLING||a===it.MPU_TASK_TRANSACTION_LIST||a===it.MPU_TASK_TRANSACTION_ACKNOWLEDGE)return a===it.MPU_TASK_TRANSACTION_ACKNOWLEDGE&&(n.messageid=r),n;if(n.taskid=t,a!==it.MPU_TASK_TRANSACTION_STOP){if(n.mixmode=this.mixMode,i&&(n.streamurl=i),this.mixMode===vi.LiveTranscodingSingle){const c=this.singleParam;if(c){n.streamtype=c.streamType,c.sourceType===ci.LiveTranscodingShareScreen?n.sourcetype=yi[c.sourceType]:n.sourcetype=yi[ci.LiveTranscodingCamera];const o=[];c.userId&&o.push(c.userId),n.subspecusers=o}}else if(a===it.MPU_TASK_TRANSACTION_START||a===it.MPU_TASK_TRANSACTION_UPDATE){const c=this.mixParam;if(c){c.taskProfile&&(n.taskprofile=gc[c.taskProfile]);const o=c.encodeParam||new Vr(1280,720);let d=o.videoWidth,h=o.videoHeight;const l={};Object.keys(o).forEach(u=>{const f=o[u];f>0&&(l[u.toLowerCase()]=f)}),l.lowbitratehighquality=0,n.encodeparam=l,n.backgrounds=c.backgrounds.map(u=>u.toJson(d,h)),n.watermarks=c.watermarks.map(u=>u.toJson(d,h)),n.clockwidgets=c.clockWidgets.map(u=>u.toJson(d,h));const p=c.users.map(u=>u.userId);n.subspecusers=[...new Set(p)],n.layouts=[{audiomixcount:c.users.length,panes:c.users.map((u,f)=>u.toJson(f,d,h,c.mediaProcessMode))}],n.layoutids=["0"],n.cropmode=c.cropMode,n.backgroundcolor=Or(c.backgroundColor),n.taskmode=c.mediaProcessMode}}}return n}}const Ur=s=>I(this,null,function*(){const a=new Uint8Array(160).fill(170),e=new TextEncoder().encode(s),t=yield window.crypto.subtle.importKey("raw",a,{name:"HMAC",hash:{name:"SHA-1"}},!1,["sign"]),i=yield window.crypto.subtle.sign("HMAC",t,e);return Array.from(new Uint8Array(i)).map(r=>r.toString(16).padStart(2,"0")).join("")});class Sc{constructor(a){g(this,"authInfo");g(this,"slsReporter");this.slsReporter=a}doRequest(a,e){var c;const t=this.authInfo;if(!t)return Promise.reject(Et.LiveTranscodingErrorInvalidParam);const i=fc[a],r={appid:t.appId,userid:t.userId,channelid:t.channelId,timestamp:t.timestamp,token:t.token,nonce:t.nonce?t.nonce:"",requestid:nt.createCallid(),tokensid:!1,session:(c=t.sessionId)!=null?c:nt.createCallid()},n=Object.keys(r).map(o=>`${o}=${encodeURIComponent(r[o])}`).join("&");return fetch(`https://gw.rtn.aliyuncs.com${i}?${n}`,{method:"POST",headers:{"Content-Type":"application/json; charset=UTF-8"},body:JSON.stringify(e)}).then(o=>o.status!==200?(this.slsReporter.reportTranscodingError(o.status,e.taskid||""),Promise.reject(new O(U.ERR_INNER,`transcoding request failed, status: ${o.status}`))):o).catch(o=>Promise.reject(new O(U.ERR_INNER,`transcoding request failed, err: ${o.message}`)))}setAuthInfo(a){this.authInfo=a}clear(){this.authInfo=void 0}startPublishLiveStream(a,e){return I(this,null,function*(){if(!this.authInfo)return Promise.reject(Et.LiveTranscodingErrorInvalidParam);const t=yield Ur(a.split("?")[0]),i=it.MPU_TASK_TRANSACTION_UPDATE,r=e.toJson(i,this.authInfo,t,a);return this.doRequest(i,r)})}startPublishLiveStreamWithTaskId(a,e){return I(this,null,function*(){if(!this.authInfo)return Promise.reject(Et.LiveTranscodingErrorInvalidParam);const t=it.MPU_TASK_TRANSACTION_UPDATE,i=e.toJson(t,this.authInfo,a);return this.doRequest(t,i)})}updatePublishLiveStream(a,e){return I(this,null,function*(){if(!this.authInfo)return Promise.reject(Et.LiveTranscodingErrorInvalidParam);const t=yield Ur(a.split("?")[0]),i=it.MPU_TASK_TRANSACTION_UPDATE,r=e.toJson(i,this.authInfo,t,a);return this.doRequest(i,r)})}updatePublishLiveStreamWithTaskId(a,e){return I(this,null,function*(){if(!this.authInfo)return Promise.reject(Et.LiveTranscodingErrorInvalidParam);const t=it.MPU_TASK_TRANSACTION_UPDATE,i=e.toJson(t,this.authInfo,a);return this.doRequest(t,i)})}stopPublishLiveStream(a){return I(this,null,function*(){if(!this.authInfo)return Promise.reject(Et.LiveTranscodingErrorInvalidParam);const e=yield Ur(a.split("?")[0]),t=it.MPU_TASK_TRANSACTION_STOP,i=new Ki().toJson(t,this.authInfo,e,a);return this.doRequest(t,i)})}stopPublishLiveStreamWithTaskId(a){if(!this.authInfo)return Promise.reject(Et.LiveTranscodingErrorInvalidParam);const e=it.MPU_TASK_TRANSACTION_STOP,t=new Ki().toJson(e,this.authInfo,a);return this.doRequest(e,t)}refreshAuthInfo(a){this.authInfo&&this.setAuthInfo(G(G({},this.authInfo),a))}}const Qt=class Qt{constructor(){g(this,"ntpClock");this.ntpClock=new X.AliRTS.Clock}static getInstance(){return Qt.instance||(Qt.instance=new Qt),Qt.instance}now(){return this.ntpClock.now()}};g(Qt,"instance");let Br=Qt;const nn=()=>Br.getInstance(),{BrowserUtil:Hr,SystenUtil:on}=X.AliRTS;class cn{constructor(){g(this,"tracker");g(this,"param");g(this,"msgCacheArr",[]);g(this,"index",0);g(this,"stsOpt");g(this,"slsToken");g(this,"ossToken");g(this,"ntpClock");this.ntpClock=nn()}createTracker(){if(!this.tracker&&this.slsToken&&this.param){const a=this.slsToken;this.ossToken&&(this.param.ossbn=this.ossToken.bucket_name,this.param.ossep=this.ossToken.region_endpoint);const e=new pr({host:a.region_endpoint,project:a.project,logstore:a.log_store_stats}),t={accessKeyId:a.access_key_id,accessKeySecret:a.access_key_secret,securityToken:a.security_token,refreshSTSToken:()=>{this.slsToken&&(t.accessKeyId=this.slsToken.access_key_id,t.accessKeySecret=this.slsToken.access_key_secret,t.securityToken=this.slsToken.security_token)}};this.stsOpt=t;const i=fr(t);e.useStsPlugin(i),this.tracker=e,this.msgCacheArr.forEach((r,n)=>{var c,o;(o=this.tracker)==null||o.send(G(vt(G({},this.param),{stat_log_id:`${((c=this.param)==null?void 0:c.sesid)||"nosession"}-${n}`}),r))}),this.index=this.index+this.msgCacheArr.length,this.msgCacheArr=[]}}start(a){this.initParam(a),this.createTracker()}updateToken(a,e){this.slsToken=a,this.ossToken=e,this.createTracker()}stop(){this.tracker=void 0,this.param=void 0,this.msgCacheArr=[],this.index=0,this.stsOpt=void 0,this.slsToken=void 0,this.ossToken=void 0}sendReport(a){var t,i;let e;a.tm=Date.now();try{e=JSON.parse(JSON.stringify(G(vt(G({bt:Hr.browserName||"unknown",ntptm:this.ntpClock.now(),ntpofs:this.ntpClock.now()-Date.now()},this.param),{stat_log_id:`${((t=this.param)==null?void 0:t.sesid)||"nosession"}-${this.index}`}),a)))}catch(r){}e&&(this.tracker?((i=this.tracker)==null||i.send(e),this.index++):this.msgCacheArr.push(e))}initParam(a){let e="";try{e=(localStorage==null?void 0:localStorage.getItem("AliRtcUUID"))||"",e||(e=dt(),localStorage==null||localStorage.setItem("AliRtcUUID",e))}catch(t){}this.param||(this.param={apid:a.appId,usrid:a.userId,statsvrs:"0.6.1",evetid:0,sesid:a.sessionId,sessionId:a.sessionId,channelid:a.channelId,usrn:a.userId,osn:on.systemName,osv:on.systemVersion,deb:xo(),den:Mo(),udid:e,sdkvrs:Li,acs:"Unknown",cput:Ba(),dm:`${window.location.protocol}//${window.location.host}`,bt:Hr.browserName,bv:Hr.browserVersion,envir:"PRODUCT",args:"",instid:dt()})}}const Ae=(s,a=1,e=6e4,t=0)=>{let i=s;return i||(i=0),Math.min(e,Math.max(t,Math.round(i*a)))},mt=(s,a,e=2e7,t=0)=>{let i=a;(!a||a<0||a>1e4)&&(i=1e3);let r=s;return r||(r=0),Math.min(e,Math.max(t,Math.round(r/(i/1e3))))},qt=(s,a)=>{if(a===0||!a)return"0.00";let e=s;return(!e||e<0)&&(e=0),(e/a*100).toFixed(2)},dn=s=>s>=0&&s<=1?Ae(Math.floor(32767*s),1,32767):0,we=(s,a)=>{var t,i,r;let e=((t=s._last)==null?void 0:t[a])||0;return s.ssrc&&((i=s._last)!=null&&i.ssrc)&&s.ssrc!==((r=s._last)==null?void 0:r.ssrc)&&(e=0),((s==null?void 0:s[a])||0)-e},hn=(s,a)=>Ae(we(s,a),1e3,1e4),Xt=(s,a=2e7)=>Ae(s,1,a),_i=class _i{constructor(a){g(this,"engine");g(this,"logClient");g(this,"authInfo");g(this,"ntpClock");g(this,"customFields",{});this.logClient=new cn,this.engine=a,this.ntpClock=nn()}static getLogClient(){return this.staticClient||(this.staticClient=new cn),this.staticClient}static reportOSSUpload(a,e,t=0){_i.getLogClient().sendReport({errmsg:`${e}/${a}.log`,errtype:t,evetid:70017,sesid:a,sessionId:a,stat_log_id:`${a}-70017`})}setCustomFields(a){this.customFields=G(G({},this.customFields),a)}getCustomField(a){return this.customFields[a]}start(a){this.authInfo=a,this.logClient.start(a)}updateToken(a,e){this.logClient.updateToken(a,e),_i.getLogClient().updateToken(a,e)}stop(){this.logClient.stop()}reportPublishAudio3A(a,e,t,i){const r={};let n=JSON.parse(i);r.publevel=n.capture_audio_cur_level_db||0,r.eleakrate=n.echo_leak_rate||0,r.playbw=n.render_bandwidth||-1,r.capbw=n.capture_bandwidth||-1,r.diff=n.diff||0,r.leak=n.leak||0,this.log({evetid:10070,traceid:t,calid:a,args:this.data2String(G({calid:a,tckid:e||"audio3a",traceid:t},r))})}reportPublishMonitor(a,e,t,i,r){if(!t||r.length<=0)return;const n=t===M.Audio,c={ctm:Math.floor(r[0].timestamp||0),src:r[0].ssrc||"",codec:r[0]._codec||""},o=[],d=[],h=[],l=[],p=[],u=[],f=[],m=[],b=[],S=[],v=[],_=[],w=[],y=[],A=[],R=[],E=[],T=[],k=[];try{if(r.forEach(P=>{var x,de,ke,$,ge,Me;if(!P||!P.timestamp)return;const B=(x=P._last)!=null&&x.timestamp?P.timestamp-P._last.timestamp:1e3,q=we(P,"bytesSent"),Y=we(P,"headerBytesSent"),J=mt(Ae(q+Y,8,2e7),B);o.push(J);const z=mt(Ae(q,8,2e7),B);d.push(z);const Z=mt(Ae(Y,8,2e7),B);h.push(Z);const ee=we(P,"packetsSent"),pe=mt(ee,B);l.push(pe);const D=we(P,"packetsLost"),N=mt(D,B);p.push(N);const L=qt(D,ee);if(u.push(L),n)(de=P._source)!=null&&de.audioLevel&&f.push(dn(P._source.audioLevel)),m.push(0);else{b.push(hn(P,"totalEncodeTime")),S.push(Xt((ke=P._source)==null?void 0:ke.framesPerSecond,100)),v.push(Xt(($=P._source)==null?void 0:$.framesPerSecond,100)),_.push(Xt(P.framesPerSecond,100)),w.push(Xt((ge=P._source)==null?void 0:ge.height,4400)),y.push(Xt((Me=P._source)==null?void 0:Me.width,7700)),A.push(Xt(P.frameHeight,4400)),R.push(Xt(P.frameWidth,7700));const Re=we(P,"totalPacketSendDelay");E.push(Ae(Re,1/(D||1),2e3));const Ie=we(P,"qpSum");T.push(Ae(Ie,1/(P.framesPerSecond||1),51)),k.push(0)}}),c.sbr=o.join(","),c.mbrs=d.join(","),c.pbrs=h.join(","),c.ps=l.join(","),c.pl=p.join(","),c.plr=u.join(","),n){const P=(i==null?void 0:i.getSettings().sampleRate)||0;c.ailevel=f.join(","),c.arpc=m.join(","),c.arsr=P,c.aesr=P,c.publevel=-90,c.rawlevel=-90}else c.em=b.join(","),c.cfps=S.join(","),c.ifps=v.join(","),c.sfps=_.join(","),c.ih=w.join(","),c.iw=y.join(","),c.sh=A.join(","),c.sw=R.join(","),c.sd=E.join(","),c.aqp=T.join(","),c.caf=k.join(","),c.can=k.join(","),c.cav=d.join(","),c.ifimax=k.join(","),c.ifimin=k.join(","),c.efimax=k.join(","),c.efimin=k.join(","),c.sfimax=k.join(","),c.sfimin=k.join(","),c.apsnr=k.join(",")}catch(P){}this.log({evetid:10070,traceid:e,calid:a,args:this.data2String(G({calid:a,tckid:t,traceid:e},c))})}reportSubscribeMonitor(a,e,t,i,r){if(!i||!r||r.length<=0)return;const n=i===M.Audio,c={ctm:Math.floor(r[0].timestamp||0),src:r[0].ssrc||"",codec:r[0]._codec||""},o=[],d=[],h=[],l=[],p=[],u=[],f=[],m=[],b=[],S=[],v=[],_=[],w=[],y=[],A=[],R=[],E=[],T=[],k=[],P=[],B=[],q=[],Y=[],J=[],z=[],Z=[],ee=[],pe=[],D=[],N=[],L=[],x=[],de=[],ke=[];try{r.forEach($=>{var le,Fe;if(!$||!$.timestamp)return;const ge=(le=$._last)!=null&&le.timestamp?$.timestamp-$._last.timestamp:1e3,Me=we($,"bytesReceived"),Re=we($,"headerBytesReceived"),Ie=mt(Ae(Me+Re,8,2e7),ge);o.push(Ie);const fe=mt(Ae(Me,8,2e7),ge);d.push(fe);const _e=mt(Ae(Re,8,2e7),ge);h.push(_e);const he=we($,"packetsReceived"),Pe=mt(he,ge);l.push(Pe);const ye=we($,"packetsLost"),Je=mt(ye,ge);p.push(Je);const rt=qt(ye,he);u.push(rt);const ae=we($,"jitterBufferDelay"),re=we($,"jitterBufferEmittedCount");if($.jitterBufferDelay&&$.jitterBufferEmittedCount){const Q=Ae(ae,1e3/re,1e4);f.push(Q)}else f.push(0);const te=we($,"fecPacketsReceived");_.push(qt(te,he));const Se=we($,"retransmittedPacketsReceived"),Oe=he+ye-Se;if(b.push(qt(he-Se,Oe)),S.push(qt(ye,Oe)),m.push(qt(Se,Oe)),v.push(Oe),de.push(0),ke.push(""),n){y.push(dn($.audioLevel));const Q=((Ne,St)=>{var It,bt,Ft;return(((It=Ne==null?void 0:Ne._source)==null?void 0:It[St])||0)-(((Ft=(bt=Ne==null?void 0:Ne._last)==null?void 0:bt._source)==null?void 0:Ft[St])||0)})($,"synthesizedSamplesEvents");A.push(Q);const Le=hn($,"synthesizedSamplesDuration");R.push(Le);const st=qt(Le,ge);w.push(st),E.push(0)}else{const Q=(Fe=$._last)!=null&&Fe.totalInterFrameDelay?$.totalInterFrameDelay-$._last.totalInterFrameDelay:0;T.push(Ae(Q,1e3/($.framesDecoded||30),500)),k.push(Ae($.framesPerSecond,1,100)),P.push(we($,"framesReceived")),x.push(we($,"framesRendered")),B.push(Ae($.frameHeight,1,4400)),q.push(Ae($.frameWidth,1,7700));const Le=we($,"totalProcessingDelay");Y.push(Ae(Le,1e3/($.framesDecoded||30),12e4));const st=we($,"nackCount");z.push(st);const Ne=we($,"pliCount");J.push(Ne);const St=we($,"qpSum");Z.push(Ae(St,1/($.framesPerSecond||1),51)),ee.push(Ae($.framesDropped));const It=we($,"totalFreezesDuration");pe.push(Ae(It,1e3,3e4));const bt=we($,"jitterBufferEmittedCount"),Ft=we($,"jitterBufferDelay");Ft&&bt?D.push(Ae(Ft,1e3/bt,3e4)):D.push(0);const Ei=we($,"jitterBufferTargetDelay");Ei&&bt?N.push(Ae(Ei,1e3/bt,3e4)):N.push(0);const Gi=we($,"jitterBufferMinimumDelay");Gi&&bt?L.push(Ae(Gi,1e3/bt,3e4)):L.push(0)}}),c.rbr=o.join(","),c.mbrs=d.join(","),c.pbrs=h.join(","),c.pr=l.join(","),c.pl=p.join(","),c.plr=u.join(","),c.jd=f.join(","),c.fecr=_.join(","),c.retransr=m.join(","),c.baser=b.join(","),c.basel=S.join(","),c.recoverr=de.join(","),c.alll=S.join(","),c.totalc=v.join(","),n?(c.er=w.join(","),c.aolevel=y.join(","),c.asrc=E.join(","),c.scnt=A.join(","),c.sdura=R.join(",")):(c.dm=T.join(","),c.dfps=k.join(","),c.rfps=P.join(","),c.rh=B.join(","),c.rw=q.join(","),c.fpt=ke.join(","),c.ns=z.join(","),c.pliss=J.join(","),c.aqp=Z.join(","),c.ofimax=de.join(","),c.ofimin=de.join(","),c.dfimax=de.join(","),c.dfimin=de.join(","),c.rfimax=de.join(","),c.rfimin=de.join(","),c.vrstutter=pe.join(","),c.cdm=D.join(","),c.tdm=N.join(","),c.pdm=L.join(","),c.ofps=x.join(","),c.dfbd=ee.join(","))}catch($){}this.log({evetid:10080,traceid:t,rmtid:e,calid:a,args:this.data2String(G({calid:a,rmtid:e,tckid:i,traceid:t},c))})}reportNetworkMonitor(a){if(a.length<=0)return;const e=[],t=[],i=[],r=[],n=[],c=[],o=[],d=[],h=[],l=[];a.forEach((u,f)=>{var b;if(!u.timestamp)return;const m=(b=u._last)!=null&&b.timestamp?u.timestamp-u._last.timestamp:1e3;e.push(Ae(u.currentRoundTripTime,1e3)),t.push(Ae(u.availableOutgoingBitrate,8,2e8)),i.push(mt(Ae(u.bytesSent,8,2e7),m,25e6)),r.push(mt(Ae(u.bytesReceived,8,2e7),m,25e6)),n.push(0),c.push(0),f%5==0&&(o.push(""),d.push(""),h.push(""),l.push(""))});const p={ctm:Math.floor(a[0].timestamp||0),rtt:e.join(","),bsps:i.join(","),brps:r.join(","),cpu:o.join(","),mem:d.join(","),sysmem:h.join(","),systotalmem:l.join(","),audioonly:this.engine.isAudioOnly()?1:0};this.log({evetid:10071,args:this.data2String(G({asb:t.join(","),abms:n.join(","),vbms:c.join(",")},p))}),this.log({evetid:10081,args:this.data2String(G({},p))})}reportLoopAudioDelay(a,e){var f;const{AIAgent:t={},AIGrtn:i={},AIPub:r={},AISub:n={},pub:c={},sub:o={},grtn:d={}}=e||{};if(Object.keys(t).length===0)return;let h=0;h=Object.keys(d).length?(c.vTotalCost||0)+(c.upRTTHalf||0)+(d.totalCost||0)+(o.downRTTHalf||0)+(o.vTotalCost||0):(c.vEncPlugCost||0)+((c.timestampRecv||0)-(c.timestamp||0))+(o.vJitterBufferDelay||0)+(o.vDecPlugCost||0);const l={};let p=0;for(let m=0;m<10;m++){const b=`ngxRtcSeiCumulativeDelayKeyInternalRttHalf_${m}`,S=`ngxRtcSeiCumulativeDelayKeyGrtnNodeBefPacer_${m}`,v=`ngxRtcSeiCumulativeDelayKeyGrtnNodePacerCost_${m}`;if(!d.hasOwnProperty(b))break;p+=d[b]||0,p+=d[S]||0,p+=d[v]||0,l[`_gnd${m}`]=`gnd[${m}]: {${this.data2String({gnirh:d[b]||0,gnbp:d[S]||0,gnpc:d[v]||0})}}`}const u={};for(let m=0;m<10;m++){const b=`aigrtninternalrtthalf_${m}`,S=`aigrtnbeforepacer_${m}`,v=`aigrtnpacercost_${m}`;if(!i.hasOwnProperty(b))break;u[`_lgnd${m}`]=`lgnd[${m}]: {${this.data2String({gnirh:i[b]||0,gnbp:i[S]||0,gnpc:i[v]||0})}}`}this.log({evetid:10073,args:this.data2String(vt(G({tdlms:h+(t.aiagenttotalcost||0),_:`aiqud:{${this.data2String(vt(G({uid:((f=this.authInfo)==null?void 0:f.userId)||"",sid:r.aAIClientScentenceId||0,quct:65535*(r.aAIClientQuestionTimestampHEAD||0)+(r.aAIClientQuestionTimestampTAIL||0),anct:65535*(r.aAIClientAnswerTimestampHEAD||0)+(r.aAIClientAnswerTimestampTAIL||0),casc:r.aAIClientSourceCost||0,camc:r.aAIClientMixerCost||0,caec:r.aAIClientEncoderCost||0,cantc:r.aIClientNetsdkThrCost||0,caqtc:r.aIClientQosThrCost||0,capc:r.aIClientPacerCost||0,cuphr:r.aIClientUpRTTHalf||0},u),{qgac:0,ldhr:d.ngxRtcSeiCumulativeDelayKeyDownRttHalf_0||0,larc:n.aAILinuxReceiveCost||0,lanqc:n.aAILinuxNeteqCost||0,larsc:n.aAILinuxRemoteSourceCost||0,lapmc:n.aAILinuxPlayMixerCost||0,lapc:n.aAILinuxPlayCost||0,lsdnc:n.aIClinetSmartDenoise||0,asrc:t.aiasrcost||0,llmc:t.aillmcost||0,ttsc:t.aittscost||0,aamc:t.aimutecost||0,aatc:t.aiagenttotalcost||0}))}};`,ssrc:a,tpd:0,scc:r.aAIClientSourceCost||0,mxc:r.aAIClientMixerCost||0,encc:r.aAIClientEncoderCost||0,netc:r.aIClientNetsdkThrCost||0,qostc:r.aIClientQosThrCost||0,pacerc:r.aIClientPacerCost||0,uphr:r.aIClientUpRTTHalf||0},l),{agac:p,dnhr:o.downRTTHalf||0,tsd:o.vTotalCost||0,rcc:n.aAILinuxReceiveCost||0,nqc:n.aAILinuxNeteqCost||0,rscc:n.aAILinuxRemoteSourceCost||0,plmxc:n.aAILinuxPlayMixerCost||0,plc:n.aAILinuxPlayCost||0,dvd:0}))})}reportJoin(a,e,t=""){var l,p;const{start:i,rs:r=0,re:n=0}=e,c=Date.now()-i,o=n-r;let d=0;r&&(d=r-i);let h=0;n&&(h=n-r),this.log({evetid:10010,args:this.data2String({sesid:((l=this.authInfo)==null?void 0:l.sessionId)||"",joitm:c,rslt:a,gslbtm:0,dnstm:0,avcftm:0,gslbrslt:0,dnsrslt:0,avcfrslt:0,mode:2,jrtc:o,usrn:(p=this.authInfo)==null?void 0:p.userId,mgt:"cdn",cttc:d,iptc:h,ndn:1,gslbloc:1,ccag:0,ucag:0,cpg:0,upg:0,tid:t})})}reportJoinConnection(a){this.log({evetid:20002,args:this.data2String(G({transretrynum:0,ldnstc:0,tcptc:0,ssltc:0,url:""},a))})}reportLeave(a,e,t){this.log({evetid:10020,args:this.data2String({lvetm:a,rslt:e,tid:t})})}reportPublish(a,e,t,i,r,n,c,o,d,h,l){this.log({evetid:a?10032:10030,calid:t,args:this.data2String({calid:t,url:e,isvl:i?1:0,isvs:r?1:0,isvss:n?1:0,isaudio:c?1:0,rslt:o,tid:"123",pubtm:Date.now()-l,pctid:d,pubtid:h,isvp:0,isarecording:0,isad:0,isdc:0,pubretry:0,pbrttimes:0})})}reportPublishFirstPacket(a,e,t,i,r,n,c,o,d){const h=Date.now();this.log({evetid:a?10033:10031,calid:e,args:this.data2String({calid:e,fpst:h-t,tckid:n,est:t,pctid:c,pubtid:o,totaltm:h-r,jorm:d===yt.JOIN_CHANNEL?1:0,cptc:0,sptc:i-t,iptc:0,ipc2fptc:0,dctc:0,patc:0})})}reportUnpublish(a,e,t,i){var r;this.log({evetid:10040,args:this.data2String({calid:a,unpubtm:e,rslt:t,tid:i,sesid:((r=this.authInfo)==null?void 0:r.sessionId)||""})})}reportSubscribe(a,e,t,i,r,n,c,o,d,h){this.log({evetid:10050,calid:a,rmtid:e,args:this.data2String(G({calid:a,rmtid:e,isvl:t?1:0,isvs:i?1:0,isvss:r?1:0,isaudio:n?1:0,rslt:c,tid:o,subtm:d,isvp:0,isaplaying:0,isad:0,isdc:0,subretry:0,sbrttimes:0},h))})}reportSubscribeFirstPacket(a,e,t,i,r){this.log({evetid:a?10054:10051,calid:e,rmtid:t,args:this.data2String(G({calid:e,rmtid:t,tckid:i,cptc:0,iptc:0,ipc2fptc:0,dctc:0,patc:0},r))})}reportSubscribeFirstFrame(a,e,t,i,r){this.log({evetid:a?10055:10052,calid:e,rmtid:t,args:this.data2String(G({calid:e,rmtid:t,tckid:i},r))}),this.log({evetid:a?10058:10057,args:this.data2String(G({calid:e,rmtid:t,tckid:i},r))})}reportUnsubscribe(a,e,t,i,r){this.log({evetid:10060,calid:a,args:this.data2String({calid:a,rmtid:e,unsubtm:t,rslt:i,tid:r})})}reportMute(a,e,t){this.log({evetid:11030,args:this.data2String({calid:a,rmtid:"",enable:e?1:0,mt:t})})}reportRoleUpdate(a,e){this.log({evetid:11040,args:this.data2String({or:a||"",nr:e,ctm:Date.now(),rslt:0})})}reportRoleUpdateResult(a,e,t,i){this.log({evetid:11041,args:this.data2String({or:a||"",nr:e,ctm:t,rslt:i})})}reportVideoProfile(a){this.log({evetid:20074,args:this.data2String({pf:a,tckid:"sophon_camera_large"})})}reportScreenProfile(a){this.log({evetid:20074,args:this.data2String({pf:a,tckid:"sophon_screenshare"})})}reportError(a){this.log({evetid:10091,args:this.data2String({rslt:(a==null?void 0:a.code)||-1})})}reportWarning(a){this.log({evetid:10092,args:this.data2String({rslt:-1,errmsg:a})})}reportRoomServerEvent(a,e,t,i){this.log({evetid:20005,args:this.data2String({calid:"",rmtid:"",rt:a?0:1,dr:a?"s":"r",mt:e,ri:t,cs:1,srt:Date.now(),rspc:(i==null?void 0:i.code)||"",mc:JSON.stringify(i)})})}reportTranscodingError(a,e){this.log({evetid:10101,args:this.data2String({rslt:a,taskid:e})})}reportBye(a){var e;this.log({evetid:10093,args:this.data2String({rslt:a,sesid:((e=this.authInfo)==null?void 0:e.sessionId)||""})})}reportAudio(a,e,t){var i;this.log({evetid:80013,args:this.data2String({rslt:a?-1:0,adm:1,adt:0,adr:a?2:0,acms:e,adrpn:t})}),this.log({evetid:80014,args:this.data2String({sesid:((i=this.authInfo)==null?void 0:i.sessionId)||"",rslt:a?-1:0,adm:1,adt:0,adr:a?2:0,acms:e,adrpn:t})})}reportScreen(a,e){var t,i,r,n;this.log({evetid:90013,args:this.data2String({rslt:a?-1:0,vcms:e,vde:(t=a==null?void 0:a.code)!=null?t:-1,sesid:((i=this.authInfo)==null?void 0:i.sessionId)||""})}),this.log({evetid:90014,args:this.data2String({rslt:a?-1:0,vcms:e,vde:(r=a==null?void 0:a.code)!=null?r:-1,sesid:((n=this.authInfo)==null?void 0:n.sessionId)||""})})}reportScreenStop(a){this.log({evetid:90019,args:this.data2String({rslt:a?a.code||-1:0})}),this.log({evetid:90020,args:this.data2String({rslt:a?a.code||-1:0})})}reportSwitchCamera(a){var e;this.log({evetid:90025,args:this.data2String({rslt:0,td:a,sesid:((e=this.authInfo)==null?void 0:e.sessionId)||""})})}reportPublishProfile(a,e){this.log({evetid:10201,args:this.data2String(G({tckid:a},e))})}reportSDKCreated(a){this.log({evetid:70011,createtm:Date.now()-a,tm:a})}reportJoinInvoked(a){this.log({evetid:70012,jnnonce:a.nonce||"",jntoken:a.token||"",jntm:a.timestamp||""})}reportJoinResult(a){this.log({evetid:70013,rslt:a?a.code||-1:0,dnsrslt:0})}reportSTSResult(a,e){this.log({evetid:70014,rslt:a,asty:1,reqtm:Date.now()-e})}reportLeaveInvoked(){this.log({evetid:70015})}reportSEIMessage(a,e,t,i,r){this.log({evetid:40301,args:this.data2String({tm:Date.now(),sei_pt:a,sei_len:e,sei_rep:t,sei_delay:i,sei_key:r})})}reportConnectionLatencyEvent(a,e,t,i,r,n,c=!1){const o={ageniid:this.getCustomField("ageniid")},d=G({tm:r||Date.now(),ntptm:n||this.ntpClock.now(),stage:a,status:e,calid:t,tckid:i,cltp:1,http:c?1:0},o);this.log({evetid:12001,args:this.data2String(d)})}log(a){a&&(a.tm=new Date().getTime(),V.debug("[ConsoleLogger]","log",a),this.logClient.sendReport(a))}data2String(a){let e="";for(let t in a)e.length&&(e+="&"),e+=t.startsWith("_")?a[t]:`${t}=${a[t]}`;return e}};g(_i,"staticClient");let Fr=_i;const di=class di extends se{constructor(e){super();g(this,"ws");g(this,"socketStatus",0);g(this,"wsUrl","");g(this,"lastConnectStartTime",0);g(this,"maxConnectRetryCount",12);g(this,"connectRetryCount",0);g(this,"gotErr",!1);g(this,"closedByInvoke",!0);g(this,"isReconnecting",!1);g(this,"networkAvailableChecked",!0);g(this,"reconnectTimeoutId",0);this.maxConnectRetryCount=e!=null?e:12,this.onOpen=this.onOpen.bind(this),this.onMessage=this.onMessage.bind(this),this.onError=this.onError.bind(this),this.onClose=this.onClose.bind(this)}get connectUrl(){return this.wsUrl}get connectStatus(){return this.socketStatus}start(e){this.wsUrl=e,this.initWebSocket()}send(e){return!(!this.ws||this.socketStatus!==2)&&(this.ws.send(JSON.stringify(e)),!0)}close(){this.closedByInvoke=!0,this.uninitWebsocket()}reconnect(){this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=0),this.emit("onReconnectStart"),this.isReconnecting=!0,this.initWebSocket()}onOpen(e){V.info(`[${di.logName}]`,"onOpen"),this.socketStatus=2,this.connectRetryCount=0,this.networkAvailableChecked=!1,this.closedByInvoke=!1,this.gotErr=!1,this.isReconnecting=!1,this.emit("onOpen",e)}onMessage(e){this.emit("onMessage",e)}onError(e){this.isReconnecting&&this.emit("onReconnectFail",e),this.emit("onError",e),this.isReconnecting=!1,this.socketStatus!==2&&nt.isNetworkAvailable().then(t=>{t&&console.error(di.logName,"onError, Network is available, token may be invalid")})}onClose(e){return I(this,null,function*(){if(this.closedByInvoke)this.socketStatus=0;else{if(V.info(`[${di.logName}]`,`onClose, code: ${e.code}, reason: ${e.reason}, status: ${status}, retryCount: ${this.connectRetryCount}`),(yield nt.isNetworkAvailable())&&!this.networkAvailableChecked)return this.reconnect(),void(this.networkAvailableChecked=!0);this.connectRetryCount||this.emit("onNetworkError"),!this.reconnectTimeoutId&&(this.connectRetryCount+=1,this.connectRetryCount>this.maxConnectRetryCount?this.emit("onConnectFail"):Date.now()-this.lastConnectStartTime>=5e3?this.reconnect():this.reconnectTimeoutId=window.setTimeout(()=>{this.reconnect()},5e3)),this.socketStatus=0,this.emit("onClose",e)}})}initWebSocket(){this.uninitWebsocket(),this.socketStatus=1,this.lastConnectStartTime=Date.now(),this.ws=new WebSocket(this.wsUrl),this.ws.addEventListener("open",this.onOpen),this.ws.addEventListener("message",this.onMessage),this.ws.addEventListener("error",this.onError),this.ws.addEventListener("close",this.onClose)}uninitWebsocket(){this.ws&&(this.ws.removeEventListener("open",this.onOpen),this.ws.removeEventListener("message",this.onMessage),this.ws.removeEventListener("error",this.onError),this.ws.removeEventListener("close",this.onClose),this.ws.readyState!==WebSocket.CLOSED&&this.ws.close(),this.ws=void 0,this.socketStatus=0)}};g(di,"logName","Socket");let jr=di;var zr={exports:{}};(function(s,a){(function(e,t){var i="function",r="undefined",n="object",c="string",o="major",d="model",h="name",l="type",p="vendor",u="version",f="architecture",m="console",b="mobile",S="tablet",v="smarttv",_="wearable",w="embedded",y="Amazon",A="Apple",R="ASUS",E="BlackBerry",T="Browser",k="Chrome",P="Firefox",B="Google",q="Huawei",Y="LG",J="Microsoft",z="Motorola",Z="Opera",ee="Samsung",pe="Sharp",D="Sony",N="Xiaomi",L="Zebra",x="Facebook",de="Chromium OS",ke="Mac OS",$=" Browser",ge=function(ae){for(var re={},te=0;te<ae.length;te++)re[ae[te].toUpperCase()]=ae[te];return re},Me=function(ae,re){return typeof ae===c&&Re(re).indexOf(Re(ae))!==-1},Re=function(ae){return ae.toLowerCase()},Ie=function(ae,re){if(typeof ae===c)return ae=ae.replace(/^\s\s*/,""),typeof re===r?ae:ae.substring(0,500)},fe=function(ae,re){for(var te,Se,Oe,le,Fe,Q,Le=0;Le<re.length&&!Fe;){var st=re[Le],Ne=re[Le+1];for(te=Se=0;te<st.length&&!Fe&&st[te];)if(Fe=st[te++].exec(ae))for(Oe=0;Oe<Ne.length;Oe++)Q=Fe[++Se],typeof(le=Ne[Oe])===n&&le.length>0?le.length===2?typeof le[1]==i?this[le[0]]=le[1].call(this,Q):this[le[0]]=le[1]:le.length===3?typeof le[1]!==i||le[1].exec&&le[1].test?this[le[0]]=Q?Q.replace(le[1],le[2]):t:this[le[0]]=Q?le[1].call(this,Q,le[2]):t:le.length===4&&(this[le[0]]=Q?le[3].call(this,Q.replace(le[1],le[2])):t):this[le]=Q||t;Le+=2}},_e=function(ae,re){for(var te in re)if(typeof re[te]===n&&re[te].length>0){for(var Se=0;Se<re[te].length;Se++)if(Me(re[te][Se],ae))return te==="?"?t:te}else if(Me(re[te],ae))return te==="?"?t:te;return re.hasOwnProperty("*")?re["*"]:ae},he={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},Pe={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[u,[h,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[u,[h,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[h,u],[/opios[\/ ]+([\w\.]+)/i],[u,[h,Z+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[u,[h,Z+" GX"]],[/\bopr\/([\w\.]+)/i],[u,[h,Z]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[u,[h,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[u,[h,"Maxthon"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer|sleipnir)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim(?:browser|boat|jet))[\/ ]?([\d\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|duckduckgo|klar|helio|(?=comodo_)?dragon)\/([-\w\.]+)/i,/(heytap|ovi|115)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[h,u],[/quark(?:pc)?\/([-\w\.]+)/i],[u,[h,"Quark"]],[/\bddg\/([\w\.]+)/i],[u,[h,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[u,[h,"UC"+T]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[u,[h,"WeChat"]],[/konqueror\/([\w\.]+)/i],[u,[h,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[u,[h,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[u,[h,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[u,[h,"Smart Lenovo "+T]],[/(avast|avg)\/([\w\.]+)/i],[[h,/(.+)/,"$1 Secure "+T],u],[/\bfocus\/([\w\.]+)/i],[u,[h,P+" Focus"]],[/\bopt\/([\w\.]+)/i],[u,[h,Z+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[u,[h,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[u,[h,"Dolphin"]],[/coast\/([\w\.]+)/i],[u,[h,Z+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[u,[h,"MIUI"+$]],[/fxios\/([\w\.-]+)/i],[u,[h,P]],[/\bqihoobrowser\/?([\w\.]*)/i],[u,[h,"360"]],[/\b(qq)\/([\w\.]+)/i],[[h,/(.+)/,"$1Browser"],u],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[h,/(.+)/,"$1"+$],u],[/samsungbrowser\/([\w\.]+)/i],[u,[h,ee+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[u,[h,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[h,"Sogou Mobile"],u],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[h,u],[/(lbbrowser|rekonq)/i,/\[(linkedin)app\]/i],[h],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[u,h],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[h,x],u],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i],[h,u],[/\bgsa\/([\w\.]+) .*safari\//i],[u,[h,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[u,[h,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[u,[h,k+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[h,k+" WebView"],u],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[u,[h,"Android "+T]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[h,u],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[u,[h,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[u,h],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[h,[u,_e,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[h,u],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[h,"Netscape"],u],[/(wolvic|librewolf)\/([\w\.]+)/i],[h,u],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[u,[h,P+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i],[h,[u,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[h,[u,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[f,"amd64"]],[/(ia32(?=;))/i],[[f,Re]],[/((?:i[346]|x)86)[;\)]/i],[[f,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[f,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[f,"armhf"]],[/windows (ce|mobile); ppc;/i],[[f,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[f,/ower/,"",Re]],[/(sun4\w)[;\)]/i],[[f,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[f,Re]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[d,[p,ee],[l,S]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr])[-\w]+)/i,/sec-(sgh\w+)/i],[d,[p,ee],[l,b]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[d,[p,A],[l,b]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[d,[p,A],[l,S]],[/(macintosh);/i],[d,[p,A]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[d,[p,pe],[l,b]],[/(?:honor)([-\w ]+)[;\)]/i],[d,[p,"Honor"],[l,b]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[d,[p,q],[l,S]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[d,[p,q],[l,b]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite|pro)?)(?: bui|\))/i],[[d,/_/g," "],[p,N],[l,b]],[/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[d,/_/g," "],[p,N],[l,S]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[d,[p,"OPPO"],[l,b]],[/\b(opd2\d{3}a?) bui/i],[d,[p,"OPPO"],[l,S]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[d,[p,"Vivo"],[l,b]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[d,[p,"Realme"],[l,b]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[d,[p,z],[l,b]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[d,[p,z],[l,S]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[d,[p,Y],[l,S]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[d,[p,Y],[l,b]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[d,[p,"Lenovo"],[l,S]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[d,/_/g," "],[p,"Nokia"],[l,b]],[/(pixel c)\b/i],[d,[p,B],[l,S]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[d,[p,B],[l,b]],[/droid.+; (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[d,[p,D],[l,b]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[d,"Xperia Tablet"],[p,D],[l,S]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[d,[p,"OnePlus"],[l,b]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[d,[p,y],[l,S]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[d,/(.+)/g,"Fire Phone $1"],[p,y],[l,b]],[/(playbook);[-\w\),; ]+(rim)/i],[d,p,[l,S]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[d,[p,E],[l,b]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[d,[p,R],[l,S]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[d,[p,R],[l,b]],[/(nexus 9)/i],[d,[p,"HTC"],[l,S]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[p,[d,/_/g," "],[l,b]],[/droid [\w\.]+; ((?:8[14]9[16]|9(?:0(?:48|60|8[01])|1(?:3[27]|66)|2(?:6[69]|9[56])|466))[gqswx])\w*(\)| bui)/i],[d,[p,"TCL"],[l,S]],[/(itel) ((\w+))/i],[[p,Re],d,[l,_e,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[d,[p,"Acer"],[l,S]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[d,[p,"Meizu"],[l,b]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[d,[p,"Ulefone"],[l,b]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[d,[p,"Energizer"],[l,b]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[d,[p,"Cat"],[l,b]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[d,[p,"Smartfren"],[l,b]],[/droid.+; (a(?:015|06[35]|142p?))/i],[d,[p,"Nothing"],[l,b]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron|infinix|tecno|micromax|advan)[-_ ]?([-\w]*)/i,/; (imo) ((?!tab)[\w ]+?)(?: bui|\))/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[p,d,[l,b]],[/(imo) (tab \w+)/i,/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[p,d,[l,S]],[/(surface duo)/i],[d,[p,J],[l,S]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[d,[p,"Fairphone"],[l,b]],[/(u304aa)/i],[d,[p,"AT&T"],[l,b]],[/\bsie-(\w*)/i],[d,[p,"Siemens"],[l,b]],[/\b(rct\w+) b/i],[d,[p,"RCA"],[l,S]],[/\b(venue[\d ]{2,7}) b/i],[d,[p,"Dell"],[l,S]],[/\b(q(?:mv|ta)\w+) b/i],[d,[p,"Verizon"],[l,S]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[d,[p,"Barnes & Noble"],[l,S]],[/\b(tm\d{3}\w+) b/i],[d,[p,"NuVision"],[l,S]],[/\b(k88) b/i],[d,[p,"ZTE"],[l,S]],[/\b(nx\d{3}j) b/i],[d,[p,"ZTE"],[l,b]],[/\b(gen\d{3}) b.+49h/i],[d,[p,"Swiss"],[l,b]],[/\b(zur\d{3}) b/i],[d,[p,"Swiss"],[l,S]],[/\b((zeki)?tb.*\b) b/i],[d,[p,"Zeki"],[l,S]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[p,"Dragon Touch"],d,[l,S]],[/\b(ns-?\w{0,9}) b/i],[d,[p,"Insignia"],[l,S]],[/\b((nxa|next)-?\w{0,9}) b/i],[d,[p,"NextBook"],[l,S]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[p,"Voice"],d,[l,b]],[/\b(lvtel\-)?(v1[12]) b/i],[[p,"LvTel"],d,[l,b]],[/\b(ph-1) /i],[d,[p,"Essential"],[l,b]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[d,[p,"Envizen"],[l,S]],[/\b(trio[-\w\. ]+) b/i],[d,[p,"MachSpeed"],[l,S]],[/\btu_(1491) b/i],[d,[p,"Rotor"],[l,S]],[/(shield[\w ]+) b/i],[d,[p,"Nvidia"],[l,S]],[/(sprint) (\w+)/i],[p,d,[l,b]],[/(kin\.[onetw]{3})/i],[[d,/\./g," "],[p,J],[l,b]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[d,[p,L],[l,S]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[d,[p,L],[l,b]],[/smart-tv.+(samsung)/i],[p,[l,v]],[/hbbtv.+maple;(\d+)/i],[[d,/^/,"SmartTV"],[p,ee],[l,v]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[p,Y],[l,v]],[/(apple) ?tv/i],[p,[d,A+" TV"],[l,v]],[/crkey/i],[[d,k+"cast"],[p,B],[l,v]],[/droid.+aft(\w+)( bui|\))/i],[d,[p,y],[l,v]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[d,[p,pe],[l,v]],[/(bravia[\w ]+)( bui|\))/i],[d,[p,D],[l,v]],[/(mitv-\w{5}) bui/i],[d,[p,N],[l,v]],[/Hbbtv.*(technisat) (.*);/i],[p,d,[l,v]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[p,Ie],[d,Ie],[l,v]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[l,v]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[p,d,[l,m]],[/droid.+; (shield) bui/i],[d,[p,"Nvidia"],[l,m]],[/(playstation [345portablevi]+)/i],[d,[p,D],[l,m]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[d,[p,J],[l,m]],[/\b(sm-[lr]\d\d[05][fnuw]?s?)\b/i],[d,[p,ee],[l,_]],[/((pebble))app/i],[p,d,[l,_]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[d,[p,A],[l,_]],[/droid.+; (glass) \d/i],[d,[p,B],[l,_]],[/droid.+; (wt63?0{2,3})\)/i],[d,[p,L],[l,_]],[/droid.+; (glass) \d/i],[d,[p,B],[l,_]],[/(pico) (4|neo3(?: link|pro)?)/i],[p,d,[l,_]],[/; (quest( \d| pro)?)/i],[d,[p,x],[l,_]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[p,[l,w]],[/(aeobc)\b/i],[d,[p,y],[l,w]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[d,[l,b]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[d,[l,S]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[l,S]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[l,b]],[/(android[-\w\. ]{0,9});.+buil/i],[d,[p,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[u,[h,"EdgeHTML"]],[/(arkweb)\/([\w\.]+)/i],[h,u],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[u,[h,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna|servo)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[h,u],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[u,h]],os:[[/microsoft (windows) (vista|xp)/i],[h,u],[/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i],[h,[u,_e,he]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[u,_e,he],[h,"Windows"]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[u,/_/g,"."],[h,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[h,ke],[u,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[u,h],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish|openharmony)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[h,u],[/\(bb(10);/i],[u,[h,E]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[u,[h,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[u,[h,P+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[u,[h,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[u,[h,"watchOS"]],[/crkey\/([\d\.]+)/i],[u,[h,k+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[h,de],u],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[h,u],[/(sunos) ?([\w\.\d]*)/i],[[h,"Solaris"],u],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[h,u]]},ye=function(ae,re){if(typeof ae===n&&(re=ae,ae=t),!(this instanceof ye))return new ye(ae,re).getResult();var te=typeof e!==r&&e.navigator?e.navigator:t,Se=ae||(te&&te.userAgent?te.userAgent:""),Oe=te&&te.userAgentData?te.userAgentData:t,le=re?function(Q,Le){var st={};for(var Ne in Q)Le[Ne]&&Le[Ne].length%2==0?st[Ne]=Le[Ne].concat(Q[Ne]):st[Ne]=Q[Ne];return st}(Pe,re):Pe,Fe=te&&te.userAgent==Se;return this.getBrowser=function(){var Q,Le={};return Le[h]=t,Le[u]=t,fe.call(Le,Se,le.browser),Le[o]=typeof(Q=Le[u])===c?Q.replace(/[^\d\.]/g,"").split(".")[0]:t,Fe&&te&&te.brave&&typeof te.brave.isBrave==i&&(Le[h]="Brave"),Le},this.getCPU=function(){var Q={};return Q[f]=t,fe.call(Q,Se,le.cpu),Q},this.getDevice=function(){var Q={};return Q[p]=t,Q[d]=t,Q[l]=t,fe.call(Q,Se,le.device),Fe&&!Q[l]&&Oe&&Oe.mobile&&(Q[l]=b),Fe&&Q[d]=="Macintosh"&&te&&typeof te.standalone!==r&&te.maxTouchPoints&&te.maxTouchPoints>2&&(Q[d]="iPad",Q[l]=S),Q},this.getEngine=function(){var Q={};return Q[h]=t,Q[u]=t,fe.call(Q,Se,le.engine),Q},this.getOS=function(){var Q={};return Q[h]=t,Q[u]=t,fe.call(Q,Se,le.os),Fe&&!Q[h]&&Oe&&Oe.platform&&Oe.platform!="Unknown"&&(Q[h]=Oe.platform.replace(/chrome os/i,de).replace(/macos/i,ke)),Q},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return Se},this.setUA=function(Q){return Se=typeof Q===c&&Q.length>500?Ie(Q,500):Q,this},this.setUA(Se),this};ye.VERSION="1.0.40",ye.BROWSER=ge([h,u,o]),ye.CPU=ge([f]),ye.DEVICE=ge([d,p,l,m,b,v,S,_,w]),ye.ENGINE=ye.OS=ge([h,u]),s.exports&&(a=s.exports=ye),a.UAParser=ye;var Je=typeof e!==r&&(e.jQuery||e.Zepto);if(Je&&!Je.ua){var rt=new ye;Je.ua=rt.getResult(),Je.ua.get=function(){return rt.getUA()},Je.ua.set=function(ae){rt.setUA(ae);var re=rt.getResult();for(var te in re)Je.ua[te]=re[te]}}})(typeof window=="object"?window:Pi)})(zr,zr.exports);var bc=zr.exports,He=(s=>(s.KEEPALIVE="keepalive",s.JOINCHANNEL="joinchannel",s.NOTIFYJOIN="notifyjoin",s.NOTIFYSTATUS="notifystatus",s.STATUSREPORT="statusreport",s.LEAVECHANNEL="leavechannel",s.NOTIFYLEAVE="notifyleave",s.NOTIFYPUBLISH="notifypublish",s.BYE="bye",s.RECONNECT="reconnect",s.PUBLISH="publish",s.REFRESHURL="refreshurl",s.UNSUBSCRIBE="unsubscribe",s.ROLEUPDATE="roleupdate",s))(He||{});class vc{constructor(a,e){g(this,"authInfo");g(this,"userName");g(this,"seqIndex",0);this.authInfo=a,this.userName=e}get roleAuth(){if(this.authInfo.role){const{timestamp:a,nonce:e,token:t,role:i}=this.authInfo;return{timestamp:a,nonce:e,token:t,tokenrole:i}}}get adaptInfo(){var e,t,i,r;let a=new bc.UAParser().getResult();return{os_name:((e=a.os.name)==null?void 0:e.replace(" ",""))+"_"+((t=a.browser.name)==null?void 0:t.replace(" ","")),device_name:((i=a.device.model)==null?void 0:i.replace(" ",""))||"",brand_name:((r=a.device.vendor)==null?void 0:r.replace(" ",""))||"",device_key:window.navigator.userAgent,os_version:a.browser.version||"",sdk_version:"7.1.7",version:"v1"}}refreshAuthInfo(a){this.authInfo=a}getSeqIndex(){return this.seqIndex}createKeepAlivePackage(){return this.createBaseSendPackage("keepalive")}createJoinPackage(a){let e=this.createBaseSendPackage("joinchannel");return e.header.displayName=this.userName,e.header.clientversion=nt.getVersionNumber().toString(),e.header.platform="web",this.roleAuth&&(e.data.auth=this.roleAuth),this.adaptInfo&&(e.data.adapt=this.adaptInfo),a&&(e.data=G(G({},e.data),a)),e}crateLeavePackage(){return this.createBaseSendPackage("leavechannel")}createStatusPackage(a){let e=this.createBaseSendPackage("statusreport");return e.header.displayName=this.userName,e.data.status=a,e}createPublishPackage(){let a=this.createBaseSendPackage("publish");return a.data.users=[{}],this.roleAuth&&(a.data.auth=this.roleAuth),a}createRoleUpdatePackage(){let a=this.createBaseSendPackage("roleupdate");return a.header.displayName=this.userName,a}createReconnectPackage(a){let e=this.createBaseSendPackage("reconnect");return e.header.displayName=this.userName,e.header.clientversion=nt.getVersionNumber().toString(),e.header.platform="web",e.data=G(G({},e.data),a!=null?a:{}),this.roleAuth&&(e.data.auth=this.roleAuth),e}createRefreshUrlPackage(){let a=this.createBaseSendPackage("refreshurl");return a.header.displayName=this.userName,a}createResponsePackage(a,e){return{version:1,code:200,tid:a,msgtype:e}}createBaseSendPackage(a){var e;return++this.seqIndex,{version:1,msgtype:a,tid:dt(),header:{appid:this.authInfo.appId,channelid:this.authInfo.channelId,sessionid:(e=this.authInfo.sessionId)!=null?e:"",userid:this.authInfo.userId},data:{seq:this.seqIndex}}}}const ct=class ct extends se{constructor(e,t,i,r,n,c){super();g(this,"authInfo");g(this,"userName");g(this,"channelProfile");g(this,"clientRole");g(this,"slsReporter");g(this,"wsClient");g(this,"packageCreater");g(this,"keepAliveTimer",0);g(this,"packageCache",new Map);g(this,"isFirstConnect",!0);g(this,"aliveChecker",0);g(this,"reconnectData");g(this,"joinChannelExtraData");this.authInfo=e,this.userName=t,this.packageCreater=new vc(e,t),this.channelProfile=i,this.clientRole=r,this.slsReporter=n,this.wsClient=new jr(c),this.wsClient.on("onOpen",this.onOpen.bind(this)),this.wsClient.on("onMessage",this.onMessage.bind(this)),this.wsClient.on("onError",this.onError.bind(this)),this.wsClient.on("onClose",this.onClose.bind(this)),this.wsClient.on("onConnectFail",this.onConnectFail.bind(this)),this.wsClient.on("onAuthInvalid",this.onAuthInvalid.bind(this)),this.wsClient.on("onNetworkError",this.onNetworkError.bind(this)),this.wsClient.on("onReconnectStart",this.onReconnectStart.bind(this)),this.wsClient.on("onReconnectFail",this.onReconnectFail.bind(this))}get retryCount(){return this.wsClient.connectRetryCount}start(e,t){this.joinChannelExtraData=t,this.wsClient.start(e)}startKeepAlive(){this.keepAliveTimer===0&&(this.keepAliveTimer=window.setInterval(()=>{let e=this.packageCreater.createKeepAlivePackage();this.sendPackage(e)},5e3)),this.checkAlive()}stopKeepAlive(){this.keepAliveTimer!==0&&(clearInterval(this.keepAliveTimer),this.keepAliveTimer=0),this.aliveChecker&&(window.clearTimeout(this.aliveChecker),this.aliveChecker=0)}sendPkgCache(){this.packageCache.forEach(e=>{this.wsClient.send(e)})}leave(){let e=this.packageCreater.crateLeavePackage();this.sendPackage(e)}reportStatus(e){let t=this.packageCreater.createStatusPackage(e);this.sendPackage(t)}publish(e){const d=e,{l1ip:t}=d,i=jt(d,["l1ip"]);let r=this.packageCreater.createPublishPackage();r.data.users=[],r.data.l1ip=t,i.subscribe.signal=this.wsClient.connectUrl;const{tracks:n,resume:c}=i;let o="7.1.7";o&&(o=o.split("-")[0]),n.forEach(h=>{const{codec:l,ssrc:p}=h;h.userdata=JSON.stringify({sdk_version:o,codec:l}),h.ssrc=`${p}`,c&&(h.attr={reason:"reconnect"})}),r.data.users.push(i),this.sendPackage(r)}roleUpdate(e){let t=this.packageCreater.createRoleUpdatePackage();t.data.clientrole=e,this.sendPackage(t)}refreshUrl(e){const t=this.packageCreater.createRefreshUrlPackage();t.data=G(vt(G({},t.data),{sessionid:t.header.sessionid}),e),this.sendPackage(t)}refreshAuthInfo(e){this.authInfo=e,this.packageCreater.refreshAuthInfo(e)}close(){V.info(`[${ct.logName}] close`),this.stopKeepAlive(),this.wsClient.off("onOpen",this.onOpen.bind(this)),this.wsClient.off("onMessage",this.onMessage.bind(this)),this.wsClient.off("onError",this.onError.bind(this)),this.wsClient.off("onClose",this.onClose.bind(this)),this.wsClient.off("onConnectFail",this.onConnectFail.bind(this)),this.wsClient.off("onAuthInvalid",this.onAuthInvalid.bind(this)),this.wsClient.off("onReconnectStart"),this.wsClient.off("onReconnectFail"),this.wsClient.close()}sendPackage(e){[He.KEEPALIVE,He.RECONNECT,He.JOINCHANNEL].includes(e.msgtype)||this.packageCache.set(e.tid,e),this.wsClient.send(e),e.msgtype!==He.KEEPALIVE&&this.slsReporter.reportRoomServerEvent(!0,e.msgtype,e.tid,e)}updateReconnectData(e){this.reconnectData=e}onOpen(){if(V.info(`[${ct.logName}] onOpen`),this.isFirstConnect){let e=this.packageCreater.createJoinPackage(this.joinChannelExtraData);e.data.configure={channelprofile:this.channelProfile},this.channelProfile!==Pt.AliRtcSdkInteractiveLive&&this.channelProfile!==Pt.AliRtcSdkInteractiveWithLowLatencyLive||(e.data.configure.clientrole=this.clientRole),this.sendPackage(e)}else{this.stopKeepAlive();const e=this.packageCreater.createReconnectPackage(this.reconnectData);this.sendPackage(e)}}onMessage(e){try{let t=JSON.parse(e.data);this.packageCache.delete(t.tid),this.onRecvMessage(t),t!=null&&t.msgtype&&(t==null?void 0:t.msgtype)!==He.KEEPALIVE&&this.slsReporter.reportRoomServerEvent(!1,t.msgtype,t.tid,t)}catch(t){V.warn(`[${ct.logName}] onMessage err`,t,e)}}onError(e){V.warn(`[${ct.logName}] onError`,e),this.isFirstConnect&&this.onConnectFail()}onConnectFail(){V.warn(`[${ct.logName}] onConnectFail`);const e=new O(U.ERR_INNER,"Signaling connect failed.");this.isFirstConnect?this.emit("onJoinChannelResult",e):this.emit("onConnectFail",e)}onAuthInvalid(){V.warn(`[${ct.logName}] onAuthInvalid`),this.isFirstConnect&&this.emit("onAuthInvalid")}onNetworkError(){V.warn(`[${ct.logName}] onNetworkError`);const e=new O(U.ERR_INNER,"Network error, signaling connect failed.");this.emit("onNetworkError",e)}onClose(e){V.info(`[${ct.logName}] onClose`,e),this.stopKeepAlive()}onKeepAliveRsp(){this.emit("onKeepAliveRsp"),this.checkAlive()}onReconnectStart(){this.emit("onReconnectStart")}onReconnectFail(){this.emit("onReconnectFail",new O(U.ERR_INNER,"signaling reconnect failed."))}checkAlive(){window.clearTimeout(this.aliveChecker),this.aliveChecker=window.setTimeout(()=>{V.info(`[${ct.logName}] not alive, reconnect`),this.stopKeepAlive(),this.emit("onReconnectStart"),this.wsClient.reconnect()},3e4)}onRecvMessage(e){switch(e.msgtype!==He.KEEPALIVE&&V.info(`[${ct.logName}] recv msg: ${e.msgtype}`),e.msgtype){case He.JOINCHANNEL:this.onJoinResult(e);break;case He.KEEPALIVE:this.onKeepAliveRsp();break;case He.PUBLISH:this.onPublishResult(e);break;case He.NOTIFYJOIN:this.onNotifyJoin(e);break;case He.NOTIFYSTATUS:this.onNotifyStatus(e);break;case He.LEAVECHANNEL:this.onLeaveResult(e);break;case He.NOTIFYLEAVE:this.onNotifyLeave(e);break;case He.NOTIFYPUBLISH:this.onNotifyPublish(e);break;case He.STATUSREPORT:this.onStatusReport(e);break;case He.BYE:this.onBye(e);break;case He.ROLEUPDATE:this.onRoleUpdateResult(e);break;case He.REFRESHURL:this.onRefreshUrlResult(e);break;case He.RECONNECT:this.onReconnectResult(e);break;default:this.onUnknownMessage(e)}}onJoinResult(e){this.isFirstConnect=!1,this.emit("onJoinChannelResult",e)}onLeaveResult(e){this.emit("onLeaveResult",e.code,e.tid)}onPublishResult(e){this.emit("onPublishResult",e.code,e.tid,e.description)}onRoleUpdateResult(e){this.emit("onRoleUpdateResult",e.code,e.tid,e.description)}onRefreshUrlResult(e){this.emit("onRefreshUrlResult",e)}onReconnectResult(e){if(e.code===200)this.sendPkgCache(),this.startKeepAlive(),this.emit("onReconnectSuccess",e.data.users);else{const t=new O(U.ERR_INNER,`reconnect failed, code: ${e.code};description: ${e.description}`);e.code===403&&(t.code=403),this.emit("onReconnectFail",t),this.close()}}onNotifyJoin(e){let t=this.packageCreater.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e&&e.data&&e.data.users&&this.emit("onNotifyJoin",e.data.users)}onNotifyStatus(e){let t=this.packageCreater.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.status&&e.data.status.length&&this.emit("onNotifyStatus",e.data.status)}onNotifyLeave(e){let t=this.packageCreater.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.users&&e.data.users.length&&this.emit("onNotifyLeave",e.data.users)}onNotifyPublish(e){let t=this.packageCreater.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.users&&e.data.users.length&&this.emit("onNotifyPublish",e.data.users)}onStatusReport(e){this.emit("onStatusReport",e.code,e.tid,e.description)}onBye(e){this.stopKeepAlive(),this.emit("onBye",e.reason,e.description)}onUnknownMessage(e){this.emit("onUnknownMessage",e)}};g(ct,"logName","RSMessageCenter");let Wr=ct;var yc=Object.defineProperty,Ac=Object.getOwnPropertyDescriptor,$r=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?Ac(a,e):a,n=s.length-1;n>=0;n--)(i=s[n])&&(r=(t?i(a,e,r):i(r))||r);return t&&r&&yc(a,e,r),r};const Ji=(Ze=class extends se{constructor(e,t,i,r=kt.prod){super();g(this,"messageCenter");g(this,"authInfo");g(this,"userName");g(this,"channelProfile");g(this,"clientRole");g(this,"slsReporter");g(this,"reconnectData");g(this,"roomServerUri","");this.channelProfile=e,this.clientRole=t,this.slsReporter=i,this.reconnectData={role:{channelprofile:e,clientrole:t}};const n=r===kt.pre?Mi.pre:Mi.prod;this.roomServerUri=`wss://${n}/roomserver/v1/ws`}updateReconnectData(e){var t;this.reconnectData=e,(t=this.messageCenter)==null||t.updateReconnectData(this.reconnectData)}reset(){V.info("[roomsig] reset"),this.messageCenter&&(this.messageCenter.close(),this.messageCenter=void 0),this.authInfo=void 0}join(e,t,i,r){return I(this,null,function*(){return new Promise((n,c)=>{const o={};this.authInfo=e,this.userName=t,this.messageCenter=new Wr(e,t,this.channelProfile,this.clientRole,this.slsReporter,i),this.initMessageCenter(),this.messageCenter.once("onJoinChannelResult",h=>{var l,p,u;if(V.info(`[${Ze.logName}]`,"join result: ",h),o.taskretrynum=((l=this.messageCenter)==null?void 0:l.retryCount)||0,h.code==200){(p=this.messageCenter)==null||p.sendPkgCache(),(u=this.messageCenter)==null||u.startKeepAlive();let f=h.data;f.tid=h.tid,f.users=h.data.users,f.timestamp=h.timestamp,o.est&&(o.joinconnecttc=Date.now()-o.est),this.slsReporter.reportJoinConnection(o),n(f)}else this.reset(),c(this.handleSignalError(h.code,h.reason,U.ERR_JOIN_CHANNEL_FAILED))}),this.messageCenter.once("onAuthInvalid",()=>{this.reset(),c(new O(U.ERR_JOIN_BAD_TOKEN,"join failed because authentication failed"))}),V.info(`[${Ze.logName}]`,"start ws connecting roomserver and auto join when connected");const d={appid:this.authInfo.appId,callid:this.authInfo.sessionId,channelid:this.authInfo.channelId,userid:this.authInfo.userId,nonce:this.authInfo.nonce||"",timestamp:this.authInfo.timestamp,token:this.authInfo.token,authtype:"app",tid:dt()};e.role&&(d.tokenrole=e.role),o.est=Date.now(),this.messageCenter.start(this.roomServerUri+"?"+nt.queryingParam(d),r)})})}leave(){return V.info("[roomsig] leave .."),new Promise((e,t)=>{this.messageCenter?(this.messageCenter.on("onLeaveResult",(i,r)=>{V.info(`[${Ze.logName}]`,"recv leave response "+i),i===200?(this.updateReconnectData(),this.reset(),e({tid:r})):t(this.handleSignalError(i,"leave error"))}),V.info(`[${Ze.logName}]`,"send leave request"),this.messageCenter.leave()):(V.info(`[${Ze.logName}]`,"no message center, ok to leave"),e({tid:""}))})}publish(e){return new Promise((t,i)=>{var r;this.messageCenter?(this.messageCenter.once("onPublishResult",(n,c,o)=>{V.info(`[${Ze.logName}]`,"recv pubish response "+n),n===200?(this.updateReconnectData(vt(G({},this.reconnectData),{publish:{users:[e]}})),t({tid:c})):i(this.handleSignalError(n,`publish error, ${o}`))}),this.authInfo&&(e.sessionid=(r=this.authInfo.sessionId)!=null?r:""),e.callid||(e.callid=dt()),V.info(`[${Ze.logName}]`,"assign callid "+e.callid+" and send publish request"),this.messageCenter.publish(e)):i(this.handleSignalError(-1,"publish error, no message center"))})}roleUpdate(e){return new Promise((t,i)=>{this.messageCenter?(this.messageCenter.on("onRoleUpdateResult",(r,n,c)=>{var o,d;V.info(`[${Ze.logName}]`,"recv role update response "+r),r===200?((d=(o=this.reconnectData)==null?void 0:o.role)!=null&&d.clientrole&&(this.reconnectData.role.clientrole=e,this.updateReconnectData(this.reconnectData)),t({tid:n})):i(this.handleSignalError(r,`role update error, ${c}`))}),this.messageCenter.roleUpdate(e)):i(this.handleSignalError(-1,"role update error, no message center"))})}setChannelProfile(e){this.channelProfile=e}refreshUrl(e){return V.info(`[${Ze.logName}]`,"refreshUrl .."),new Promise((t,i)=>{this.messageCenter?(this.messageCenter.on("onRefreshUrlResult",r=>{const{code:n,description:c,data:o={}}=r||{};V.info("recv refresh url response "+n),n===200?t(o):i(this.handleSignalError(n,`refresh url error, ${c}`))}),V.info("send refresh url request"),this.messageCenter.refreshUrl(e)):i(this.handleSignalError(-1,"refresh url error, no message center"))})}reportStatus(e){return V.info(`[${Ze.logName}]`,"reportStatus "+e),new Promise((t,i)=>{this.messageCenter?(this.messageCenter.once("onStatusReport",(r,n)=>{r===200?t():i(new O(r,n))}),this.messageCenter.reportStatus(e)):i(new O(-1,"No messageCenter"))})}handleSignalError(e,t,i=U.ERR_INNER){return new O(i,`signal error: code - ${e}; description - ${t}`)}refreshAuthInfo(e){return I(this,null,function*(){var t;this.authInfo&&(this.authInfo=e,(t=this.messageCenter)==null||t.refreshAuthInfo(this.authInfo))})}initMessageCenter(){var e,t,i,r,n,c,o,d,h,l,p,u,f;(e=this.messageCenter)==null||e.on("onKeepAliveRsp",()=>{this.emit("onKeepAliveRsp")}),(t=this.messageCenter)==null||t.on("onNotifyJoin",m=>{this.emit("onNotifyJoin",m)}),(i=this.messageCenter)==null||i.on("onNotifyStatus",m=>{this.emit("onNotifyStatus",m)}),(r=this.messageCenter)==null||r.on("onNotifyLeave",m=>{this.emit("onNotifyLeave",m)}),(n=this.messageCenter)==null||n.on("onNotifyPublish",m=>{this.emit("onNotifyPublish",m)}),(c=this.messageCenter)==null||c.on("onBye",(m,b)=>{this.emit("onBye",m,b)}),(o=this.messageCenter)==null||o.on("onReconnectStart",()=>{this.emit("onReconnectStart")}),(d=this.messageCenter)==null||d.on("onReconnectSuccess",m=>{this.emit("onReconnectSuccess",m)}),(h=this.messageCenter)==null||h.on("onReconnectFail",m=>{this.emit("onReconnectFail",m)}),(l=this.messageCenter)==null||l.on("onConnectFail",m=>{this.emit("onConnectFail",m),this.reset()}),(p=this.messageCenter)==null||p.on("onNetworkError",m=>{this.emit("onNetworkError",m)}),(u=this.messageCenter)==null||u.on("onAuthInvalid",()=>{this.emit("onAuthInvalid")}),(f=this.messageCenter)==null||f.on("onUnknownMessage",m=>{this.emit("onUnknownMessage",m)})}},g(Ze,"logName","RoomServerSignaling"),Ze);$r([C()],Ji.prototype,"join",1),$r([C()],Ji.prototype,"publish",1),$r([C()],Ji.prototype,"roleUpdate",1);let Rc=Ji;const _c=6e5,wi=class wi extends se{constructor(e,t){super();g(this,"env");g(this,"authInfo");g(this,"timer");g(this,"slsReporter");g(this,"expiration",0);g(this,"skipTime",0);g(this,"requestToken",()=>I(this,null,function*(){if(this.skipTime=0,!this.authInfo)return;const{appId:e,channelId:t,userId:i,nonce:r="",token:n,timestamp:c,sessionId:o,role:d}=this.authInfo;let h="https://gw.rtn.aliyuncs.com";this.env===kt.pre&&(h="https://pgw.rtn.aliyuncs.com");const l=`${h}/gslb/v1/stsupdate?appid=${e}&channelid=${t}&userid=${i}&nonce=${r}&token=${n}&timestamp=${c}&session=${o}${d?`&tokenrole=${d}`:""}&slstoken=true&osstoken=true&tokensid=false`,p=Date.now();fetch(l).then(u=>u.json()).then(u=>{var f,m;if(u.code!==0)throw new Error;{const b=(f=u.data)==null?void 0:f.oss,S=(m=u.data)==null?void 0:m.sls;this.expiration=b.expiration||S.expiration,this.emit("onTokenUpdate",b,S),V.event(`[${wi.logName}]`,"getToken",b,S)}this.slsReporter.reportSTSResult(200,p)}).catch(u=>{this.slsReporter.reportSTSResult(-1,p),V.error(`[${wi.logName}]`,"getToken",u.message)})}));this.slsReporter=e,this.env=t}refreshAuthInfo(e){this.authInfo=e}startSTSUpdate(e){this.authInfo=e,this.requestToken(),this.timer&&clearInterval(this.timer),this.timer=window.setInterval(()=>{this.expiration&&Math.floor((Date.now()+9e5)/1e3)<this.expiration&&this.skipTime<12?this.skipTime+=1:this.requestToken()},_c)}clear(){this.timer&&clearInterval(this.timer)}};g(wi,"logName","StsManager");let Kr=wi;var wc=Object.defineProperty,Ec=Object.getOwnPropertyDescriptor;class Jr extends se{constructor(e,t,i,r=kt.prod){super();g(this,"signaling");g(this,"authInfo");g(this,"userName");g(this,"channelProfile");g(this,"clientRole");g(this,"env",kt.prod);g(this,"maxConnectRetryCount");g(this,"stsManager");g(this,"slsReporter");this.channelProfile=e,this.clientRole=t,this.env=r,this.slsReporter=i,this.stsManager=new Kr(i,r)}reset(){var e;V.info("[signalingmanager] reset"),(e=this.signaling)==null||e.reset(),this.stsManager.clear(),this.signaling=void 0,this.authInfo=void 0}join(e,t=e.userId,i,r,n){return this.maxConnectRetryCount=i,this.userName=t,new Promise((c,o)=>{this.signaling?o(new O(U.ERR_JOIN_ALREADY_JOINED,"already joined")):(V.info("[signalingmanager] create signaling"),this.signaling=new Rc(this.channelProfile,this.clientRole,this.slsReporter,this.env),this.initSignaling(),r&&(r.rs=Date.now()),this.signaling.join(e,t,i,n).then(d=>{this.authInfo=e,r&&(r.re=Date.now()),c(d)}).catch(d=>{this.reset(),o(d)}),this.stsManager.startSTSUpdate(e))})}retryJoin(){const e=this.authInfo;this.reset(),e&&this.join(e,this.userName,this.maxConnectRetryCount)}leave(){return new Promise((e,t)=>{this.signaling?this.signaling.leave().then(i=>{this.reset(),e(i)}).catch(i=>{t(i)}):e({tid:""})})}publish(e){return new Promise((t,i)=>{var r;this.signaling&&this.authInfo?(e.userid=this.authInfo.userId,e.displayname=(r=this.userName)!=null?r:this.authInfo.userId,this.signaling.publish(e).then(n=>{t(n)}).catch(n=>{i(n)})):i(new O(U.ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL,"no signaling"))})}reportStatus(e){return new Promise((t,i)=>{this.signaling?this.signaling.reportStatus(e).then(()=>{t()}).catch(r=>{i(r)}):i(new O(-1,"no signaling"))})}setClientRole(e){return I(this,null,function*(){const t=this.clientRole;if(!this.signaling)return void(this.clientRole=e);const i=Date.now();try{const r=yield this.signaling.roleUpdate(e);return this.slsReporter.reportRoleUpdateResult(t,e,Date.now()-i,0),r}catch(r){this.slsReporter.reportRoleUpdateResult(t,e,Date.now()-i,r.code||-1)}})}setChannelProfile(e){this.signaling?this.signaling.setChannelProfile(e):this.channelProfile=e}refreshUrl(e){return this.signaling?this.signaling.refreshUrl(e):Promise.reject(new O(U.ERR_SDK_INVALID_STATE,"should join first"))}refreshAuthInfo(e){return I(this,null,function*(){var t;try{this.authInfo&&(this.authInfo=G(G({},this.authInfo),e),(t=this.signaling)==null||t.refreshAuthInfo(this.authInfo),this.stsManager.refreshAuthInfo(this.authInfo))}catch(i){throw i}})}initSignaling(){var e,t,i,r,n,c,o,d,h,l,p,u,f,m;(e=this.signaling)==null||e.on("onKeepAliveRsp",this.onKeepAliveRsp.bind(this)),(t=this.signaling)==null||t.on("onNotifyJoin",this.onNotifyJoin.bind(this)),(i=this.signaling)==null||i.on("onNotifyStatus",this.onNotifyStatus.bind(this)),(r=this.signaling)==null||r.on("onNotifyLeave",this.onNotifyLeave.bind(this)),(n=this.signaling)==null||n.on("onNotifyPublish",this.onNotifyPublish.bind(this)),(c=this.signaling)==null||c.on("onBye",this.onBye.bind(this)),(o=this.signaling)==null||o.on("onReconnectStart",this.onReconnectStart.bind(this)),(d=this.signaling)==null||d.on("onReconnectSuccess",this.onReconnectSuccess.bind(this)),(h=this.signaling)==null||h.on("onReconnectFail",this.onReconnectFail.bind(this)),(l=this.signaling)==null||l.on("onConnectFail",this.onConnectFail.bind(this)),(p=this.signaling)==null||p.on("onNetworkError",this.onNetworkError.bind(this)),(u=this.signaling)==null||u.on("onAuthInvalid",this.onAuthInvalid.bind(this)),(f=this.signaling)==null||f.on("onError",this.onError.bind(this)),(m=this.signaling)==null||m.on("onUnknownMessage",this.onUnknownMessage.bind(this))}onKeepAliveRsp(){this.emit("onKeepAliveRsp")}onNotifyJoin(e){this.emit("onNotifyJoin",e)}onNotifyStatus(e){this.emit("onNotifyStatus",e)}onNotifyLeave(e){this.emit("onNotifyLeave",e)}onNotifyPublish(e){this.emit("onNotifyPublish",e)}onBye(e,t){this.emit("onBye",e,t)}onConnectFail(e){this.reset(),this.emit("onConnectFail",e)}onNetworkError(e){this.emit("onNetworkError",e)}onAuthInvalid(){}onReconnectStart(){this.emit("onReconnectStart")}onReconnectSuccess(e){this.emit("onReconnectSuccess",e)}onReconnectFail(e){this.emit("onReconnectFail",e)}onError(e){this.emit("onError",e)}onUnknownMessage(e){this.emit("onUnknownMessage",e)}}g(Jr,"logName","SignalingManager"),((s,a,e,t)=>{for(var i,r=t>1?void 0:t?Ec(a,e):a,n=s.length-1;n>=0;n--)(i=s[n])&&(r=(t?i(a,e,r):i(r))||r);t&&r&&wc(a,e,r)})([C(H)],Jr.prototype,"publish",1);class ln{constructor(a){g(this,"taskProfile");g(this,"encodeParam");g(this,"users",[]);g(this,"backgroundColor",0);g(this,"backgrounds",[]);g(this,"watermarks",[]);g(this,"clockWidgets",[]);g(this,"cropMode");g(this,"mediaProcessMode");this.taskProfile=a}}class un{constructor(a,e,t){g(this,"userId");g(this,"streamType");g(this,"sourceType");this.userId=a,this.streamType=e,this.sourceType=t}}class pn{constructor(a,e,t,i=0,r=16777215,n=Ri.NOTO_SERIF_CJKSC_REGULAR){g(this,"x");g(this,"y");g(this,"fontSize");g(this,"zOrder");g(this,"fontColor");g(this,"fontType");this.x=a,this.y=e,this.fontSize=t,this.zOrder=i,this.fontColor=r,this.fontType=n}toJson(a,e){return{x:pt(this.x,a),y:pt(this.y,e),fonttype:this.fontType,fontsize:this.fontSize,fontcolor:Or(this.fontColor),zorder:this.zOrder}}}var mn=(s=>(s[s.NOT_DISPLAY=0]="NOT_DISPLAY",s[s.ALWAYS=1]="ALWAYS",s[s.WHEN_NO_VIDEO=2]="WHEN_NO_VIDEO",s))(mn||{});class Gr{constructor(a,e,t,i,r,n=0,c=1,o=1){g(this,"url");g(this,"x");g(this,"y");g(this,"width");g(this,"height");g(this,"alpha");g(this,"display",1);g(this,"zOrder");this.url=a,this.x=e,this.y=t,this.width=i,this.height=r,this.zOrder=n,this.alpha=c,this.display=o}toJson(a,e){return{url:this.url,alpha:this.alpha,display:this.display,x:pt(this.x,a),y:pt(this.y,e),width:pt(this.width,a),height:pt(this.height,e),zorder:this.zOrder}}}g(Gr,"DisplayType",mn);class gn{constructor(a,e,t,i,r=0,n=16777215,c=Ri.NOTO_SERIF_CJKSC_REGULAR){g(this,"text");g(this,"x");g(this,"y");g(this,"fontSize");g(this,"zOrder");g(this,"fontColor");g(this,"fontType");this.text=a,this.x=e,this.y=t,this.fontSize=i,this.zOrder=r,this.fontColor=n,this.fontType=c}toJson(a,e){return{text:this.text,x:pt(this.x,a),y:pt(this.y,e),fonttype:this.fontType,fontsize:this.fontSize,fontcolor:Or(this.fontColor),zorder:this.zOrder}}}class fn{constructor(a,e,t,i,r,n=0,c){g(this,"userId");g(this,"x");g(this,"y");g(this,"width");g(this,"height");g(this,"zOrder");g(this,"sourceType");g(this,"segmentType",Ai.LiveTranscodingNoBody);g(this,"images",[]);g(this,"texts",[]);this.userId=typeof a=="number"?a.toString():a,this.x=e,this.y=t,this.width=i,this.height=r,this.zOrder=n,c&&(this.sourceType=c)}toJson(a,e,t,i){const r={paneid:a,majorpane:0,x:pt(this.x,e),y:pt(this.y,t),width:pt(this.width,e),height:pt(this.height,t),zorder:this.zOrder,userid:this.userId,images:this.images.map(n=>n.toJson(e,t)),texts:this.texts.map(n=>n.toJson(e,t))};return this.sourceType&&yi[this.sourceType]?r.sourcetype=yi[this.sourceType]:r.sourcetype=yi[ci.LiveTranscodingCamera],this.segmentType&&i===$i.LiveTranscodingVirtualBackground?r.segmenttype=this.segmentType:r.segmenttype=Ai.LiveTranscodingNoBody,r}}class Tc{constructor(a){g(this,"_updateables");g(this,"_useWebworker");g(this,"_inited");g(this,"_active");g(this,"_previousRAFTime");g(this,"_previousWorkerTime");g(this,"_webWorkerString");g(this,"_webWorker");g(this,"_intervalThreshold");g(this,"_rafId");this._updateables=[],this._useWebworker=!1,this._inited=!1,this._active=!1,this._previousRAFTime=void 0,this._previousWorkerTime=void 0,this._intervalThreshold=a&&a>0&&a<=60?1/a:.1,this._webWorkerString=`
132
+ `)});try{this.startConnect();const d=yield this.rts.subscribe(Er(r,this.preferredSubL1Ip),n);return this._pcTraceId=d.traceId,this.setConnected(!0),{traceId:d.traceId,stream:d}}catch(d){throw this.setConnected(!1),this.emit("disconnected"),O.fromRtsError(d)}})}subscribeAdd(e){return I(this,null,function*(){var n,c,o,d;const{remoteUser:t,options:i}=e,r=vt(G({url:t.streamUrl,subAudio:!!i.audio,subVideo:!(!i.screen&&!i.video)},this.getSubConfig(t.streamInfo,i)),{targetStream:i.screen?t.getScreenStream:t.getCameraStream});yield this.dcConnectingPromise;try{return(yield qa(h=>I(this,null,function*(){return yield this.dcConnectingPromise,h>0&&V.event(`[${Te.logName}]`,`subscribeAdd retry times: ${h}`),this.isConnected?this.rts.subscribeAdd([r]):Promise.reject()}),10,100,h=>{var l,p,u,f;return(h==null?void 0:h.errorCode)===15006||(h==null?void 0:h.errorCode)===15004&&((f=(u=(p=(l=h.extraInfo)==null?void 0:l.parsedData)==null?void 0:p.streams)==null?void 0:u[0])==null?void 0:f.res_code)===404}))[0]}catch(h){if(((d=(o=(c=(n=h==null?void 0:h.extraInfo)==null?void 0:n.parsedData)==null?void 0:c.streams)==null?void 0:o[0])==null?void 0:d.res_code)===508)return this.emit("subscribeexceeds"),null;throw O.fromRtsError(h)}})}subscribeDelete(e){return I(this,null,function*(){var n,c,o,d;const{remoteUser:t,options:i}=e,r=vt(G({url:t.streamUrl,subAudio:!!i.audio,subVideo:!(!i.screen&&!i.video)},this.getSubConfig(t.streamInfo,i)),{targetStream:i.screen?t.getScreenStream:t.getCameraStream});yield this.dcConnectingPromise;try{return V.event(`[${Te.logName}]`,"subscribeDeleteTracks",JSON.stringify({url:r.url,subAudio:r.subAudio,subVideo:r.subVideo,aMsid:r.aMsid,vMsid:r.vMsid})),(yield this.rts.subscribeDeleteTracks([r]))[0]}catch(h){if(((d=(o=(c=(n=h==null?void 0:h.extraInfo)==null?void 0:n.parsedData)==null?void 0:c.streams)==null?void 0:o[0])==null?void 0:d.res_code)===404)return;throw O.fromRtsError(h)}})}subscribeStop(e){return I(this,null,function*(){var t,i,r,n;try{yield this.rts.subscribeStop([{url:e}])}catch(c){if(((n=(r=(i=(t=c==null?void 0:c.extraInfo)==null?void 0:t.parsedData)==null?void 0:i.streams)==null?void 0:r[0])==null?void 0:n.res_code)===404)return;throw O.fromRtsError(c)}})}subscribeAddDataChannel(e){return I(this,null,function*(){yield this.dcConnectingPromise;const t=yield this.rts.subscribeAddDatachannel({signalUrl:e,url:e,label:M.Data,msid:M.Data}),i=t==null?void 0:t.datachannel;if(i&&i.send){const r=new ArrayBuffer(4);new DataView(r).setUint8(0,240),i.send(r)}return i})}subscribeStopDatachannel(e,t){return I(this,null,function*(){let i;try{i=yield this.rts.subscribeStopDatachannel({url:e,datachannel:t})}catch(r){}return t==null||t.dispose(),i})}publish(n,c){return I(this,arguments,function*(e,t,i=!1,r=yt.MANUAL){let o,d="";if(this.connecting&&(yield this.connectingPromise),this.connected){yield this.dcConnectingPromise;let h,l=!1;const{audio:p,video:u,videoSmall:f,screen:m}=this.localStreamManager.publishStreams;p&&(d=yield this.publishAdd(e,p,t,{aMsid:M.Audio},i),l=!0,h=M.Audio,yield xt(100)),u&&(d=yield this.publishAdd(e,u,t,{vMsid:M.VideoLarge},i),l=!1,h=M.VideoLarge,yield xt(100)),f&&(d=yield this.publishAdd(e,f,t,{vMsid:M.VideoSmall},i),l=!1,h=M.VideoSmall,yield xt(100)),m&&(d=yield this.publishAdd(e,m,t,{isScreen:!0,vMsid:M.Screen},i),l=!1,h=M.Screen),h&&(yield this.waitPublishSender(e,l,h))}else{const h=yield this.httpPublish(e,t,i,r);d=h.traceId,o=h.l1ip}return{traceId:d,l1ip:o}})}reportSubscribeLatency(e,t,i,r){const n=[];e.audio&&n.push(e.aMsid||M.Audio),e.video?n.push(e.vMsid||M.VideoLarge):e.screen&&n.push(M.Screen),n.forEach(c=>{this.slsReporter.reportConnectionLatencyEvent(ot.HANDLE_SUB_TASK,ht.START,t,c,i,0,r),this.slsReporter.reportConnectionLatencyEvent(ot.HANDLE_SUB_TASK,ht.END,t,c,Date.now(),0,r)})}subscribe(e,t,i,r,n){return I(this,null,function*(){let c=!1;const{options:o,remoteUser:d}=e;if(o.video&&o.screen)throw new O(U.ERR_INNER,"subscribe error, video and screen cannot be subscribed at the same time");let h;this.connecting&&(yield this.connectingPromise);let l=Date.now();this.connected?h=yield this.subscribeAdd(e):(c=!0,h=yield this.httpSubscribe(e)),this.reportSubscribeLatency(o,i,l,c);const p=Date.now();let u=M.VideoLarge,f=o.video||o.screen,m=o.audio;o.video&&o.vMsid?u=o.vMsid:o.screen&&(u=M.Screen);let b=0,S=0,v=0;const _=((w,y)=>{let A=0;const R=()=>{let E;return m&&!b&&(E=this.rts.getSubscribeAudioStats(d.streamUrl).then(T=>{if(T.packetsReceived>0)b=Date.now(),V.debug(`[${Te.logName}]`,d.userId,"Stats 音频首包");else if(!f)return A<w&&(A++,new Promise(k=>setTimeout(()=>k(R()),y)));return!0})),f&&!v&&(E=this.rts.getSubscribeVideoStats(d.streamUrl,u).then(T=>(!S&&T.packetsReceived>0&&(S=Date.now(),V.debug(`[${Te.logName}]`,d.userId,"Stats 视频首包")),T.framesDecoded>0?(v=Date.now(),V.debug(`[${Te.logName}]`,d.userId,"Stats 视频首帧数据"),!0):A<w?(A++,new Promise(k=>setTimeout(()=>k(R()),y))):(V.event(`[${Te.logName}]`,d.userId,"尝试获取首帧数据失败"),!1)))),Promise.resolve(E)};return R()})(20,100);return _.then(()=>{S&&this.slsReporter.reportSubscribeFirstPacket(t===be.Resume,i,r,u,{fprt:S-l,ifsprtc:v?v-l:0,ajsub:t===be.Join?1:0,pctid:this.pcTraceId,subtid:(h==null?void 0:h.traceId)||"",sstc:p-l}),v&&this.slsReporter.reportSubscribeFirstFrame(t===be.Resume,i,r,u,{fvfrt:v-l,fp2fftc:v-S,ajsub:t===be.Join?1:0,tffrtc:t===be.Join?v-this.localJoinTime:v-n,pctid:this.pcTraceId,subtid:(h==null?void 0:h.traceId)||"",fvfdtc:v-l}),b&&(this.slsReporter.reportConnectionLatencyEvent(ot.FIRST_REMOTE,ht.DECODED,i,M.Audio,b),this.slsReporter.reportSubscribeFirstPacket(t===be.Resume,i,r,M.Audio,{fprt:b-l,ifsprtc:b-l,ajsub:t===be.Join?1:0,pctid:this.pcTraceId,subtid:(h==null?void 0:h.traceId)||"",sstc:p-l}))}),h.isHTTP=c,h.statsCheckPromise=_,h})}getSubscribeVideoStats(e,t){return I(this,null,function*(){return yield this.rts.getSubscribeVideoStats(e,t)})}getSubscribeAudioStats(e,t){return I(this,null,function*(){return yield this.rts.getSubscribeAudioStats(e,t)})}getStreamByMsid(e){return this.rts.commonController.streamManager.getStreamByMsid(e)}getDatachannelByMsid(e){return this.rts.commonController.streamManager.getDatachannelByMsid(e)}getPCStats(){return I(this,null,function*(){var e,t;return(t=(e=this.rts.commonController.peerCore)==null?void 0:e.pc)==null?void 0:t.getStats()})}sendSEI(e,t,i,r){return I(this,null,function*(){return this.rts.sendSEI({url:e,vMsid:M.VideoLarge,data:t,repeatCount:i,payloadType:r})})}},g(Te,"logName","RtsManager"),Te);Be([C(H)],xe.prototype,"startConnect",1),Be([C()],xe.prototype,"updatePublishingTracks",1),Be([C(H,H)],xe.prototype,"httpPublish",1),Be([C(H,H)],xe.prototype,"waitPublishSender",1),Be([C(([s,a,e])=>[s,JSON.stringify(e)],H)],xe.prototype,"publishAdd",1),Be([C(H,H)],xe.prototype,"publishDelete",1),Be([C(([s,a,e])=>[s,JSON.stringify(e)])],xe.prototype,"publishReplace",1),Be([C(H)],xe.prototype,"publishStop",1),Be([C(H)],xe.prototype,"publishAddDataChannel",1),Be([C(H)],xe.prototype,"publishStopDataChannel",1),Be([C()],xe.prototype,"unpublish",1),Be([C(zi,({traceId:s})=>s)],xe.prototype,"httpSubscribe",1),Be([C(zi,({traceId:s})=>s)],xe.prototype,"subscribeAdd",1),Be([C(zi)],xe.prototype,"subscribeDelete",1),Be([C(H)],xe.prototype,"subscribeStop",1),Be([C(H)],xe.prototype,"subscribeAddDataChannel",1),Be([C(H)],xe.prototype,"subscribeStopDatachannel",1),Be([C(H)],xe.prototype,"publish",1),Be([C(zi)],xe.prototype,"subscribe",1),Be([C()],xe.prototype,"sendSEI",1);let Yo=xe;class Cr{constructor(a=_r){g(this,"defaultProfile");g(this,"profile");g(this,"profileMap",new Map);g(this,"audioProfile");g(this,"contentHint");this.defaultProfile=G({},a)}updateProfile(a,e){this.profileMap.set(a,G(G(G({},this.defaultProfile),this.profileMap.get(a)||{}),e||{})),this.profile=a}get videoProfile(){return this.profile}updateAudioProfile(a){this.audioProfile=a}setContentHint(a,e){e&&(this.contentHint=e),this.contentHint&&a&&(a.contentHint=this.contentHint)}setVideoProfile(a,e,t=!1){return I(this,null,function*(){if(!this.profile)return;const i=this.profileMap.get(this.profile)||(e==null?void 0:e.VideoProfileMap.get(this.profile));if(i){if(!t&&a&&a.readyState==="live"&&a.applyConstraints)try{yield a.applyConstraints(i)}catch(r){}if(e){const r=G({},i);i.maxSendFrameRate&&(r.frameRate=i.maxSendFrameRate),e==null||e.VideoProfileMap.set(this.profile,r),yield e.setVideoProfile(this.profile)}}})}}var Ve=(s=>(s[s.AliRtcSdkStreamTypeCapture=0]="AliRtcSdkStreamTypeCapture",s[s.AliRtcSdkStreamTypeScreen=1]="AliRtcSdkStreamTypeScreen",s))(Ve||{});class kr extends se{constructor(e){super();g(this,"type");g(this,"originVideoTrack");g(this,"videoSource");g(this,"_videoMuted",!1);g(this,"originAudioTrack");g(this,"audioSource");g(this,"_audioMuted",!1);g(this,"_targetVideoTrack");g(this,"_targetDualVideoTrack");g(this,"_targetAudioTrack");g(this,"_publishVideoStream");g(this,"_publishDualVideoStream");g(this,"_publishAudioStream");g(this,"_previewStream");g(this,"plugins",[]);g(this,"_profileManager");g(this,"cameraVideoConstraints");g(this,"micAudioConstraints");g(this,"onVideoTrackEnded",()=>{this.emit("videotrackended")});g(this,"onAudioTrackEnded",()=>{this.emit("audiotrackended")});this.type=e}get profileManager(){return this._profileManager}get audioProfile(){var e;return(e=this.profileManager)==null?void 0:e.audioProfile}updateSource(e,t,i){return I(this,null,function*(){var c,o,d,h,l,p;const{videoTrack:r,audioTrack:n}=e;r&&((c=this.originVideoTrack)==null||c.removeEventListener("ended",this.onVideoTrackEnded)),n&&((o=this.originAudioTrack)==null||o.removeEventListener("ended",this.onAudioTrackEnded)),this.type===Ve.AliRtcSdkStreamTypeScreen?this.stop():(r&&((d=this.originVideoTrack)==null||d.stop()),n&&((h=this.originAudioTrack)==null||h.stop())),r&&(this.originVideoTrack=r,(l=this.originVideoTrack)==null||l.addEventListener("ended",this.onVideoTrackEnded),this.videoSource=t||li.Camera,this.updateVideoTrack(r)),n&&(this.originAudioTrack=n,(p=this.originAudioTrack)==null||p.addEventListener("ended",this.onAudioTrackEnded),this.audioSource=i||Oi.Microphone,this.updateAudioTrack(n))})}get currentProfile(){var e;return(e=this.profileManager)==null?void 0:e.profile}get currentVideoTrack(){return this._targetVideoTrack}get currentDualVideoTrack(){return this._targetDualVideoTrack}get publishVideoStream(){return this._publishVideoStream}get publishDualVideoStream(){return this._publishDualVideoStream}get currentAudioTrack(){return this._targetAudioTrack}get publishAudioStream(){return this._publishAudioStream}get previewStream(){return this._previewStream}updateVideoTrack(e,t=!1){return I(this,null,function*(){(this._targetVideoTrack!==e||t)&&(this._targetVideoTrack=e)})}updateDualVideoTrack(e,t=!1){return I(this,null,function*(){(this._targetDualVideoTrack!==e||t)&&(this._targetDualVideoTrack=e)})}updateAudioTrack(e,t=!1){return I(this,null,function*(){(this._targetAudioTrack!==e||t)&&(this._targetAudioTrack=e)})}setAudioMuted(e){var t,i;this._audioMuted=e,e?(t=this.publishAudioStream)==null||t.disableAudio():(i=this.publishAudioStream)==null||i.enableAudio()}get isAudioMuted(){return this._audioMuted}setVideoMuted(e){var t,i;this._videoMuted=e,e?(t=this.publishVideoStream)==null||t.disableVideo():(i=this.publishVideoStream)==null||i.enableVideo()}get isVideoMuted(){return this._videoMuted}process(e){return I(this,null,function*(){var t,i,r,n,c,o,d,h,l,p,u,f;this._targetAudioTrack=this.originAudioTrack,this._targetVideoTrack=this.originVideoTrack;for(const m of this.plugins)try{yield m.execute(this,e)}catch(b){console.error(`error in plugin-${m.name}, error: ${b}`)}this._targetVideoTrack?((i=(t=this._publishVideoStream)==null?void 0:t.videoTrack)==null?void 0:i.id)!==this._targetVideoTrack.id&&(this._publishVideoStream=yield fi(this._targetVideoTrack),this.setVideoMuted(this._videoMuted),(r=this.profileManager)==null||r.setVideoProfile(this.originVideoTrack,this._publishVideoStream,!0),(n=this.profileManager)==null||n.setContentHint(this._targetVideoTrack),this.previewStream?(c=this.previewStream)==null||c.mergeStream(this._publishVideoStream):this._previewStream=yield fi(this._targetVideoTrack)):(this._publishVideoStream=void 0,(o=this.previewStream)==null||o.deleteTracks({video:!0})),this._targetDualVideoTrack?((h=(d=this._publishDualVideoStream)==null?void 0:d.videoTrack)==null?void 0:h.id)!==this._targetDualVideoTrack.id&&(this._publishDualVideoStream=yield fi(this._targetDualVideoTrack),this._videoMuted?this._publishDualVideoStream.disableVideo():this._publishDualVideoStream.enableVideo()):this._publishDualVideoStream=void 0,this._targetAudioTrack?((p=(l=this._publishAudioStream)==null?void 0:l.audioTrack)==null?void 0:p.id)!==this._targetAudioTrack.id&&(this._publishAudioStream=yield fi(this._targetAudioTrack),this.setAudioMuted(this._audioMuted),this.previewStream?(u=this.previewStream)==null||u.mergeStream(this._publishAudioStream):this._previewStream=yield fi(this._targetAudioTrack)):(this._publishAudioStream=void 0,(f=this.previewStream)==null||f.deleteTracks({audio:!0}))})}stopVideo(){var e,t;this.originVideoTrack&&((e=this.originVideoTrack)==null||e.removeEventListener("ended",this.onAudioTrackEnded),(t=this.originVideoTrack)==null||t.stop(),this.originVideoTrack=void 0),this.updateVideoTrack(void 0)}stopAudio(){var e,t;this.originAudioTrack&&((e=this.originAudioTrack)==null||e.removeEventListener("ended",this.onAudioTrackEnded),(t=this.originAudioTrack)==null||t.stop(),this.originAudioTrack=void 0),this.updateAudioTrack(void 0)}stop(){this.stopVideo(),this.stopAudio()}updateVideoProfile(e,t,i=!1){return I(this,null,function*(){this._profileManager||(this._profileManager=new Cr(this.type===Ve.AliRtcSdkStreamTypeScreen?Ja:_r)),e&&this._profileManager.updateProfile(e,t),yield this._profileManager.setVideoProfile(this.originVideoTrack,this._publishVideoStream,i)})}get videoProfile(){var e;return(e=this.profileManager)==null?void 0:e.videoProfile}setVideoContentHint(e){this._profileManager||(this._profileManager=new Cr(this.type===Ve.AliRtcSdkStreamTypeScreen?Ja:_r)),this._profileManager.setContentHint(this.currentVideoTrack,e)}updateAudioProfile(e){return I(this,null,function*(){this._profileManager||(this._profileManager=new Cr),this._profileManager.updateAudioProfile(e)})}cloneVideoProfile(e){return I(this,null,function*(){var t;yield(t=this.profileManager)==null?void 0:t.setVideoProfile(void 0,e)})}addPlugin(e){const t=this.plugins.findIndex(i=>i.zIndex>e.zIndex);t>-1?this.plugins.splice(t,0,e):this.plugins.push(e)}removePlugin(e){const t=this.plugins.indexOf(e);return t>-1&&(e.clear(this),this.plugins.splice(t,1),!0)}}var Qo=Object.defineProperty,Zo=Object.getOwnPropertyDescriptor,ft=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?Zo(a,e):a,n=s.length-1;n>=0;n--)(i=s[n])&&(r=(t?i(a,e,r):i(r))||r);return t&&r&&Qo(a,e,r),r};const ut=(Bt=class extends se{constructor(e,t){super();g(this,"pluginManager");g(this,"slsReporter");g(this,"publishingCameraVideoStream");g(this,"publishingScreenVideoStream");g(this,"cameraStreamInfo",new kr(Ve.AliRtcSdkStreamTypeCapture));g(this,"screenStreamInfo",new kr(Ve.AliRtcSdkStreamTypeScreen));g(this,"streamInfos",[this.cameraStreamInfo,this.screenStreamInfo]);g(this,"_audioCaptureDisabled",!1);g(this,"_cameraCaptureDisabled",!1);g(this,"_publishLocalAudioStreamEnabled",!0);g(this,"_publishLocalVideoStreamEnabled",!0);g(this,"_publishLocalScreenStreamEnabled",!0);this.screenStreamInfo.setVideoContentHint("motion"),this.pluginManager=e,this.slsReporter=t,this.cameraStreamInfo.on("videotrackended",()=>I(this,null,function*(){yield this.stopLocalStream({video:!0}),this.emit("trackended",Gt.VideoTrackEnded)})),this.cameraStreamInfo.on("audiotrackended",()=>I(this,null,function*(){yield this.stopLocalStream({audio:!0}),this.emit("trackended",Gt.AudioTrackEnded)})),this.screenStreamInfo.on("videotrackended",()=>I(this,null,function*(){yield this.stopLocalStream({screen:!0}),this.emit("trackended",Gt.ScreenTrackEnded)})),this.pluginManager.on("added",i=>I(this,null,function*(){if(V.info(`[${Bt.logName}]`,"plugin added",i.name),!i.isSupported("7.1.9"))return console.warn(`${i.name} is not supported!!!`),void i.emit("unsupported");try{yield i.init()}catch(r){i.emit("error",O.fromError(r,Ot.AliRtcPluginErrorInitError))}i.streamType===Ve.AliRtcSdkStreamTypeCapture&&(this.cameraStreamInfo.addPlugin(i),yield this.cameraStreamInfo.process(this.streamInfos)),i.streamType===Ve.AliRtcSdkStreamTypeScreen&&(this.screenStreamInfo.addPlugin(i),yield this.screenStreamInfo.process(this.streamInfos)),this.emit("publishupdate")})),this.pluginManager.on("removed",i=>I(this,null,function*(){this.cameraStreamInfo.removePlugin(i)&&(yield this.cameraStreamInfo.process(this.streamInfos)),this.screenStreamInfo.removePlugin(i)&&(yield this.screenStreamInfo.process(this.streamInfos)),this.emit("publishupdate")})),this.pluginManager.on("updated",()=>I(this,null,function*(){yield this.updateStreams()}))}get hasCamera(){return!!this.cameraStreamInfo.originVideoTrack}get audioCaptureDisabled(){return this._audioCaptureDisabled}set audioCaptureDisabled(e){this._audioCaptureDisabled=e}get cameraCaptureDisabled(){return this._cameraCaptureDisabled}set cameraCaptureDisabled(e){this._cameraCaptureDisabled=e}setAudioMuted(e){this.cameraStreamInfo.setAudioMuted(e)}get isAudioMuted(){return this.cameraStreamInfo.isAudioMuted}setCameraMuted(e){this.cameraStreamInfo.setVideoMuted(e)}get isCameraMuted(){return this.cameraStreamInfo.isVideoMuted}setScreenMuted(e){this.screenStreamInfo.setVideoMuted(e)}get isScreenMuted(){return this.screenStreamInfo.isVideoMuted}get publishLocalAudioStreamEnabled(){return this._publishLocalAudioStreamEnabled}set publishLocalAudioStreamEnabled(e){this._publishLocalAudioStreamEnabled=e}get publishLocalVideoStreamEnabled(){return this._publishLocalVideoStreamEnabled}set publishLocalVideoStreamEnabled(e){this._publishLocalVideoStreamEnabled=e}get publishLocalScreenStreamEnabled(){return this._publishLocalScreenStreamEnabled}set publishLocalScreenStreamEnabled(e){this._publishLocalScreenStreamEnabled=e}updateStreams(){return I(this,null,function*(){yield this.cameraStreamInfo.process(this.streamInfos),yield this.screenStreamInfo.process(this.streamInfos),this.emit("publishupdate")})}setAvailableCameraDeviceId(){return I(this,null,function*(){var e,t,i,r;if((e=this.cameraStreamInfo.cameraVideoConstraints)!=null&&e.deviceId){let n=(t=this.cameraStreamInfo.cameraVideoConstraints)==null?void 0:t.deviceId;const c=yield X.AliRTS.getCameraList();c.find(o=>o.deviceId===n)||(n=(r=(i=c.find(o=>!!o.deviceId))==null?void 0:i.deviceId)!=null?r:""),this.cameraStreamInfo.cameraVideoConstraints.deviceId=n}})}setAvailableMicrophoneDeviceId(){return I(this,null,function*(){var e,t,i,r;if((e=this.cameraStreamInfo.micAudioConstraints)!=null&&e.deviceId){let n=(t=this.cameraStreamInfo.micAudioConstraints)==null?void 0:t.deviceId;const c=yield X.AliRTS.getMicList();c.find(o=>o.deviceId===n)||(n=(r=(i=c.find(o=>!!o.deviceId))==null?void 0:i.deviceId)!=null?r:""),this.cameraStreamInfo.micAudioConstraints.deviceId=n}})}createLocalStream(e){return I(this,null,function*(){var l;const{screen:t,mediaStream:i,videoProfile:r,screenProfile:n}=e;let{video:c,audio:o}=e;const d=(p=>{const{audio:u,video:f,screen:m}=p;if(f&&m)throw new O(U.ERR_INNER,"create stream error, cannot create video && screen together");return!!(f||u||m)})(e);let h;if(d){i||(c===!0&&this.cameraStreamInfo.cameraVideoConstraints?(yield this.setAvailableCameraDeviceId(),c=G({},this.cameraStreamInfo.cameraVideoConstraints)):typeof c=="object"&&(yield this.setAvailableCameraDeviceId(),c=G(G({},c),this.cameraStreamInfo.cameraVideoConstraints)),o===void 0&&this.audioCaptureDisabled?o=!1:o&&(o===!0&&this.cameraStreamInfo.micAudioConstraints?(yield this.setAvailableMicrophoneDeviceId(),o=G({},this.cameraStreamInfo.micAudioConstraints)):typeof o=="object"&&(yield this.setAvailableMicrophoneDeviceId(),o=G(G({},o),this.cameraStreamInfo.micAudioConstraints)),this._audioCaptureDisabled=!1));const p=Date.now();try{h=yield X.AliRTS.createStream({audio:o,video:c,screen:t,custom:!!i,mediaStream:i,skipProfile:!0}),V.info(`[${Bt.logName}]`,"createLocalStream",{audio:o,video:c,screen:t,custom:!!i,time:Date.now()-p}),o&&!i&&this.slsReporter.reportAudio(null,Date.now()-p,((l=h==null?void 0:h.audioTrack)==null?void 0:l.label)||""),t&&!i&&this.slsReporter.reportScreen(null,Date.now()-p)}catch(u){throw o&&!i&&this.slsReporter.reportAudio(u,Date.now()-p,""),t&&!i&&this.slsReporter.reportScreen(null,Date.now()-p),u}if(t)yield this.screenStreamInfo.updateSource(h,li.Screen,Oi.Screen),yield this.setScreenProfile(n||Ka),this.setScreenContentHint(),this.publishingScreenVideoStream=void 0;else if(yield this.cameraStreamInfo.updateSource(h,li.Camera,Oi.Microphone),h.hasVideo&&(yield this.setVideoProfile(r||$a),this.setVideoContentHint(),this.publishingCameraVideoStream=void 0),h.hasAudio&&typeof o=="boolean"){const u=this.cameraStreamInfo.audioProfile;u&&(yield h.setAudioProfile(u))}}return X.AliRTS.SystenUtil.isIos&&X.AliRTS.SystenUtil.compareVersion("15.1")&&!X.AliRTS.SystenUtil.compareVersion("15.2")&&(yield xt(1e3)),yield this.updateStreams(),h})}stopLocalStream(e){return I(this,null,function*(){const{screen:t,video:i,audio:r}=e!=null?e:{};let n=!1;i&&this.cameraStreamInfo.originVideoTrack&&(n=!0,this.cameraStreamInfo.stopVideo(),this.publishingCameraVideoStream=void 0),r&&this.cameraStreamInfo.originAudioTrack&&(n=!0,this.cameraStreamInfo.stopAudio()),t&&this.screenStreamInfo.originVideoTrack&&(n=!0,this.screenStreamInfo.stop(),this.publishingScreenVideoStream=void 0,this.slsReporter.reportScreenStop(null)),n&&(yield this.updateStreams())})}get publishStreams(){const{publishLocalVideoStreamEnabled:e,publishLocalAudioStreamEnabled:t,publishLocalScreenStreamEnabled:i}=this;return{video:e?this.cameraStreamInfo.publishVideoStream:void 0,videoSmall:e?this.cameraStreamInfo.publishDualVideoStream:void 0,audio:t?this.cameraStreamInfo.publishAudioStream:void 0,screen:i?this.screenStreamInfo.publishVideoStream:void 0}}createHTTPPublishStream(){return I(this,null,function*(){var o,d,h,l;let e,t,i,r,n=!1;const c=this.publishStreams;try{if(!(c.audio||c.video||c.videoSmall||c.screen))throw V.error(`[${Bt.logName}]`,"no tracks founded"),new O(U.ERR_SDK_PUBLISH_INVAILD,"no tracks founded");const p=new MediaStream;(o=c.audio)!=null&&o.audioTrack&&p.addTrack(c.audio.audioTrack),(d=c.video)!=null&&d.videoTrack?(p.addTrack(c.video.videoTrack),i=c.videoSmall,r=c.screen):(h=c.screen)!=null&&h.videoTrack&&(t=M.Screen,p.addTrack((l=c.screen)==null?void 0:l.videoTrack),n=!0),e=yield Qa(p),n?(this.screenStreamInfo.cloneVideoProfile(e),this.publishingScreenVideoStream=e):(this.cameraStreamInfo.cloneVideoProfile(e),this.publishingCameraVideoStream=e)}catch(p){}return{publishStream:e,videoSmallStream:i,screenStream:r,vMsid:t}})}stop(){this.cameraStreamInfo.stop(),this.screenStreamInfo.stop(),this.updateStreams()}setVideoProfile(e,t,i=!1){return I(this,null,function*(){yield this.cameraStreamInfo.updateVideoProfile(e,t,i),this.publishingCameraVideoStream&&this.cameraStreamInfo.cloneVideoProfile(this.publishingCameraVideoStream)})}setVideoContentHint(e){this.cameraStreamInfo.setVideoContentHint(e)}setAudioProfile(e){return I(this,null,function*(){var t;yield this.cameraStreamInfo.updateAudioProfile(e),yield(t=this.publishingCameraVideoStream)==null?void 0:t.setAudioProfile(e)})}setScreenProfile(e,t){return I(this,null,function*(){yield this.screenStreamInfo.updateVideoProfile(e,t),this.publishingScreenVideoStream&&this.screenStreamInfo.cloneVideoProfile(this.publishingScreenVideoStream)})}setScreenContentHint(e){this.screenStreamInfo.setVideoContentHint(e)}setCameraVideoConstraints(e){var t;this.cameraStreamInfo.cameraVideoConstraints=G(G({},(t=this.cameraStreamInfo.cameraVideoConstraints)!=null?t:{}),e)}setMicAudioConstraints(e){var t;this.cameraStreamInfo.micAudioConstraints=G(G({},(t=this.cameraStreamInfo.micAudioConstraints)!=null?t:{}),e)}},g(Bt,"logName","LocalStreamManager"),Bt);ft([C(([s])=>{const{audio:a,video:e,screen:t,custom:i,skipProfile:r,videoProfile:n,screenProfile:c}=s;return[{audio:a,video:e,screen:t,custom:i,skipProfile:r,videoProfile:n,screenProfile:c}]})],ut.prototype,"createLocalStream",1),ft([C(H)],ut.prototype,"stopLocalStream",1),ft([C()],ut.prototype,"createHTTPPublishStream",1),ft([C()],ut.prototype,"stop",1),ft([C(H)],ut.prototype,"setVideoProfile",1),ft([C(H)],ut.prototype,"setVideoContentHint",1),ft([C(H)],ut.prototype,"setAudioProfile",1),ft([C(H)],ut.prototype,"setScreenProfile",1),ft([C(H)],ut.prototype,"setScreenContentHint",1),ft([C(H)],ut.prototype,"setCameraVideoConstraints",1),ft([C(H)],ut.prototype,"setMicAudioConstraints",1);let ec=ut;const tc=s=>I(this,null,function*(){const a=new X.AliRTS.SupportUtil;window.isSecureContext||console.warn("WebRTC 需要 HTTPS 安全上下文,细节可参考:https://developer.mozilla.org/zh-CN/docs/Web/Security/Secure_Contexts");let e={support:!1,detail:{isWebRTCSupported:a.checkMediaDevices()&&a.checkWebRtcSupport(),isH264DecodeSupported:!1,isH264EncodeSupported:!1,isScreenShareSupported:!1,isSendMediaExtensionMsgSupported:!1,isBrowserSupported:!0}},t=!1;try{e.detail.isWebRTCSupported?(yield a.isSupport({isReceiveVideo:!0}),t=!0):console.warn("当前浏览器不支持 WebRTC")}catch(i){t=!1,e.detail.isBrowserSupported=a.checkBrowser({errorCode:0,message:""})}if(e.support=t,a.checkWebRtcSupport()&&s!=="sendonly"){const i=yield a.checkH264Decode();e.detail.isH264DecodeSupported=i,e.support=e.support&&i}if(a.checkWebRtcSupport()&&s!=="recvonly"){const i=yield a.checkH264Encode();e.detail.isH264EncodeSupported=i,e.support=e.support&&i}return e.detail.isScreenShareSupported=a.checkWebRtcSupport()&&a.checkScreenCapture()&&!X.AliRTS.SystenUtil.isAndroid&&!X.AliRTS.SystenUtil.isIos,e.detail.isSendMediaExtensionMsgSupported=a.checkWebRtcSupport()&&a.checkEncodedTransformSupport(),e});var en=(s=>(s[s.PRE_PROCESSOR=0]="PRE_PROCESSOR",s[s.POST_PROCESSOR=1]="POST_PROCESSOR",s))(en||{}),ni=(s=>(s[s.AUDIO=0]="AUDIO",s[s.VIDEO=1]="VIDEO",s[s.BOTH=2]="BOTH",s))(ni||{});class Dt extends se{constructor(e,t=Ve.AliRtcSdkStreamTypeCapture,i=1){super();g(this,"name");g(this,"options");g(this,"type",0);g(this,"streamType");g(this,"trackType");g(this,"zIndex",1);g(this,"_isEnable",!0);g(this,"shouldCache",!0);g(this,"lastInputAudioTrack");g(this,"lastOutputAudioTrack");g(this,"lastInputVideoTrack");g(this,"lastOutputVideoTrack");g(this,"_hasCleared",!0);this.name=e,this.streamType=t,this.trackType=i,this.options=this.initOptions}get initOptions(){return{}}getOptions(){return this.options}init(){return I(this,null,function*(){})}enable(){this._isEnable||(this._isEnable=!0,this.init(),this.emit("enabled"))}disable(){this._isEnable&&(this._isEnable=!1,this.clear(),this.emit("disabled"))}get isEnable(){return this._isEnable}audioUpdated(e){var t,i;return((t=this.lastInputAudioTrack)==null?void 0:t.id)!==((i=e.currentAudioTrack)==null?void 0:i.id)}videoUpdated(e){var t,i;return((t=this.lastInputVideoTrack)==null?void 0:t.id)!==((i=e.currentVideoTrack)==null?void 0:i.id)}execute(e,t){return I(this,null,function*(){const i=this.shouldUpdate(e,t);this.lastInputAudioTrack=e.currentAudioTrack,this.lastInputVideoTrack=e.currentVideoTrack,this._hasCleared||i?(yield this.process(e,t),this._hasCleared=!1):this.shouldCache&&(!this.lastOutputAudioTrack||this.trackType!==2&&this.trackType!==0||this.lastOutputAudioTrack&&e.updateAudioTrack(this.lastOutputAudioTrack),!this.lastOutputVideoTrack||this.trackType!==2&&this.trackType!==1||this.lastOutputVideoTrack&&e.updateVideoTrack(this.lastOutputVideoTrack)),this.lastOutputAudioTrack=e.currentAudioTrack,this.lastOutputVideoTrack=e.currentVideoTrack})}clear(e){this._hasCleared=!0,this.lastInputAudioTrack=void 0,this.lastInputVideoTrack=void 0,this.lastOutputAudioTrack=void 0,this.lastOutputVideoTrack=void 0}}class ic extends Dt{constructor(){super("AliRtcScreenStandardize",Ve.AliRtcSdkStreamTypeScreen);g(this,"canvas");g(this,"lastWidth");g(this,"lastHeight");g(this,"isProcessingScreenTrack",!1);this.shouldCache=!1}get initOptions(){return{base:4}}setOptions(e){this.options=e}isSupported(){return!(typeof TransformStream=="undefined"||typeof MediaStreamTrackProcessor=="undefined"||typeof MediaStreamTrackGenerator=="undefined")}updateProcessCanvas(e,t){if(this.canvas&&this.lastWidth===e&&this.lastHeight===t)return;const i=Math.ceil(e/this.options.base)*this.options.base,r=Math.ceil(t/this.options.base)*this.options.base;if(this.canvas||(this.canvas=document.createElement("canvas")),this.canvas.width=i,this.canvas.height=r,this.lastWidth&&e>this.lastWidth||this.lastHeight&&t>this.lastHeight){const n=this.canvas.getContext("2d");n&&n.clearRect(0,0,i,r)}this.lastWidth=e,this.lastHeight=t}shouldProcess(e){var i;let t=!1;if(e.originVideoTrack&&e.videoSource===li.Screen){const r=(i=e.originVideoTrack)==null?void 0:i.getSettings();if(r){const{width:n,height:c}=r;t=!n||!c||!(n%this.options.base===0&&c%this.options.base===0)}}return t}shouldUpdate(e){return this.shouldProcess(e)!==this.isProcessingScreenTrack}handleFrame(e){return I(this,null,function*(){var n;const{displayWidth:t,displayHeight:i}=e;if(!t||!i||t%this.options.base===0&&i%this.options.base===0)return e;this.updateProcessCanvas(t,i);const r=(n=this.canvas)==null?void 0:n.getContext("2d");if(this.canvas&&r){r.drawImage(e,0,0,t,i);const c=new VideoFrame(this.canvas,{timestamp:e.timestamp});return e.close(),c}return e})}process(e){return I(this,null,function*(){var h;if(!this.shouldProcess(e))return this.clear(e),void(this.isProcessingScreenTrack=!1);if(e.originVideoTrack){const l=e.originVideoTrack.getSettings();if(l){const{width:p,height:u}=l;if(!(!p||!u||!(p%this.options.base===0&&u%this.options.base===0)))return void this.clear(e)}}const t=new MediaStreamTrackProcessor({track:e.originVideoTrack}),i=new MediaStreamTrackGenerator({kind:"video"}),r=new MediaStream([i]),n=this,c=new TransformStream({transform(l,p){return I(this,null,function*(){const u=yield n.handleFrame(l);yield p.enqueue(u),u==null||u.close()})}});t.readable.pipeThrough(c).pipeTo(i.writable);const o=(h=r.getVideoTracks())==null?void 0:h[0];e.updateVideoTrack(o),this.isProcessingScreenTrack=!0})}clear(e){this.canvas=void 0,this.lastWidth=void 0,this.lastHeight=void 0,super.clear(e)}}class rc extends Dt{constructor(){super("blankAudio",Ve.AliRtcSdkStreamTypeCapture,ni.BOTH);g(this,"hasTrack",!1);g(this,"oscillator",null);g(this,"audioTrack",null);g(this,"createAudioTrack",()=>{const e=new AudioContext;this.oscillator=e.createOscillator();const t=e.createGain();t.gain.value=0;const i=e.createMediaStreamDestination();this.oscillator.connect(t),t.connect(i),this.oscillator.start();const r=i.stream;return this.audioTrack=r.getAudioTracks()[0],this.audioTrack});this.zIndex=9}isSupported(){return!0}setOptions(){throw new Error("Method not implemented.")}shouldUpdate(e,t){return this.hasTrack!==t.some(i=>i.originVideoTrack||i.originAudioTrack)}process(e,t){return I(this,null,function*(){var r;const i=t.some(n=>n.originVideoTrack||n.originAudioTrack);this.hasTrack=i,i?this.audioTrack&&((r=this.oscillator)==null||r.stop(),this.oscillator=null,this.audioTrack.stop(),this.audioTrack=null):(this.audioTrack||(this.audioTrack=this.createAudioTrack()),e.updateAudioTrack(this.audioTrack))})}}class tn{constructor(a){g(this,"name","COMMON");this.name=a||this.name}info(...a){}warn(...a){}print(a,...e){const t=a.toLowerCase();t&&console[t](`[${a}][${this.name}]`,...e)}}g(tn,"LEVEL",0);class sc{constructor(){g(this,"logger",new tn("AudioMixer"));g(this,"audioContext",new AudioContext);g(this,"audioDestination",this.audioContext.createMediaStreamDestination());g(this,"audioTrack",(a=>a.getAudioTracks()[0])(this.audioDestination.stream));g(this,"sourceNodeMap",{})}get sourceNodeList(){return Object.values(this.sourceNodeMap).map(a=>a.sourceNode).filter(a=>!!a)}get gainNodeList(){return Object.values(this.sourceNodeMap).map(a=>a.gainNode).filter(a=>!!a)}get sourceCount(){return this.sourceNodeList.length}resume(){var a;return(a=this.audioContext)==null?void 0:a.resume()}addTrack(a){this.connectTrack(a)}hasTrack(a){return!!this.sourceNodeMap[a]}removeTrack(a){const{sourceNode:e,gainNode:t}=this.sourceNodeMap[a]||{};t==null||t.disconnect(),e==null||e.disconnect(),delete this.sourceNodeMap[a],e?this.logger.info("SourceNode disconnected. Active source node:",this.sourceNodeList.length):this.logger.warn(`SourceNode ${a} does not exit. Active source node: ${this.sourceNodeList.length}`)}getAudioTrack(){return this.audioTrack}setVolume(a,e){const{gainNode:t}=this.sourceNodeMap[e]||{};t?(this.logger.info(`Setting node(${e}) volume to ${this.scale(a)}`),t.gain.value=this.scale(a)):this.logger.warn(`GainNode ${e} does not exit.`)}reset(){this.disconnectSourceNode(),this.sourceNodeMap={}}dispose(){var a;this.reset(),(a=this.audioTrack)==null||a.stop(),this.audioDestination.disconnect(),this.audioContext.close()}connectTrack(a){if(!this.audioContext)return this.logger.warn("AudioContext not initialized");let e=new MediaStream;e.addTrack(a);const t=this.audioContext.createMediaStreamSource(e),i=this.audioContext.createGain();i.gain.value=1,t.connect(i),i.connect(this.audioDestination),this.sourceNodeMap[a.id]={track:a,sourceNode:t,gainNode:i},this.logger.info("New sourceNode connected. Active source node:",this.sourceNodeList.length)}disconnectSourceNode(){this.sourceNodeList.forEach(a=>a.disconnect()),this.gainNodeList.forEach(a=>a.disconnect())}scale(a){return a/100}}class ac extends Dt{constructor(){super("audioMixer",Ve.AliRtcSdkStreamTypeCapture,ni.AUDIO);g(this,"audioMixer");g(this,"primaryAudioTrackId");g(this,"screenAudioTrackId");g(this,"dirty",!1);this.zIndex=8}get initOptions(){return{audio:1,screen:1}}setOptions(e){Object.entries(e).forEach(([t,i])=>{this.isValidVolume(i)&&(this.options[t]=i)}),this.dirty=!0,this.emit("updated")}isSupported(){return"AudioContext"in window}shouldUpdate(e,t){var n,c;if(e.type!==Ve.AliRtcSdkStreamTypeCapture)return!1;const i=t.find(o=>o.type===Ve.AliRtcSdkStreamTypeCapture),r=t.find(o=>o.type===Ve.AliRtcSdkStreamTypeScreen);return!(this.primaryAudioTrackId===((n=i==null?void 0:i.currentAudioTrack)==null?void 0:n.id)&&this.screenAudioTrackId===((c=r==null?void 0:r.currentAudioTrack)==null?void 0:c.id)&&!this.dirty)}process(e,t){return I(this,null,function*(){var c,o;this.dirty=!1;const i=t.find(d=>d.type===Ve.AliRtcSdkStreamTypeScreen),r=e.currentAudioTrack,n=i==null?void 0:i.currentAudioTrack;if(!n&&this.options.audio===1)return this.audioMixer&&(this.audioMixer.dispose(),this.audioMixer=void 0),this.primaryAudioTrackId=r==null?void 0:r.id,void e.updateAudioTrack(r);this.audioMixer||(this.audioMixer=new sc),yield this.audioMixer.resume(),this.primaryAudioTrackId&&(r==null?void 0:r.id)!==this.primaryAudioTrackId&&((c=this.audioMixer)==null||c.removeTrack(this.primaryAudioTrackId)),r&&!this.audioMixer.hasTrack(r==null?void 0:r.id)&&this.audioMixer.addTrack(r),this.primaryAudioTrackId=r==null?void 0:r.id,this.screenAudioTrackId&&(n==null?void 0:n.id)!==this.screenAudioTrackId&&((o=this.audioMixer)==null||o.removeTrack(this.screenAudioTrackId)),n&&!this.audioMixer.hasTrack(n==null?void 0:n.id)&&this.audioMixer.addTrack(n),this.screenAudioTrackId=n==null?void 0:n.id,this.updateVolume(),e.updateAudioTrack(this.audioMixer.getAudioTrack())})}isValidVolume(e){return e!==void 0&&e>=0&&e<=4}updateVolume(){this.audioMixer&&(this.primaryAudioTrackId&&this.audioMixer.setVolume(100*this.options.audio,this.primaryAudioTrackId),this.screenAudioTrackId&&this.audioMixer.setVolume(100*this.options.screen,this.screenAudioTrackId))}clear(e){var t;(t=this.audioMixer)==null||t.dispose(),super.clear(e)}}class nc extends Dt{constructor(){super(...arguments);g(this,"hasVideoTrack",!1);g(this,"videoScaler")}get initOptions(){return{width:320,height:180,frameRate:15}}setOptions(e){var t;this.options=e,(t=this.videoScaler)==null||t.updateOptions(e)}isSupported(){return gt.isSupport()}shouldUpdate(e){return this.hasVideoTrack!==!!e.currentVideoTrack}process(e){return I(this,null,function*(){if(e.currentVideoTrack){if(this.hasVideoTrack=!0,!this.videoScaler){const i=this.options||this.initOptions;this.videoScaler=gt.getInstance(e.currentVideoTrack,i)}const t=this.videoScaler.getVideoTrack();t&&e.updateDualVideoTrack(t)}else e.updateDualVideoTrack(),this.emit("updated"),this.videoScaler&&this.videoScaler.dispose()})}clear(e){super.clear(e),this.hasVideoTrack=!1,e==null||e.updateDualVideoTrack()}}function oi(s,a,e,t){return new(e||(e=Promise))(function(i,r){function n(d){try{o(t.next(d))}catch(h){r(h)}}function c(d){try{o(t.throw(d))}catch(h){r(h)}}function o(d){var h;d.done?i(d.value):(h=d.value,h instanceof e?h:new e(function(l){l(h)})).then(n,c)}o((t=t.apply(s,a||[])).next())})}var Ut,wt;function rn(){return oi(this,void 0,void 0,function*(){let s=!1;try{s=yield(()=>I(this,null,function*(){return 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]))}))()}catch(a){s=!1}return console.log("isSupportedSIMD",s),s})}typeof SuppressedError=="function"&&SuppressedError,(wt=Ut||(Ut={}))[wt.ERROR=0]="ERROR",wt[wt.WARN=1]="WARN",wt[wt.INFO=2]="INFO",wt[wt.LOG=3]="LOG",wt[wt.DEBUG=4]="DEBUG";class ve{static error(...a){var e;ve.logLevel>=Ut.ERROR&&((e=console.error)===null||e===void 0||e.call(console,`[${ve.logTag}] `,...a))}static warn(...a){var e;ve.logLevel>=Ut.WARN&&((e=console.warn)===null||e===void 0||e.call(console,`[${ve.logTag}] `,...a))}static info(...a){var e;ve.logLevel>=Ut.INFO&&((e=console.info)===null||e===void 0||e.call(console,`[${ve.logTag}] `,...a))}static log(...a){var e;ve.logLevel>=Ut.LOG&&((e=console.log)===null||e===void 0||e.call(console,`[${ve.logTag}] `,...a))}static debug(...a){var e;ve.logLevel>=Ut.DEBUG&&((e=console.debug)===null||e===void 0||e.call(console,`[${ve.logTag}] `,...a))}}ve.logLevel=Ut.WARN,ve.logTag="aliyun-audio-3a";class oc{}class sn extends oc{static isSupported(){return function(){if(typeof window=="object"&&window!==null){const a="AudioWorklet"in window,e="WebAssembly"in window;return a&&e}return!1}()}static isSupportedSIMD(){return oi(this,void 0,void 0,function*(){return yield rn()})}static setLogger(a){ve.logLevel=a}constructor(a){super(),this.channelCount=1,this.sampleRate=48e3,this.collectDumpOutputData=[],this.collectDumpNearInputData=[],this.collectDumpFarInputData=[],this.collectDumpMetaData=[],this.statUpdateTimer=0,this.statUpdateInterval=5e3,this.options=Object.assign({aecOn:!0,ansOn:!0,agcOn:!0,hdOn:!1,ansMode:1,dumpOn:!1,aiaecOn:!1,wasmCdnPath:"https://g.alicdn.com/code/npm/@ali/aliyun-audio-3a/0.0.6/"},a||{})}initWASM(a,e,t){return oi(this,void 0,void 0,function*(){ve.log("initWASM",a,e,t);const i=n=>oi(this,void 0,void 0,function*(){try{const c=yield fetch(n,{credentials:"same-origin"});return c.ok||this.onLoadError(new Error(`Failed to fetch WASM: ${c.status}:${c.statusText}, url:${n}`)),c.arrayBuffer()}catch(c){return this.onLoadError(new Error("WASM load error")),ve.error("Error fetching WASM:",c),new Uint8Array(0)}}),r=n=>oi(this,void 0,void 0,function*(){return fetch(n).then(c=>c.text())});try{const n=yield rn(),c=this.options.wasmCdnPath+"audio_module_v2.wasm",o=this.options.wasmCdnPath+"audio_module_v2_simd.wasm",h=yield i(n?o:c),l=this.options.wasmCdnPath+"audio_module_v2.js",p=this.options.wasmCdnPath+"audio_module_v2_simd.js",u=n?p:l,f=yield r(u);a.port.postMessage(Object.assign({type:"init",channelCount:e,sampleRate:t,wasmBuffer:h,isSupportSIMD:n,audioModuleScript:f,logLevel:ve.logLevel},this.options),[h])}catch(n){ve.error("Error initializing WASM:",n),this.onLoadError(new Error("WASM init error"))}a.port.onmessage=n=>{n.data.type==="init_done"&&this.onLoadSuccess(void 0),n.data.type==="dump_output_data"&&this.onDumpOutputData(n.data.data),n.data.type==="dump_near_data"&&this.onDumpNearInputData(n.data.data),n.data.type==="dump_far_data"&&this.onDumpFarInputData(n.data.data),n.data.type==="dump_meta_data"&&this.onDumpMeatData(n.data.data),n.data.type==="output_log"&&this.onOutputLog(n.data.data),n.data.type==="apm_stat_data"&&this.onStatData(n.data.data)}})}createProcessor(a,e,t,i,r){return oi(this,void 0,void 0,function*(){this.audioContext=a,this.audioContext.resume(),this.channelCount=t,this.sampleRate=i;try{const o=new Blob(['!function(){"use strict";var Bc=Object.defineProperty,Hc=Object.defineProperties;var Fc=Object.getOwnPropertyDescriptors;var qi=Object.getOwnPropertySymbols,jc=Object.getPrototypeOf,Cn=Object.prototype.hasOwnProperty,kn=Object.prototype.propertyIsEnumerable,zc=Reflect.get;var Xr=(W,X,se)=>X in W?Bc(W,X,{enumerable:!0,configurable:!0,writable:!0,value:se}):W[X]=se,G=(W,X)=>{for(var se in X||(X={}))Cn.call(X,se)&&Xr(W,se,X[se]);if(qi)for(var se of qi(X))kn.call(X,se)&&Xr(W,se,X[se]);return W},vt=(W,X)=>Hc(W,Fc(X));var jt=(W,X)=>{var se={};for(var qe in W)Cn.call(W,qe)&&X.indexOf(qe)<0&&(se[qe]=W[qe]);if(W!=null&&qi)for(var qe of qi(W))X.indexOf(qe)<0&&kn.call(W,qe)&&(se[qe]=W[qe]);return se};var g=(W,X,se)=>(Xr(W,typeof X!="symbol"?X+"":X,se),se);var Yr=(W,X,se)=>zc(jc(W),se,X);var I=(W,X,se)=>new Promise((qe,Ii)=>{var Ci=gt=>{try{ei(se.next(gt))}catch(ti){Ii(ti)}},ki=gt=>{try{ei(se.throw(gt))}catch(ti){Ii(ti)}},ei=gt=>gt.done?qe(gt.value):Promise.resolve(gt.value).then(Ci,ki);ei((se=se.apply(W,X)).next())});function t(t,e,a,n){return new(a||(a=Promise))((function(s,i){function o(t){try{h(n.next(t))}catch(t){i(t)}}function r(t){try{h(n.throw(t))}catch(t){i(t)}}function h(t){var e;t.done?s(t.value):(e=t.value,e instanceof a?e:new a((function(t){t(e)}))).then(o,r)}h((n=n.apply(t,e||[])).next())}))}var e;"function"==typeof SuppressedError&&SuppressedError,function(t){t[t.ERROR=0]="ERROR",t[t.WARN=1]="WARN",t[t.INFO=2]="INFO",t[t.LOG=3]="LOG",t[t.DEBUG=4]="DEBUG"}(e||(e={}));class a{static error(...t){var n;a.logLevel>=e.ERROR&&(null===(n=console.error)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static warn(...t){var n;a.logLevel>=e.WARN&&(null===(n=console.warn)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static info(...t){var n;a.logLevel>=e.INFO&&(null===(n=console.info)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static log(...t){var n;a.logLevel>=e.LOG&&(null===(n=console.log)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}static debug(...t){var n;a.logLevel>=e.DEBUG&&(null===(n=console.debug)||void 0===n||n.call(console,`[${a.logTag}] `,...t))}}a.logLevel=e.WARN,a.logTag="aliyun-audio-3a";const n=Float32Array.BYTES_PER_ELEMENT,s=Uint16Array.BYTES_PER_ELEMENT;class i{constructor(t,e,a,n,s){this._channelData=[],this._name=t,this._isInitialized=!1,this._module=e,this._length=a,this._ringLength=2*a,this._maxChannelCount=s?Math.min(s,32):n,this._channelCount=n,this._allocateHeap(),this._isInitialized=!0,this._readIndex=0,this._writeIndex=0,this._framesAvailable=0,this._channelDataLocal=[];for(let t=0;t<this._channelCount;++t)this._channelDataLocal[t]=new Float32Array(this._ringLength)}_allocateHeap(){const t=this._length*n,e=this._channelCount*t;this._dataPtr=this._module._malloc(e),this._channelData=[];for(let e=0;e<this._channelCount;++e){const a=this._dataPtr+e*t,n=a+t;this._channelData[e]=this._module.HEAPF32.subarray(a>>s,n>>s)}}adaptChannel(t){t<this._maxChannelCount&&(this._channelCount=t)}get length(){return this._isInitialized?this._length:null}get numberOfChannels(){return this._isInitialized?this._channelCount:null}get maxChannelCount(){return this._isInitialized?this._maxChannelCount:null}getChannelData(t){return void 0!==t&&t>=this._channelCount?null:void 0===t?this._channelData:this._channelData[t]}getHeapAddress(){return this._dataPtr}getPointer(){return this._dataPtr}free(){this._isInitialized=!1,null!==this._dataPtr&&this._module._free(this._dataPtr),this._channelData=[]}get framesAvailable(){return this._framesAvailable}push(t){const e=t[0].length;for(let a=0;a<e;++a){for(let e=0;e<this._channelCount;++e)this._channelDataLocal[e][this._writeIndex]=t[e][a];this._writeIndex=(this._writeIndex+1)%this._ringLength}this._framesAvailable+=e,this._framesAvailable>this._ringLength&&(console.warn(this._name,"Too many frames available, overflow"),this._framesAvailable=this._ringLength,this._writeIndex=0)}pull(t){if(0===this._framesAvailable)return void console.warn(this._name,"No frames available");const e=t[0].length;for(let a=0;a<e;++a){for(let e=0;e<this._channelCount;++e)t[e][a]=this._channelDataLocal[e][this._readIndex];this._readIndex=(this._readIndex+1)%this._ringLength}this._framesAvailable-=e,this._framesAvailable<0&&(this._framesAvailable=0,this._readIndex=0)}}class o{constructor(t){this.inited=!1,this.handle=null,this.channelCount=1,this.isEnable=!0,this.dumpAudioData=!1,this.kernelBufferSize=512,this.node=t,this.onDumpOutputDataFunction=null,this.onDumpNearDataFunction=null,this.onDumpFarDataFunction=null,this.onDumpMetaDataFunction=null,this.wasmInvoker=null,this._nearAudioBuffer={},this._outputAudioBuffer={}}destructor(){this.wasmInvoker=null,this.handle=null}init(n){return t(this,void 0,void 0,(function*(){const{wasmBuffer:t,audioModuleScript:s,channelCount:o=1,sampleRate:r=44100,dumpAudioData:h=!1,logLevel:l=e.DEBUG}=n;a.logLevel=l,a.log("AudioAPM init",JSON.stringify(n)),this.channelCount=o,this.dumpAudioData=h;try{const e=new Function(`let module={};let exports={};${s}; return module`)();this.wasmInvoker=yield e.exports({wasmBinary:t})}catch(t){this.node.port.postMessage({type:"error",message:"audioModule init error"}),a.error(t)}this._nearAudioBuffer=new i("inBuffer",this.wasmInvoker,this.kernelBufferSize,2*this.channelCount,32),this._outputAudioBuffer=new i("outBuffer",this.wasmInvoker,this.kernelBufferSize,this.channelCount,32);const u=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=String.fromCharCode.apply(null,a);this.node&&this.node.port&&this.node.port.postMessage({type:"output_log",message:"output_log",data:n})}),"vii");if(this.wasmInvoker.__apm_log_callback(u),this.handle=this.wasmInvoker.__apm_create(n.aecOn?1:0,n.ansOn?1:0,n.agcOn?1:0,n.hdOn?1:0,r,o,n.dumpOn?1:0,this.kernelBufferSize),n.aiaecOn){const t=102;this.wasmInvoker.__apm_set_param(this.handle,t,7)}if(n.useHardOnly){const t=108;this.wasmInvoker.__apm_set_param(this.handle,t,1)}this.node.port.postMessage({type:"init_done",message:"init done"}),this.inited=!0}))}getStatData(){if(this.wasmInvoker&&this.isEnable){let t=this.wasmInvoker.__apm_get_stat(this.handle),e=this.wasmInvoker.UTF8ToString(t);this.wasmInvoker._free(t),this.node&&this.node.port&&this.node.port.postMessage({type:"apm_stat_data",message:"apm_stat_data",data:e})}}onOutputLog(t){console.log("[WASM_LOG]",t)}destory(){return t(this,void 0,void 0,(function*(){var t;try{null===(t=this.wasmInvoker)||void 0===t||t.__apm_destory(this.handle),this.inited=!1}catch(t){a.error(t)}finally{this.handle=null}}))}enable(){this.isEnable=!0,a.log("APM enable")}disable(){this.isEnable=!1,a.log("APM disable")}getStat(){if(null==this.wasmInvoker||null==this.handle)return"";let t=this.wasmInvoker.__apm_get_stat(this.handle),e=this.wasmInvoker.UTF8ToString(t);return this.wasmInvoker._free(t),e}startDump(){this.onDumpOutputDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_output_data",message:"dump_output_data",data:n})}),"vii"),this.onDumpNearDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_near_data",message:"dump_near_data",data:n})}),"vii"),this.onDumpFarDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_far_data",message:"dump_far_data",data:n})}),"vii"),this.onDumpMetaDataFunction=this.wasmInvoker.addFunction(((t,e)=>{const a=this.wasmInvoker.HEAPU8.subarray(t,t+e),n=new Uint8Array(a);this.node&&this.node.port&&this.node.port.postMessage({type:"dump_meta_data",message:"dump_meta_data",data:n})}),"vii"),this.wasmInvoker.__apm_dump_start(this.handle,this.onDumpOutputDataFunction,this.onDumpNearDataFunction,this.onDumpFarDataFunction,this.onDumpMetaDataFunction)}stopDump(){this.wasmInvoker.__apm_dump_stop(this.handle),this.wasmInvoker&&(this.wasmInvoker.removeFunction(this.onDumpOutputDataFunction),this.wasmInvoker.removeFunction(this.onDumpNearDataFunction),this.wasmInvoker.removeFunction(this.onDumpFarDataFunction),this.wasmInvoker.removeFunction(this.onDumpMetaDataFunction))}process(t,e,a){if(!this.inited||!this.isEnable){for(let e=0;e<this.channelCount;e++){a[e].set(t[e])}return}const n=this.channelCount;let s=0;if(this.handle&&this.isEnable){const i=t[0].length,o=[];for(let a=0;a<n;a++)e[a]&&e[a].length>0&&(s=1),o.push(t[a]||new Float32Array(i).fill(0)),o.push(e[a]||new Float32Array(i).fill(0));if(this._nearAudioBuffer.push(o),this._nearAudioBuffer.framesAvailable>=this.kernelBufferSize){this._nearAudioBuffer.pull(this._nearAudioBuffer.getChannelData()),this.wasmInvoker.__apm_process_new(this.handle,this._nearAudioBuffer.getHeapAddress(),this._outputAudioBuffer.getHeapAddress(),n,s);const t=this._outputAudioBuffer.getChannelData();this._outputAudioBuffer.push(t)}this._outputAudioBuffer.pull(a)}}}class r extends AudioWorkletProcessor{constructor(){super(),this.apm=new o(this),this.port.onmessage=t=>{const e=t.data||{};switch(a.log("onmessage data",e),e.type){case"init":this.apm.init(e);break;case"destroy":this.apm.destory();break;case"enable":this.apm.enable();break;case"disable":this.apm.disable();break;case"start_dump":this.apm.startDump();break;case"stop_dump":this.apm.stopDump();break;case"get_stat_data":this.apm.getStatData();break;default:a.warn("Unknown message type:",e.type)}}}process(t,e){const a=t[0],n=t.length>1?t[1]:[],s=e[0];return this.apm.process(a,n,s),!0}}registerProcessor("aliyun-web-3a-processor",r)}();\n'],{type:"application/javascript"}),d=URL.createObjectURL(o);yield this.audioContext.audioWorklet.addModule(d)}catch(o){ve.error("Failed to add module to audio worklet:",o)}let n=new AudioWorkletNode(this.audioContext,"aliyun-web-3a-processor",{numberOfInputs:2,outputChannelCount:[t]});this.workletNode=n,e.connect(n),r&&(this.farNode=r,r.connect(n,0,1));const c=this.audioContext.createMediaStreamDestination();n.connect(c),this.targetMediaTrack=c.stream.getAudioTracks()[0],yield this.initWASM(n,t,i),this.statUpdateTimer=window.setInterval(()=>{this.getStatData()},this.statUpdateInterval)})}addFarNode(a){this.workletNode&&(this.farNode&&this.farNode.disconnect(this.workletNode),a&&(this.farNode=a,a.connect(this.workletNode,0,1)))}getStatData(){var a;try{(a=this.workletNode)===null||a===void 0||a.port.postMessage({type:"get_stat_data"})}catch(e){ve.error("Failed to post message to worklet node:",e)}}destroy(){if(this.statUpdateTimer&&window.clearInterval(this.statUpdateTimer),this.audioContext&&this.workletNode&&this.workletNode.port)try{this.workletNode.port.postMessage({type:"destroy"}),this.workletNode.port.onmessage=null,this.workletNode.disconnect(),ve.log("postMessage destroy")}catch(a){ve.error("Failed to post message to worklet node:",a)}}startDump(){var a;try{(a=this.workletNode)===null||a===void 0||a.port.postMessage({type:"start_dump"})}catch(e){ve.error("Failed to post message to worklet node:",e)}}stopDump(){var a;try{(a=this.workletNode)===null||a===void 0||a.port.postMessage({type:"stop_dump"})}catch(e){ve.error("Failed to post message to worklet node:",e)}setTimeout(()=>{this.onDumpOutputData(null,!0),this.onDumpNearInputData(null,!0),this.onDumpFarInputData(null,!0),this.onDumpMeatData(null,!0)},3e3)}onDumpOutputData(a,e=!1){if(a&&a.length>0&&this.collectDumpOutputData.push(a),e&&this.collectDumpOutputData.length>0||1024*this.collectDumpOutputData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpOutputData);this.onDumpData(t,"output_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpOutputData=[]}}onDumpNearInputData(a,e=!1){if(a&&a.length>0&&this.collectDumpNearInputData.push(a),e&&this.collectDumpNearInputData.length>0||1024*this.collectDumpNearInputData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpNearInputData);this.onDumpData(t,"near_input_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpNearInputData=[]}}onDumpFarInputData(a,e=!1){if(a&&a.length>0&&this.collectDumpFarInputData.push(a),e&&this.collectDumpFarInputData.length>0||1024*this.collectDumpFarInputData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpFarInputData);this.onDumpData(t,"far_input_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpFarInputData=[]}}onDumpMeatData(a,e=!1){if(a&&a.length>0&&this.collectDumpMetaData.push(a),e&&this.collectDumpMetaData.length>0||1024*this.collectDumpMetaData.length>=this.getMaxDumpBytes()){let t=new Blob(this.collectDumpMetaData);this.onDumpData(t,"meta_"+this.sampleRate+"hz_"+this.channelCount+"ch.pcm"),this.collectDumpMetaData=[]}}getMaxDumpBytes(){return 600*Number(this.sampleRate.toFixed(0))*Number(this.channelCount.toFixed(0))*2}enable(){var a;if(!((a=this.workletNode)===null||a===void 0)&&a.port)try{this.workletNode.port.postMessage({type:"enable"}),ve.log("postMessage enable")}catch(e){ve.error("Failed to post message to worklet node:",e)}}disable(){var a;if(!((a=this.workletNode)===null||a===void 0)&&a.port)try{ve.log("postMessage disable"),this.workletNode.port.postMessage({type:"disable"})}catch(e){ve.error("Failed to post message to worklet node:",e)}}on(a,e){a==="loaderror"&&(this.onLoadError=e),a==="loadsuccess"&&(this.onLoadSuccess=e),a==="dumpdata"&&(this.onDumpData=e),a==="outputlog"&&(this.onOutputLog=e),a==="statdata"&&(this.onStatData=e)}onLoadError(a){console.log("onLoadError",a)}onLoadSuccess(a){console.log("onLoadSuccess",a)}onDumpData(a,e){console.log("onDumpData",a,e)}onOutputLog(a){console.log("[WASM]",a)}onStatData(a){console.log("onStatData:",a)}}const Si="[AliyunAudio3A] ";class cc extends Dt{constructor(e){super("AliRtcAudioProcessPlugin",Ve.AliRtcSdkStreamTypeCapture,ni.AUDIO);g(this,"audioProcessor");g(this,"slsReporter");g(this,"enableSoft3ACheck",!1);g(this,"useHardOnly",!1);g(this,"lastDiffOutputLog","");g(this,"audioContext",new AudioContext({sampleRate:48e3}));g(this,"farNode");g(this,"createNode",e=>this.audioContext.createMediaStreamSource(new MediaStream([e])));this.options=e,this.slsReporter=e==null?void 0:e.slsReporter,this.enableSoft3ACheck=(e==null?void 0:e.enableSoft3ACheck)||!1,this.useHardOnly=(e==null?void 0:e.useHardOnly)||!1,this.zIndex=7,document.addEventListener("click",this.activeAudioContext)}activeAudioContext(){this.audioContext.resume(),document.removeEventListener("click",this.activeAudioContext)}audioUpdated(e){var t,i;return((t=this.lastInputAudioTrack)==null?void 0:t.id)!==((i=e.currentAudioTrack)==null?void 0:i.id)}videoUpdated(e){return console.log("videoUpdated",e),!1}setOptions(e){var t;!this.farNode&&e.farMediaStream&&(this.farNode=this.audioContext.createMediaStreamSource(e.farMediaStream),this.audioProcessor&&((t=this.audioProcessor)==null||t.addFarNode(this.farNode)),this.options=G(G({},this.options),e))}isSupported(){return sn.isSupported()}shouldUpdate(e){return!!(e.originAudioTrack&&!this.audioProcessor||!e.originAudioTrack&&this.audioProcessor)}process(e){return I(this,null,function*(){var t;if(!e.currentAudioTrack)return e.updateAudioTrack(),void this.clear(e);if(!this.audioProcessor){V.info(Si,"create audio processor this.options:",this.options),this.audioProcessor=new sn({aecOn:!0,ansOn:!0,agcOn:!0,dumpOn:((t=this.options)==null?void 0:t.dumpAudioData)||!1,aiaecOn:this.options.aiaecOn||!1,useHardOnly:this.useHardOnly,wasmCdnPath:this.options.wasmCdnPath||"https://g.alicdn.com/code/npm/@ali/aliyun-audio-3a/0.0.6/"}),this.audioProcessor.on("dumpdata",(r,n)=>{let c=3e3;n.includes("far")?c=5e3:n.includes("output")?c=1e4:n.includes("meta")&&(c=8e3),setTimeout(()=>{const o=URL.createObjectURL(r),d=document.createElement("a");d.href=o,d.download=n,document.body.appendChild(d),d.click(),document.body.removeChild(d)},c)}),this.audioProcessor.on("loadsuccess",()=>{var r,n;V.info(Si,"loadsuccess"),this.enableSoft3ACheck||e.updateAudioTrack((r=this.audioProcessor)==null?void 0:r.targetMediaTrack),this.options.dumpAudioData&&((n=this.audioProcessor)==null||n.startDump())}),this.audioProcessor.on("loaderror",r=>{V.error(Si,"loaderror:",r==null?void 0:r.message),this.emit("error",r)}),this.audioProcessor.on("outputlog",r=>{V.info(Si,"outputlog:",r),r!=null&&r.includes("diff")&&(this.lastDiffOutputLog=r||"")}),this.audioProcessor.on("statdata",r=>{var n;if(r)try{let c=r;if(this.lastDiffOutputLog){const o=this.extractDiffValue(this.lastDiffOutputLog),d=JSON.parse(r);o!==null&&(d.diff=o);const h=this.extractLeakValue(this.lastDiffOutputLog);h!==null&&(d.leak=h),c=JSON.stringify(d)}(n=this.slsReporter)==null||n.reportPublishAudio3A("","","",c)}catch(c){V.error(Si,"statdata error:",c)}});const i=this.createNode(e.currentAudioTrack);yield this.audioProcessor.createProcessor(this.audioContext,i,1,48e3,this.farNode)}})}extractDiffValue(e){if(!e)return null;const t=e.match(/diff\s*=\s*(-?\d+\.?\d*)/);return t?parseFloat(t[1]):null}extractLeakValue(e){if(!e)return null;const t=e.match(/leak\s*=\s*(-?\d+\.?\d*)/);return t?parseFloat(t[1]):null}clear(e){var t,i,r;this.options.dumpAudioData&&((t=this.audioProcessor)==null||t.stopDump()),super.clear(e),(i=this.audioProcessor)==null||i.destroy(),this.audioProcessor=void 0,document.removeEventListener("click",this.activeAudioContext),(r=this.farNode)==null||r.disconnect(),this.farNode=void 0}dump(){var e;(e=this.audioProcessor)==null||e.stopDump()}}var bi=(s=>(s[s.Default=0]="Default",s[s.Human=1]="Human",s[s.Robot=2]="Robot",s))(bi||{}),dc=Object.defineProperty,hc=Object.getOwnPropertyDescriptor,an=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?hc(a,e):a,n=s.length-1;n>=0;n--)(i=s[n])&&(r=(t?i(a,e,r):i(r))||r);return t&&r&&dc(a,e,r),r};const Pr=(Ht=class extends se{constructor(e){super();g(this,"self");g(this,"remoteUser");g(this,"sendReadyMsg",!1);g(this,"hasPubDataChannel",!1);g(this,"hasSubDataChannel",!1);g(this,"readyMsgSuccess",!1);g(this,"sendReadyMsgTimer");g(this,"startReadyMsgTime");g(this,"onSubscribeDataChannel",e=>{!this.remoteUser&&e&&(this.hasSubDataChannel=!0,this.remoteUser=e,this.remoteUser.on("remoteDataChannelMessage",this.onCheckReadyMsg),this.trySendReadyMsg())});g(this,"onCheckReadyMsg",(e,t)=>{var i,r;if(this.sendReadyMsg&&!this.readyMsgSuccess)try{const n=new TextDecoder().decode(t.data),c=JSON.parse(n);c.key==="aliyun_aigc"&&c.type==="ready_resp"&&((i=c.data)==null?void 0:i.ready)===!0&&(V.event(`[${Ht.logName}]`,"onCheckReadyMsg success"),this.readyMsgSuccess=!0,this.emit("dcready",e),(r=this.remoteUser)==null||r.off("remoteDataChannelMessage",this.onCheckReadyMsg),window.clearTimeout(this.sendReadyMsgTimer))}catch(n){}});g(this,"onDataPublishStateChange",(e,t)=>{t===ie.AliRtcStatePublished&&(this.hasPubDataChannel=!0,this.trySendReadyMsg())});this.self=e,this.self.on("dataPublishStateChanged",this.onDataPublishStateChange)}destory(){this.self.off("dataPublishStateChanged",this.onDataPublishStateChange),window.clearTimeout(this.sendReadyMsgTimer),this.remoteUser=void 0,this.sendReadyMsg=!1,this.hasPubDataChannel=!1,this.hasSubDataChannel=!1,this.readyMsgSuccess=!1,this.startReadyMsgTime=0}trySendReadyMsg(){V.event(`[${Ht.logName}]`,`trySendReadyMsg: pub(${this.hasPubDataChannel}, sub: ${this.hasSubDataChannel})`),this.hasPubDataChannel&&this.hasSubDataChannel&&(this.sendReadyMsg=!0,this.sendReadyMsgLoop())}sendReadyMsgLoop(e=0){return I(this,null,function*(){const t=JSON.stringify({key:"aliyun_aigc",version:"1.0",type:"ready_req",data:{ready:!0}});try{this.self.sendDataChannelMessage(new Vt(new TextEncoder().encode(t).buffer))}catch(n){}this.startReadyMsgTime||(this.startReadyMsgTime=Date.now());let i=50;const r=Date.now()-this.startReadyMsgTime;i=r<1e3?50:r<2e3?100:r<3e3?500:2e3,e>30?V.event(`[${Ht.logName}]`,"sendReadyMsgLoop fail after 30 times"):this.sendReadyMsgTimer=window.setTimeout(()=>{this.sendReadyMsgLoop(e+1)},i)})}},g(Ht,"logName","DataChannelReadyHelper"),Ht);an([C()],Pr.prototype,"destory",1),an([C()],Pr.prototype,"sendReadyMsgLoop",1);let lc=Pr;class uc{constructor(a){g(this,"_useSysEchoCancellation",!0);g(this,"_useSysNoiseSuppression",!0);g(this,"_useSysAutoGainControl",!0);g(this,"_useAIAEC",!1);g(this,"_enableSoft3A",!1);g(this,"_enableSoft3ACheck",!1);g(this,"_useHardOnly",!1);g(this,"_dumpAudioData",!1);g(this,"_useAudio3AConfigFromServer",!0);a&&Object.assign(this,a)}get useSysEchoCancellation(){return this._useSysEchoCancellation}set useSysEchoCancellation(a){this._useSysEchoCancellation=a}get useSysNoiseSuppression(){return this._useSysNoiseSuppression}set useSysNoiseSuppression(a){this._useSysNoiseSuppression=a}get useSysAutoGainControl(){return this._useSysAutoGainControl}set useSysAutoGainControl(a){this._useSysAutoGainControl=a}get useAIAEC(){return this._useAIAEC}set useAIAEC(a){this._useAIAEC=a}get enableSoft3A(){return this._enableSoft3A}set enableSoft3A(a){this._enableSoft3A=a}get enableSoft3ACheck(){return this._enableSoft3ACheck}set enableSoft3ACheck(a){this._enableSoft3ACheck=a}get useHardOnly(){return this._useHardOnly}set useHardOnly(a){this._useHardOnly=a}get dumpAudioData(){return this._dumpAudioData}set dumpAudioData(a){this._dumpAudioData=a}get useAudio3AConfigFromServer(){return this._useAudio3AConfigFromServer}set useAudio3AConfigFromServer(a){this._useAudio3AConfigFromServer=a}loadFromLocalConfig(a){var e,t,i,r,n,c,o,d,h;this.useAudio3AConfigFromServer=(e=a.useAudio3AConfigFromServer)!=null?e:this.useAudio3AConfigFromServer,this.useSysEchoCancellation=(t=a.useSysEchoCancellation)!=null?t:this.useSysEchoCancellation,this.useSysNoiseSuppression=(i=a.useSysNoiseSuppression)!=null?i:this.useSysNoiseSuppression,this.useSysAutoGainControl=(r=a.useSysAutoGainControl)!=null?r:this.useSysAutoGainControl,this.useAIAEC=(n=a.useAIAEC)!=null?n:this.useAIAEC,this.enableSoft3A=(c=a.enableSoft3A)!=null?c:this.enableSoft3A,this.dumpAudioData=(o=a.dumpAudioData)!=null?o:this.dumpAudioData,this.enableSoft3ACheck=(d=a.enableSoft3ACheck)!=null?d:this.enableSoft3ACheck,this.useHardOnly=(h=a.useHardOnly)!=null?h:this.useHardOnly}loadFromServerConfig(a){if(a&&typeof a=="object"){const e=ri(a,"enableSoft3A"),t=si(a,"enableSoft3A");if(e===!0&&t===!0&&(this.enableSoft3A=!0),this.enableSoft3A){if(a.archCfgs){const i=ri(a,"enableSoft3ACheck");i!==void 0&&(this.enableSoft3ACheck=i);const r=ri(a,"useAIAEC");r!==void 0&&(this.useAIAEC=r);const n=ri(a,"useSysNoiseSuppression");n!==void 0&&(this.useSysNoiseSuppression=n);const c=ri(a,"useSysEchoCancellation");c!==void 0&&(this.useSysEchoCancellation=c);const o=ri(a,"useSysAutoGainControl");o!==void 0&&(this.useSysAutoGainControl=o)}if(a.config){const i=si(a,"enableSoft3ACheck");i!==void 0&&(this.enableSoft3ACheck=i);const r=si(a,"useAIAEC");r!==void 0&&(this.useAIAEC=r);const n=si(a,"useSysNoiseSuppression");n!==void 0&&(this.useSysNoiseSuppression=n);const c=si(a,"useSysEchoCancellation");c!==void 0&&(this.useSysEchoCancellation=c);const o=si(a,"useSysAutoGainControl");o!==void 0&&(this.useSysAutoGainControl=o)}V.info("setAudio3AConfig:","enableSoft3A",this.enableSoft3A,", enableSoft3ACheck",this.enableSoft3ACheck,", useAIAEC",this.useAIAEC,", useSysNoiseSuppression",this.useSysNoiseSuppression,", useSysEchoCancellation",this.useSysEchoCancellation,", useSysAutoGainControl",this.useSysAutoGainControl)}}}}var pc=Object.defineProperty,mc=Object.getOwnPropertyDescriptor,tt=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?mc(a,e):a,n=s.length-1;n>=0;n--)(i=s[n])&&(r=(t?i(a,e,r):i(r))||r);return t&&r&&pc(a,e,r),r};class Ge extends se{constructor(e){super();g(this,"self");g(this,"userMap",{});g(this,"usersViewMap",{});g(this,"rtsManager");g(this,"localStreamManager");g(this,"authInfo");g(this,"signalingManager");g(this,"pluginManager");g(this,"audioMixerPlugin");g(this,"dualVideoPlugin");g(this,"blankAudioPlugin");g(this,"audioProcessorPlugin");g(this,"slsReporter");g(this,"statsMonitorId");g(this,"autoSubAudio",!0);g(this,"autoSubVideo",!0);g(this,"autoSubScreen",!0);g(this,"wantSubAudio",!0);g(this,"wantSubVideo",!0);g(this,"wantSubScreen",!0);g(this,"defaultStreamType",ze.AliRtcVideoStreamTypeHigh);g(this,"audioMuted",!1);g(this,"playoutVolume",1);g(this,"refreshUrlTimer");g(this,"audioVolumeIndicationInterval",0);g(this,"indicationTimer",0);g(this,"parameter",{});g(this,"audio3AConfig",new uc);g(this,"dcReadyHelper");const{signalingManager:t,slsReporter:i}=e;this.signalingManager=t,this.addSignalingManagerListener(),this.slsReporter=i,this.pluginManager=new Go,this.localStreamManager=new ec(this.pluginManager,this.slsReporter),this.rtsManager=new Yo(this.localStreamManager,this.slsReporter,this.parameter),this.self=new jo({rtsManager:this.rtsManager,localStreamManager:this.localStreamManager,slsReporter:this.slsReporter,signalingManager:this.signalingManager,pluginManager:this.pluginManager,audioVolumeIndicationInterval:this.audioVolumeIndicationInterval,parameter:this.parameter}),this.audioMixerPlugin=new ac,this.pluginManager.add(this.audioMixerPlugin),this.dualVideoPlugin=new nc("dualVideoPlugin"),new X.AliRTS.SupportUtil().checkScreenCapture()&&this.pluginManager.add(new ic)}addSignalingManagerListener(){this.signalingManager.on("onNotifyPublish",e=>{e.forEach(t=>{var i;(i=t==null?void 0:t.tracks)==null||i.forEach(r=>{var n;if(r.msid===M.Audio&&r.userdata)try{const c=JSON.parse(r.userdata);c.agent_instance&&((n=this.slsReporter)==null||n.setCustomFields({ageniid:c.agent_instance}))}catch(c){console.error("Failed to parse userdata:",c)}})}),this.slsReporter.reportConnectionLatencyEvent(ot.RECV_NOTIFY_PUBLISH,"","",""),V.event("[Signaling] Notify Publish ",e),e.forEach(t=>{this.onRemotePublishStateChange(t)})}),this.signalingManager.stsManager.on("onTokenUpdate",(e,t)=>{this.slsReporter.updateToken(t,e)})}isAutoSubAudio(){return this.autoSubAudio}setAutoSubAudio(e){this.autoSubAudio=e}isAutoSubVideo(){return this.autoSubVideo}setAutoSubVideo(e){this.autoSubVideo=e}isAutoSubScreen(){return this.autoSubScreen}setAutoSubScreen(e){this.autoSubScreen=e}isWantSubAudio(){return this.wantSubAudio}setWantSubAudio(e){this.wantSubAudio=e,this.remoteUsers.forEach(t=>{t.setWantSubAudio(e),t.updateSubscribe(be.User)})}isWantSubVideo(){return this.wantSubVideo}setWantSubVideo(e){this.wantSubVideo=e,this.remoteUsers.forEach(t=>{t.setWantSubVideo(e),t.updateSubscribe(be.User)})}isWantSubScreen(){return this.wantSubScreen}setWantSubScreen(e){this.wantSubScreen=e,this.remoteUsers.forEach(t=>{t.setWantSubScreen(e),t.updateSubscribe(be.User)})}setRemoteDefaultVideoStreamType(e){this.defaultStreamType=e,this.remoteUsers.forEach(t=>{t.setRemoteDefaultVideoStreamType(e)})}setRemoteUserVideoStreamType(e,t){var i;(i=this.getRemoteUser(e))==null||i.setRemoteDefaultVideoStreamType(t)}setAudioMuted(e){this.audioMuted=e,this.remoteUsers.forEach(t=>{t.setAudioMuted(e)})}setLocalViewConfig(e,t){var r;if(!e)return(r=this.publisher)==null?void 0:r.setViewConfig(null,t);const i=wr(e);i.length!==0&&i.forEach(n=>{var c,o;(c=this.publisher)==null||c.resetElement(n),Object.values(this.usersViewMap).forEach(({cameraViews:d=[],screenViews:h=[]})=>{d.includes(n)&&d.splice(d.indexOf(n),1),h.includes(n)&&h.splice(h.indexOf(n),1)}),(o=this.publisher)==null||o.setViewConfig(i,t)})}setRemoteViewConfig(e,t,i){var n,c;if(!t)return(n=this.userMap[e])==null?void 0:n.setViewConfig(null,i);const r=wr(t);r.length!==0&&(r.forEach(o=>{var d;(d=this.publisher)==null||d.resetElement(o),Object.values(this.usersViewMap).forEach(({cameraViews:h=[],screenViews:l=[]})=>{h.includes(o)&&h.splice(h.indexOf(o),1),l.includes(o)&&l.splice(l.indexOf(o),1)})}),(c=this.userMap[e])==null||c.setViewConfig(r,i))}get channel(){var e;return(e=this.authInfo)==null?void 0:e.channelId}get userId(){var e;return(e=this.authInfo)==null?void 0:e.userId}get remoteUsers(){return Object.values(this.userMap)}get publisher(){return this.self}get isSubscribing(){var e;return((e=this.remoteUsers)!=null?e:[]).some(t=>{const{isAudioSubscribing:i,isVideoSubscribing:r,isScreenSubscribing:n}=t;return i||r||n})}onRemotePublishStateChange(e,t=!0){var u;const{userid:i,callid:r,subscribe:n,pubid:c="",tracks:o}=e,d=(u=n==null?void 0:n.pullstreamurl)!=null?u:"";let h=this.getRemoteUser(i);if(!h)return;const l=h.streamInfo.audioTrackInfo,p=h.streamInfo.videoTrackInfo;h.updateRemoteTracks(r,d,c,o),l===h.streamInfo.audioTrackInfo&&p===h.streamInfo.videoTrackInfo||this.emit("remoteTrackAvailableChange",i,h.streamInfo.audioTrackInfo,h.streamInfo.videoTrackInfo),t&&h.updateSubscribe(be.Publish)}setTimeoutToUpdateAllStreamUrls(e){var r;if(!e)return;let t=354e4;const i=(r=function(n){var c,o;try{const d=new URL(n),[h,l]=d.pathname.slice(1).split("/"),p=/(\w+)(web\w{5}-\w{4}-\w{4}-\w{4}-\w{12})/.exec(l),u=p==null?void 0:p[1],f=p==null?void 0:p[2],m=new URLSearchParams(d.search);return{appId:h,channelId:u,sessionId:f,timeoutTs:1e3*parseInt((o=(c=m.get("auth_key"))==null?void 0:c.split("-")[0])!=null?o:"0")}}catch(d){return null}}(e))==null?void 0:r.timeoutTs;i&&(t=i-Date.now()-6e4),this.refreshUrlTimer=window.setTimeout(()=>I(this,null,function*(){var c;const n=yield this.signalingManager.refreshUrl({pushstreamurl:this.self.url,users:this.remoteUsers.map(o=>({userid:o.userId,subscribe:{pullstreamurl:o.streamUrl}}))});n.pushstreamurl&&(this.self.url=n.pushstreamurl),(c=n.users)==null||c.forEach(o=>{var h;const d=this.getRemoteUser(o.userid);d&&((h=o.subscribe)!=null&&h.pullstreamurl)&&(d.streamUrl=o.subscribe.pullstreamurl)}),this.setTimeoutToUpdateAllStreamUrls(n.pushstreamurl)}),t)}init(e,t,i){var r;this.authInfo=e,this.self.enableAudioVolumeIndication(this.audioVolumeIndicationInterval),this.self.initInfo(e,t.pushstreamurl),this.audio3AConfig.useAudio3AConfigFromServer&&this.audio3AConfig.loadFromServerConfig((r=t==null?void 0:t.config)==null?void 0:r.data),this.setupAudioProcessingPluginIfNeeded(),i.capabilityProfile===bi.Human&&(this.dcReadyHelper=new lc(this.self),this.dcReadyHelper.on("dcready",n=>{var c;this.emit("remoteUserSubscribedDataChannel",n),(c=this.dcReadyHelper)==null||c.destory(),this.dcReadyHelper=void 0})),this.setTimeoutToUpdateAllStreamUrls(t.pushstreamurl),t.users.forEach(n=>{this.addUser(n,be.InRoom)}),this.startStatsMonitor()}leave(){return I(this,null,function*(){var e;this.stopStatsMonitor(),this.refreshUrlTimer!==void 0&&(window.clearTimeout(this.refreshUrlTimer),this.refreshUrlTimer=void 0),Object.values(this.usersViewMap).forEach(({cameraViews:t=[],screenViews:i=[]})=>{t.forEach(r=>{r.srcObject=null,r._playPromise=void 0}),i.forEach(r=>{r.srcObject=null,r._playPromise=void 0})}),this.usersViewMap={};for(let t in this.userMap)this.userMap[t]&&(this.userMap[t].clear(),delete this.userMap[t]);this.self.leave(),(e=this.dcReadyHelper)==null||e.destory(),this.dcReadyHelper=void 0,this.localStreamManager.stop(),this.rtsManager.clear(),this.authInfo=void 0})}clear(){return I(this,null,function*(){yield this.leave(),this.self.clear(),this.pluginManager.removeAll()})}startStatsMonitor(){this.statsMonitorId=window.setInterval(()=>I(this,null,function*(){if(this.publisher){const{audio:i,video:r,candidate:n}=yield this.publisher.getStats();i&&i.length>0&&this.emit("rtcLocalAudioStats",i),r&&r.length>0&&this.emit("rtcLocalVideoStats",r),n&&this.emit("rtcStats",n)}const e=[],t=[];for(const i of this.remoteUsers){const{audio:r,video:n}=yield i.getStats();r&&r.forEach(c=>{e.push(c)}),n&&n.forEach(c=>{t.push(c)})}e.length>0&&this.emit("rtcRemoteAudioStats",e),t.length>0&&this.emit("rtcRemoteVideoStats",t)}),2e3)}stopStatsMonitor(){this.statsMonitorId&&clearInterval(this.statsMonitorId)}addUser(e,t){const i=e.userid;let r=this.userMap[i];return r||(r=this.executeAddUser(i,e.displayname||"",t),this.userMap[i]=r,this.emit("remoteUserJoin",i,0)),this.onRemotePublishStateChange(e,t!==be.InRoom),r}executeAddUser(e,t,i){const r=new Jo({userId:e,displayName:t,rtsManager:this.rtsManager,signalingManager:this.signalingManager,usersViewMap:this.usersViewMap,slsReporter:this.slsReporter,localUser:this.self,audioVolumeIndicationInterval:this.audioVolumeIndicationInterval,playoutVolume:this.playoutVolume,parameter:this.parameter});return r.on(Ye.Remote,this.onRemoteDeviceStatusChange.bind(this)),r.on(Ee.PullStreamStats,this.onRemoteStatReport.bind(this)),r.on(Ee.RtsSubscribeExceeds,this.onSubscribeExceeds.bind(this)),r.on("audioSubscribeStateChanged",(n,c,o,d)=>{this.emit("audioSubscribeStateChanged",n,c,o,d,this.channel||"")}),r.on("videoSubscribeStateChanged",(n,c,o,d)=>{this.emit("videoSubscribeStateChanged",n,c,o,d,this.channel||"")}),r.on("screenSubscribeStateChanged",(n,c,o,d)=>{this.emit("screenSubscribeStateChanged",n,c,o,d,this.channel||"")}),r.on("dataSubscribeStateChanged",(n,c,o,d)=>{var h;o===me.AliRtcStateSubscribed&&((h=this.dcReadyHelper)==null||h.onSubscribeDataChannel(this.userMap[n])),this.emit("dataSubscribeStateChanged",n,c,o,d,this.channel||"")}),r.on("remoteAudioAutoPlayFail",n=>{this.emit("remoteAudioAutoPlayFail",n)}),r.on("remoteVideoAutoPlayFail",(n,c)=>{this.emit("remoteVideoAutoPlayFail",n,c)}),r.on("remoteAudioPlayError",(n,c)=>{this.emit("remoteAudioPlayError",n,c)}),r.on("remoteVideoPlayError",(n,c)=>{this.emit("remoteVideoPlayError",n,c)}),r.on("remoteSubscribeError",n=>{this.emit("remoteSubscribeError",n,r.userId)}),r.on("occurError",n=>{this.emit("occurError",n,r.userId)}),r.on("remoteDataChannelMessage",(n,c)=>{this.emit("remoteDataChannelMessage",n,c)}),r.setWantSubAudio(this.autoSubAudio&&this.wantSubAudio),r.setWantSubVideo(this.autoSubVideo&&this.wantSubVideo),r.setWantSubScreen(this.autoSubScreen&&this.wantSubScreen),r.setRemoteDefaultVideoStreamType(this.defaultStreamType),r.setAudioMuted(this.audioMuted),(this.autoSubAudio||this.autoSubVideo||this.autoSubScreen)&&r.updateSubscribe(i),r}onRemoteDeviceStatusChange(e,t){e===Ee.MuteAudio?this.emit("userAudioMuted",t,!0):e===Ee.UnmuteAudio?this.emit("userAudioMuted",t,!1):e===Ee.MuteVideo?this.emit("userVideoMuted",t,!0):e===Ee.UnmuteVideo?this.emit("userVideoMuted",t,!1):e===Ee.MuteScreen?this.emit("userScreenMuted",t,!0):e===Ee.UnmuteScreen&&this.emit("userScreenMuted",t,!1)}onRemoteStatReport(e,t,i){this.emit(Ee.PullStreamStats,e,t,i)}onSubscribeExceeds(e,t){this.emit(Ee.RtsSubscribeExceeds,e,t)}removeLeftUser(e){return I(this,null,function*(){e.userid&&this.userMap[e.userid]&&(yield this.userMap[e.userid].clear(!1),delete this.userMap[e.userid])})}diffUsers(e){const t=[],i=[];e.forEach(n=>{n.userid&&(this.userMap[n.userid]?i.push(n):t.push(n))});const r=Object.keys(this.userMap).filter(n=>!e.find(c=>c.userid===n)).map(n=>({userid:n,reason:"",leavecode:Rr.AliRtcUserOfflineQuit}));return{joinList:t,leaveList:r,presentList:i}}getRemoteUser(e){return this.userMap[e]}updateRemoteUserDeviceStatus(e){e&&e.userid&&this.userMap[e.userid]&&this.userMap[e.userid].updateRemoteUserDeviceStatus(e.status)}updateAudioWant(e,t){const i=this.userMap[e];if(!i)throw new O(U.ERR_INNER,`no remote user(${e}) founded`);i.setWantSubAudio(t),t?i.updateSubscribe(be.User):i.stopSubscribe({audio:!0})}updateVideoWant(e,t){const i=this.userMap[e];if(!i)throw new O(U.ERR_INNER,`no remote user(${e}) founded`);i.setWantSubVideo(t),t?i.updateSubscribe(be.User):i.stopSubscribe({video:!0})}updateScreenWant(e,t){const i=this.userMap[e];if(!i)throw new O(U.ERR_INNER,`no remote user(${e}) founded`);i.setWantSubScreen(t),t?i.updateSubscribe(be.User):i.stopSubscribe({screen:!0})}stopIndication(){this.indicationTimer&&window.clearInterval(this.indicationTimer)}startIndication(e){this.stopIndication(),this.indicationTimer=window.setInterval(()=>{const t=this.remoteUsers.map(i=>({userId:i.userId,volume:i.getAudioLevel()||0}));t.unshift({userId:"",volume:this.self.getAudioLevel()||0}),this.emit("audioVolume",t)},e)}setEnableDualVideoStream(e,t){if(!this.dualVideoPlugin)return;t&&this.dualVideoPlugin.setOptions(t);const i=this.pluginManager.has(this.dualVideoPlugin.name);e?!i&&this.pluginManager.add(this.dualVideoPlugin):i&&this.pluginManager.remove(this.dualVideoPlugin.name)}setAudioVolume(e){var t;(t=this.audioMixerPlugin)==null||t.setOptions(e)}enableAudioVolumeIndication(e){this.audioVolumeIndicationInterval!==e&&(this.audioVolumeIndicationInterval>0&&e<=0&&this.stopIndication(),e>0&&this.startIndication(e),this.audioVolumeIndicationInterval=e,this.remoteUsers.forEach(t=>{t.enableAudioVolumeIndication(e)}),this.self.enableAudioVolumeIndication(e))}setPlayoutVolume(e){this.playoutVolume=e,this.remoteUsers.forEach(t=>{t.setPlayoutVolume(e)})}refreshAuthInfo(e){this.authInfo&&(this.authInfo=G(G({},this.authInfo),e)),e.userId&&this.self.refreshUserInfo(e.userId)}setEnableMediaExtensionMsg(e){this.rtsManager.setEncodedInsertableStreams(e)}setAudioRedEnabled(e){this.rtsManager.setAudioRedEnabled(e)}setVideoCodec(e){this.rtsManager.changeVideoCodec(e)}setParameter(e){var i,r,n,c;const t=JSON.parse(e);Object.keys(t).forEach(o=>{const d=this.parameter[o],h=t[o];this.parameter[o]=typeof d=="object"&&typeof h=="object"?G(G({},d),h):h}),t.enableBlankAudio===!0?(this.blankAudioPlugin||(this.blankAudioPlugin=new rc),this.pluginManager.has((i=this.blankAudioPlugin)==null?void 0:i.name)||this.pluginManager.add(this.blankAudioPlugin)):t.enableBlankAudio===!1&&(this.blankAudioPlugin&&this.pluginManager.remove((r=this.blankAudioPlugin)==null?void 0:r.name),(n=this.blankAudioPlugin)==null||n.clear(),this.blankAudioPlugin=void 0),t.audio&&((c=this.audio3AConfig)==null||c.loadFromLocalConfig(t.audio))}setupAudioProcessingPluginIfNeeded(){if(this.audio3AConfig.enableSoft3A){let e=0;this.audio3AConfig.enableSoft3ACheck&&(e=1e4),setTimeout(()=>{this.audioProcessorPlugin||(this.audioProcessorPlugin=new cc({dumpAudioData:this.audio3AConfig.dumpAudioData,aiaecOn:this.audio3AConfig.useAIAEC,slsReporter:this.slsReporter,enableSoft3ACheck:this.audio3AConfig.enableSoft3ACheck,useHardOnly:this.audio3AConfig.useHardOnly})),this.audioProcessorPlugin&&!this.pluginManager.has(this.audioProcessorPlugin.name)&&(this.audioProcessorPlugin.on("error",({message:t})=>{var i;V.error("audioProcessorPlugin error:",t),(i=this.self.audioTrack)==null||i.applyConstraints({echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0})}),this.pluginManager.add(this.audioProcessorPlugin))},e)}else this.audioProcessorPlugin&&(this.pluginManager.remove(this.audioProcessorPlugin.name),this.audioProcessorPlugin=void 0);this.self.setMicrophoneConstraints({echoCancellation:this.audio3AConfig.useSysEchoCancellation,noiseSuppression:this.audio3AConfig.useSysNoiseSuppression,autoGainControl:this.audio3AConfig.useSysAutoGainControl})}getParameter(){return JSON.stringify(this.parameter)}sendDataChannelMessage(e){return this.self.sendDataChannelMessage(e)}}g(Ge,"logName","BizControl"),tt([C()],Ge.prototype,"init",1),tt([C()],Ge.prototype,"leave",1),tt([C()],Ge.prototype,"clear",1),tt([C(H)],Ge.prototype,"addUser",1),tt([C()],Ge.prototype,"removeLeftUser",1),tt([C()],Ge.prototype,"diffUsers",1),tt([C(H)],Ge.prototype,"updateAudioWant",1),tt([C(H)],Ge.prototype,"updateVideoWant",1),tt([C(H)],Ge.prototype,"updateScreenWant",1),tt([C()],Ge.prototype,"stopIndication",1),tt([C()],Ge.prototype,"startIndication",1),tt([C(H)],Ge.prototype,"setEnableDualVideoStream",1),tt([C(H)],Ge.prototype,"setAudioVolume",1),tt([C()],Ge.prototype,"enableAudioVolumeIndication",1);var vi=(s=>(s[s.LiveTranscodingSingle=0]="LiveTranscodingSingle",s[s.LiveTranscodingMix=1]="LiveTranscodingMix",s))(vi||{}),Dr=(s=>(s[s.LiveTranscodingOrigin=0]="LiveTranscodingOrigin",s[s.LiveTranscodingAudio=1]="LiveTranscodingAudio",s[s.LiveTranscodingVideo=2]="LiveTranscodingVideo",s))(Dr||{}),ci=(s=>(s[s.LiveTranscodingCamera=0]="LiveTranscodingCamera",s[s.LiveTranscodingShareScreen=1]="LiveTranscodingShareScreen",s))(ci||{});const yi={0:"camera",1:"shareScreen"};var Mr=(s=>(s[s.LiveTranscoding_Profile_1IN_1080P=0]="LiveTranscoding_Profile_1IN_1080P",s[s.LiveTranscoding_Profile_1IN_720P=1]="LiveTranscoding_Profile_1IN_720P",s[s.LiveTranscoding_Profile_1IN_360P=2]="LiveTranscoding_Profile_1IN_360P",s[s.LiveTranscoding_Profile_2IN_1080P=3]="LiveTranscoding_Profile_2IN_1080P",s[s.LiveTranscoding_Profile_2IN_720P=4]="LiveTranscoding_Profile_2IN_720P",s[s.LiveTranscoding_Profile_2IN_360P=5]="LiveTranscoding_Profile_2IN_360P",s[s.LiveTranscoding_Profile_4IN_1080P=6]="LiveTranscoding_Profile_4IN_1080P",s[s.LiveTranscoding_Profile_4IN_720P=7]="LiveTranscoding_Profile_4IN_720P",s[s.LiveTranscoding_Profile_4IN_360P=8]="LiveTranscoding_Profile_4IN_360P",s[s.LiveTranscoding_Profile_9IN_1080P=9]="LiveTranscoding_Profile_9IN_1080P",s[s.LiveTranscoding_Profile_9IN_720P=10]="LiveTranscoding_Profile_9IN_720P",s[s.LiveTranscoding_Profile_9IN_360P=11]="LiveTranscoding_Profile_9IN_360P",s[s.LiveTranscoding_Profile_12IN_1080P=12]="LiveTranscoding_Profile_12IN_1080P",s[s.LiveTranscoding_Profile_12IN_720P=13]="LiveTranscoding_Profile_12IN_720P",s[s.LiveTranscoding_Profile_12IN_360P=14]="LiveTranscoding_Profile_12IN_360P",s[s.LiveTranscoding_Profile_16IN_1080P=15]="LiveTranscoding_Profile_16IN_1080P",s[s.LiveTranscoding_Profile_16IN_720P=16]="LiveTranscoding_Profile_16IN_720P",s[s.LiveTranscoding_Profile_16IN_360P=17]="LiveTranscoding_Profile_16IN_360P",s[s.LiveTranscoding_Profile_Mixed=9999]="LiveTranscoding_Profile_Mixed",s))(Mr||{});const gc={0:"1IN_1080P",1:"1IN_720P",2:"1IN_360P",3:"2IN_1080P",4:"2IN_720P",5:"2IN_360P",6:"4IN_1080P",7:"4IN_720P",8:"4IN_360P",9:"9IN_1080P",10:"9IN_720P",11:"9IN_360P",12:"12IN_1080P",13:"12IN_720P",14:"12IN_360P",15:"16IN_1080P",16:"16IN_720P",17:"16IN_360P",9999:"Mixed_Audio"};var Wi=(s=>(s[s.LiveTranscoding_HZ_48000=48e3]="LiveTranscoding_HZ_48000",s[s.LiveTranscoding_HZ_44100=44100]="LiveTranscoding_HZ_44100",s[s.LiveTranscoding_HZ_32000=32e3]="LiveTranscoding_HZ_32000",s[s.LiveTranscoding_HZ_16000=16e3]="LiveTranscoding_HZ_16000",s[s.LiveTranscoding_HZ_8000=8e3]="LiveTranscoding_HZ_8000",s))(Wi||{}),Ai=(s=>(s[s.LiveTranscodingNoBody=0]="LiveTranscodingNoBody",s[s.LiveTranscodingBody=1]="LiveTranscodingBody",s))(Ai||{}),Ri=(s=>(s[s.NOTO_SERIF_CJKSC_REGULAR=0]="NOTO_SERIF_CJKSC_REGULAR",s[s.ALIBABA_PUHUITI_REGULAR=1]="ALIBABA_PUHUITI_REGULAR",s[s.ALIBABA_PUHUITI_BOLD=2]="ALIBABA_PUHUITI_BOLD",s[s.ALIBABA_PUHUITI_Heavy=3]="ALIBABA_PUHUITI_Heavy",s[s.ALIBABA_PUHUITI_LIGHT=4]="ALIBABA_PUHUITI_LIGHT",s[s.ALIBABA_PUHUITI_MEDIUM=5]="ALIBABA_PUHUITI_MEDIUM",s))(Ri||{}),Lr=(s=>(s[s.LiveTranscodingOrigin=0]="LiveTranscodingOrigin",s[s.LiveTranscodingCrop=1]="LiveTranscodingCrop",s[s.LiveTranscodingFill=2]="LiveTranscodingFill",s))(Lr||{}),$i=(s=>(s[s.LiveTranscodingNormal=0]="LiveTranscodingNormal",s[s.LiveTranscodingVirtualBackground=1]="LiveTranscodingVirtualBackground",s))($i||{}),Nr=(s=>(s[s.LiveTranscodingState_IDLE=0]="LiveTranscodingState_IDLE",s[s.LiveTranscodingState_CONNNECT=1]="LiveTranscodingState_CONNNECT",s[s.LiveTranscodingState_RUNNING=2]="LiveTranscodingState_RUNNING",s[s.LiveTranscodingState_RECOVERING=3]="LiveTranscodingState_RECOVERING",s[s.LiveTranscodingState_FAILURE=4]="LiveTranscodingState_FAILURE",s[s.LiveTranscodingState_END=5]="LiveTranscodingState_END",s))(Nr||{}),Et=(s=>(s[s.LiveTranscodingErrorPublishOk=0]="LiveTranscodingErrorPublishOk",s[s.LiveTranscodingErrorStreamNotFound=17825793]="LiveTranscodingErrorStreamNotFound",s[s.LiveTranscodingErrorStreamAlreadyExist=17825794]="LiveTranscodingErrorStreamAlreadyExist",s[s.LiveTranscodingErrorInvalidParam=17825795]="LiveTranscodingErrorInvalidParam",s[s.LiveTranscodingErrorInternalError=17825796]="LiveTranscodingErrorInternalError",s[s.LiveTranscodingErrorRtmpServerError=17825797]="LiveTranscodingErrorRtmpServerError",s[s.LiveTranscodingErrorRtmpStreamUrlError=17825798]="LiveTranscodingErrorRtmpStreamUrlError",s[s.LiveTranscodingErrorPublishTimeout=17825799]="LiveTranscodingErrorPublishTimeout",s[s.LiveTranscodingErrorNotAuthorized=17825800]="LiveTranscodingErrorNotAuthorized",s))(Et||{}),xr=(s=>(s[s.TrascodingPublishTaskStatusStart=0]="TrascodingPublishTaskStatusStart",s[s.TrascodingPublishTaskStatusUpdate=1]="TrascodingPublishTaskStatusUpdate",s[s.TrascodingPublishTaskStatusStop=2]="TrascodingPublishTaskStatusStop",s))(xr||{}),it=(s=>(s[s.MPU_TASK_TRANSACTION_START=0]="MPU_TASK_TRANSACTION_START",s[s.MPU_TASK_TRANSACTION_UPDATE=1]="MPU_TASK_TRANSACTION_UPDATE",s[s.MPU_TASK_TRANSACTION_STOP=2]="MPU_TASK_TRANSACTION_STOP",s[s.MPU_TASK_TRANSACTION_LIST=3]="MPU_TASK_TRANSACTION_LIST",s[s.MPU_TASK_TRANSACTION_POLLING=4]="MPU_TASK_TRANSACTION_POLLING",s[s.MPU_TASK_TRANSACTION_ACKNOWLEDGE=5]="MPU_TASK_TRANSACTION_ACKNOWLEDGE",s[s.MPU_TASK_TRANSACTION_END=6]="MPU_TASK_TRANSACTION_END",s))(it||{});const fc={0:"/libra/v1/sdk/start-task",1:"/libra/v1/sdk/update-task",2:"/libra/v1/sdk/stop-task",3:"/libra/v1/sdk/list-task",4:"/libra/v1/sdk/polling",5:"/libra/v1/sdk/acknowledge",6:"/"};class Vr{constructor(a,e,t,i,r,n,c,o){g(this,"videoWidth");g(this,"videoHeight");g(this,"videoFramerate",20);g(this,"videoBitrate",2e3);g(this,"videoGop",30);g(this,"audioSamplerate",Wi.LiveTranscoding_HZ_44100);g(this,"audioBitrate",500);g(this,"audioChannels",1);this.videoWidth=a,this.videoHeight=e,t&&(this.videoFramerate=t),i&&(this.videoBitrate=i),r&&(this.videoGop=r),n&&(this.audioSamplerate=n),c&&(this.audioBitrate=c),o&&(this.audioChannels=o)}}const Or=s=>((16711680&s)>>16)+(65280&s)+((255&s)<<16),pt=(s=0,a)=>{if(a==0)return 0;let e=s/a;return e<0&&(e=0),e>1&&(e=1),e};class Ki{constructor(a,e,t){g(this,"mixMode",vi.LiveTranscodingSingle);g(this,"singleParam");g(this,"mixParam");a&&(this.mixMode=a),e&&(this.singleParam=e),t&&(this.mixParam=t)}toJson(a,e,t,i,r){const n={appid:e.appId,channelid:e.channelId};if(a===it.MPU_TASK_TRANSACTION_POLLING||a===it.MPU_TASK_TRANSACTION_LIST||a===it.MPU_TASK_TRANSACTION_ACKNOWLEDGE)return a===it.MPU_TASK_TRANSACTION_ACKNOWLEDGE&&(n.messageid=r),n;if(n.taskid=t,a!==it.MPU_TASK_TRANSACTION_STOP){if(n.mixmode=this.mixMode,i&&(n.streamurl=i),this.mixMode===vi.LiveTranscodingSingle){const c=this.singleParam;if(c){n.streamtype=c.streamType,c.sourceType===ci.LiveTranscodingShareScreen?n.sourcetype=yi[c.sourceType]:n.sourcetype=yi[ci.LiveTranscodingCamera];const o=[];c.userId&&o.push(c.userId),n.subspecusers=o}}else if(a===it.MPU_TASK_TRANSACTION_START||a===it.MPU_TASK_TRANSACTION_UPDATE){const c=this.mixParam;if(c){c.taskProfile&&(n.taskprofile=gc[c.taskProfile]);const o=c.encodeParam||new Vr(1280,720);let d=o.videoWidth,h=o.videoHeight;const l={};Object.keys(o).forEach(u=>{const f=o[u];f>0&&(l[u.toLowerCase()]=f)}),l.lowbitratehighquality=0,n.encodeparam=l,n.backgrounds=c.backgrounds.map(u=>u.toJson(d,h)),n.watermarks=c.watermarks.map(u=>u.toJson(d,h)),n.clockwidgets=c.clockWidgets.map(u=>u.toJson(d,h));const p=c.users.map(u=>u.userId);n.subspecusers=[...new Set(p)],n.layouts=[{audiomixcount:c.users.length,panes:c.users.map((u,f)=>u.toJson(f,d,h,c.mediaProcessMode))}],n.layoutids=["0"],n.cropmode=c.cropMode,n.backgroundcolor=Or(c.backgroundColor),n.taskmode=c.mediaProcessMode}}}return n}}const Ur=s=>I(this,null,function*(){const a=new Uint8Array(160).fill(170),e=new TextEncoder().encode(s),t=yield window.crypto.subtle.importKey("raw",a,{name:"HMAC",hash:{name:"SHA-1"}},!1,["sign"]),i=yield window.crypto.subtle.sign("HMAC",t,e);return Array.from(new Uint8Array(i)).map(r=>r.toString(16).padStart(2,"0")).join("")});class Sc{constructor(a){g(this,"authInfo");g(this,"slsReporter");this.slsReporter=a}doRequest(a,e){var c;const t=this.authInfo;if(!t)return Promise.reject(Et.LiveTranscodingErrorInvalidParam);const i=fc[a],r={appid:t.appId,userid:t.userId,channelid:t.channelId,timestamp:t.timestamp,token:t.token,nonce:t.nonce?t.nonce:"",requestid:nt.createCallid(),tokensid:!1,session:(c=t.sessionId)!=null?c:nt.createCallid()},n=Object.keys(r).map(o=>`${o}=${encodeURIComponent(r[o])}`).join("&");return fetch(`https://gw.rtn.aliyuncs.com${i}?${n}`,{method:"POST",headers:{"Content-Type":"application/json; charset=UTF-8"},body:JSON.stringify(e)}).then(o=>o.status!==200?(this.slsReporter.reportTranscodingError(o.status,e.taskid||""),Promise.reject(new O(U.ERR_INNER,`transcoding request failed, status: ${o.status}`))):o).catch(o=>Promise.reject(new O(U.ERR_INNER,`transcoding request failed, err: ${o.message}`)))}setAuthInfo(a){this.authInfo=a}clear(){this.authInfo=void 0}startPublishLiveStream(a,e){return I(this,null,function*(){if(!this.authInfo)return Promise.reject(Et.LiveTranscodingErrorInvalidParam);const t=yield Ur(a.split("?")[0]),i=it.MPU_TASK_TRANSACTION_UPDATE,r=e.toJson(i,this.authInfo,t,a);return this.doRequest(i,r)})}startPublishLiveStreamWithTaskId(a,e){return I(this,null,function*(){if(!this.authInfo)return Promise.reject(Et.LiveTranscodingErrorInvalidParam);const t=it.MPU_TASK_TRANSACTION_UPDATE,i=e.toJson(t,this.authInfo,a);return this.doRequest(t,i)})}updatePublishLiveStream(a,e){return I(this,null,function*(){if(!this.authInfo)return Promise.reject(Et.LiveTranscodingErrorInvalidParam);const t=yield Ur(a.split("?")[0]),i=it.MPU_TASK_TRANSACTION_UPDATE,r=e.toJson(i,this.authInfo,t,a);return this.doRequest(i,r)})}updatePublishLiveStreamWithTaskId(a,e){return I(this,null,function*(){if(!this.authInfo)return Promise.reject(Et.LiveTranscodingErrorInvalidParam);const t=it.MPU_TASK_TRANSACTION_UPDATE,i=e.toJson(t,this.authInfo,a);return this.doRequest(t,i)})}stopPublishLiveStream(a){return I(this,null,function*(){if(!this.authInfo)return Promise.reject(Et.LiveTranscodingErrorInvalidParam);const e=yield Ur(a.split("?")[0]),t=it.MPU_TASK_TRANSACTION_STOP,i=new Ki().toJson(t,this.authInfo,e,a);return this.doRequest(t,i)})}stopPublishLiveStreamWithTaskId(a){if(!this.authInfo)return Promise.reject(Et.LiveTranscodingErrorInvalidParam);const e=it.MPU_TASK_TRANSACTION_STOP,t=new Ki().toJson(e,this.authInfo,a);return this.doRequest(e,t)}refreshAuthInfo(a){this.authInfo&&this.setAuthInfo(G(G({},this.authInfo),a))}}const Qt=class Qt{constructor(){g(this,"ntpClock");this.ntpClock=new X.AliRTS.Clock}static getInstance(){return Qt.instance||(Qt.instance=new Qt),Qt.instance}now(){return this.ntpClock.now()}};g(Qt,"instance");let Br=Qt;const nn=()=>Br.getInstance(),{BrowserUtil:Hr,SystenUtil:on}=X.AliRTS;class cn{constructor(){g(this,"tracker");g(this,"param");g(this,"msgCacheArr",[]);g(this,"index",0);g(this,"stsOpt");g(this,"slsToken");g(this,"ossToken");g(this,"ntpClock");this.ntpClock=nn()}createTracker(){if(!this.tracker&&this.slsToken&&this.param){const a=this.slsToken;this.ossToken&&(this.param.ossbn=this.ossToken.bucket_name,this.param.ossep=this.ossToken.region_endpoint);const e=new pr({host:a.region_endpoint,project:a.project,logstore:a.log_store_stats}),t={accessKeyId:a.access_key_id,accessKeySecret:a.access_key_secret,securityToken:a.security_token,refreshSTSToken:()=>{this.slsToken&&(t.accessKeyId=this.slsToken.access_key_id,t.accessKeySecret=this.slsToken.access_key_secret,t.securityToken=this.slsToken.security_token)}};this.stsOpt=t;const i=fr(t);e.useStsPlugin(i),this.tracker=e,this.msgCacheArr.forEach((r,n)=>{var c,o;(o=this.tracker)==null||o.send(G(vt(G({},this.param),{stat_log_id:`${((c=this.param)==null?void 0:c.sesid)||"nosession"}-${n}`}),r))}),this.index=this.index+this.msgCacheArr.length,this.msgCacheArr=[]}}start(a){this.initParam(a),this.createTracker()}updateToken(a,e){this.slsToken=a,this.ossToken=e,this.createTracker()}stop(){this.tracker=void 0,this.param=void 0,this.msgCacheArr=[],this.index=0,this.stsOpt=void 0,this.slsToken=void 0,this.ossToken=void 0}sendReport(a){var t,i;let e;a.tm=Date.now();try{e=JSON.parse(JSON.stringify(G(vt(G({bt:Hr.browserName||"unknown",ntptm:this.ntpClock.now(),ntpofs:this.ntpClock.now()-Date.now()},this.param),{stat_log_id:`${((t=this.param)==null?void 0:t.sesid)||"nosession"}-${this.index}`}),a)))}catch(r){}e&&(this.tracker?((i=this.tracker)==null||i.send(e),this.index++):this.msgCacheArr.push(e))}initParam(a){let e="";try{e=(localStorage==null?void 0:localStorage.getItem("AliRtcUUID"))||"",e||(e=dt(),localStorage==null||localStorage.setItem("AliRtcUUID",e))}catch(t){}this.param||(this.param={apid:a.appId,usrid:a.userId,statsvrs:"0.6.1",evetid:0,sesid:a.sessionId,sessionId:a.sessionId,channelid:a.channelId,usrn:a.userId,osn:on.systemName,osv:on.systemVersion,deb:xo(),den:Mo(),udid:e,sdkvrs:Li,acs:"Unknown",cput:Ba(),dm:`${window.location.protocol}//${window.location.host}`,bt:Hr.browserName,bv:Hr.browserVersion,envir:"PRODUCT",args:"",instid:dt()})}}const Ae=(s,a=1,e=6e4,t=0)=>{let i=s;return i||(i=0),Math.min(e,Math.max(t,Math.round(i*a)))},mt=(s,a,e=2e7,t=0)=>{let i=a;(!a||a<0||a>1e4)&&(i=1e3);let r=s;return r||(r=0),Math.min(e,Math.max(t,Math.round(r/(i/1e3))))},qt=(s,a)=>{if(a===0||!a)return"0.00";let e=s;return(!e||e<0)&&(e=0),(e/a*100).toFixed(2)},dn=s=>s>=0&&s<=1?Ae(Math.floor(32767*s),1,32767):0,we=(s,a)=>{var t,i,r;let e=((t=s._last)==null?void 0:t[a])||0;return s.ssrc&&((i=s._last)!=null&&i.ssrc)&&s.ssrc!==((r=s._last)==null?void 0:r.ssrc)&&(e=0),((s==null?void 0:s[a])||0)-e},hn=(s,a)=>Ae(we(s,a),1e3,1e4),Xt=(s,a=2e7)=>Ae(s,1,a),_i=class _i{constructor(a){g(this,"engine");g(this,"logClient");g(this,"authInfo");g(this,"ntpClock");g(this,"customFields",{});this.logClient=new cn,this.engine=a,this.ntpClock=nn()}static getLogClient(){return this.staticClient||(this.staticClient=new cn),this.staticClient}static reportOSSUpload(a,e,t=0){_i.getLogClient().sendReport({errmsg:`${e}/${a}.log`,errtype:t,evetid:70017,sesid:a,sessionId:a,stat_log_id:`${a}-70017`})}setCustomFields(a){this.customFields=G(G({},this.customFields),a)}getCustomField(a){return this.customFields[a]}start(a){this.authInfo=a,this.logClient.start(a)}updateToken(a,e){this.logClient.updateToken(a,e),_i.getLogClient().updateToken(a,e)}stop(){this.logClient.stop()}reportPublishAudio3A(a,e,t,i){const r={};let n=JSON.parse(i);r.publevel=n.capture_audio_cur_level_db||0,r.eleakrate=n.echo_leak_rate||0,r.playbw=n.render_bandwidth||-1,r.capbw=n.capture_bandwidth||-1,r.diff=n.diff||0,r.leak=n.leak||0,this.log({evetid:10070,traceid:t,calid:a,args:this.data2String(G({calid:a,tckid:e||"audio3a",traceid:t},r))})}reportPublishMonitor(a,e,t,i,r){if(!t||r.length<=0)return;const n=t===M.Audio,c={ctm:Math.floor(r[0].timestamp||0),src:r[0].ssrc||"",codec:r[0]._codec||""},o=[],d=[],h=[],l=[],p=[],u=[],f=[],m=[],b=[],S=[],v=[],_=[],w=[],y=[],A=[],R=[],E=[],T=[],k=[];try{if(r.forEach(P=>{var x,de,ke,$,ge,Me;if(!P||!P.timestamp)return;const B=(x=P._last)!=null&&x.timestamp?P.timestamp-P._last.timestamp:1e3,q=we(P,"bytesSent"),Y=we(P,"headerBytesSent"),J=mt(Ae(q+Y,8,2e7),B);o.push(J);const z=mt(Ae(q,8,2e7),B);d.push(z);const Z=mt(Ae(Y,8,2e7),B);h.push(Z);const ee=we(P,"packetsSent"),pe=mt(ee,B);l.push(pe);const D=we(P,"packetsLost"),N=mt(D,B);p.push(N);const L=qt(D,ee);if(u.push(L),n)(de=P._source)!=null&&de.audioLevel&&f.push(dn(P._source.audioLevel)),m.push(0);else{b.push(hn(P,"totalEncodeTime")),S.push(Xt((ke=P._source)==null?void 0:ke.framesPerSecond,100)),v.push(Xt(($=P._source)==null?void 0:$.framesPerSecond,100)),_.push(Xt(P.framesPerSecond,100)),w.push(Xt((ge=P._source)==null?void 0:ge.height,4400)),y.push(Xt((Me=P._source)==null?void 0:Me.width,7700)),A.push(Xt(P.frameHeight,4400)),R.push(Xt(P.frameWidth,7700));const Re=we(P,"totalPacketSendDelay");E.push(Ae(Re,1/(D||1),2e3));const Ie=we(P,"qpSum");T.push(Ae(Ie,1/(P.framesPerSecond||1),51)),k.push(0)}}),c.sbr=o.join(","),c.mbrs=d.join(","),c.pbrs=h.join(","),c.ps=l.join(","),c.pl=p.join(","),c.plr=u.join(","),n){const P=(i==null?void 0:i.getSettings().sampleRate)||0;c.ailevel=f.join(","),c.arpc=m.join(","),c.arsr=P,c.aesr=P,c.publevel=-90,c.rawlevel=-90}else c.em=b.join(","),c.cfps=S.join(","),c.ifps=v.join(","),c.sfps=_.join(","),c.ih=w.join(","),c.iw=y.join(","),c.sh=A.join(","),c.sw=R.join(","),c.sd=E.join(","),c.aqp=T.join(","),c.caf=k.join(","),c.can=k.join(","),c.cav=d.join(","),c.ifimax=k.join(","),c.ifimin=k.join(","),c.efimax=k.join(","),c.efimin=k.join(","),c.sfimax=k.join(","),c.sfimin=k.join(","),c.apsnr=k.join(",")}catch(P){}this.log({evetid:10070,traceid:e,calid:a,args:this.data2String(G({calid:a,tckid:t,traceid:e},c))})}reportSubscribeMonitor(a,e,t,i,r){if(!i||!r||r.length<=0)return;const n=i===M.Audio,c={ctm:Math.floor(r[0].timestamp||0),src:r[0].ssrc||"",codec:r[0]._codec||""},o=[],d=[],h=[],l=[],p=[],u=[],f=[],m=[],b=[],S=[],v=[],_=[],w=[],y=[],A=[],R=[],E=[],T=[],k=[],P=[],B=[],q=[],Y=[],J=[],z=[],Z=[],ee=[],pe=[],D=[],N=[],L=[],x=[],de=[],ke=[];try{r.forEach($=>{var le,Fe;if(!$||!$.timestamp)return;const ge=(le=$._last)!=null&&le.timestamp?$.timestamp-$._last.timestamp:1e3,Me=we($,"bytesReceived"),Re=we($,"headerBytesReceived"),Ie=mt(Ae(Me+Re,8,2e7),ge);o.push(Ie);const fe=mt(Ae(Me,8,2e7),ge);d.push(fe);const _e=mt(Ae(Re,8,2e7),ge);h.push(_e);const he=we($,"packetsReceived"),Pe=mt(he,ge);l.push(Pe);const ye=we($,"packetsLost"),Je=mt(ye,ge);p.push(Je);const rt=qt(ye,he);u.push(rt);const ae=we($,"jitterBufferDelay"),re=we($,"jitterBufferEmittedCount");if($.jitterBufferDelay&&$.jitterBufferEmittedCount){const Q=Ae(ae,1e3/re,1e4);f.push(Q)}else f.push(0);const te=we($,"fecPacketsReceived");_.push(qt(te,he));const Se=we($,"retransmittedPacketsReceived"),Oe=he+ye-Se;if(b.push(qt(he-Se,Oe)),S.push(qt(ye,Oe)),m.push(qt(Se,Oe)),v.push(Oe),de.push(0),ke.push(""),n){y.push(dn($.audioLevel));const Q=((Ne,St)=>{var It,bt,Ft;return(((It=Ne==null?void 0:Ne._source)==null?void 0:It[St])||0)-(((Ft=(bt=Ne==null?void 0:Ne._last)==null?void 0:bt._source)==null?void 0:Ft[St])||0)})($,"synthesizedSamplesEvents");A.push(Q);const Le=hn($,"synthesizedSamplesDuration");R.push(Le);const st=qt(Le,ge);w.push(st),E.push(0)}else{const Q=(Fe=$._last)!=null&&Fe.totalInterFrameDelay?$.totalInterFrameDelay-$._last.totalInterFrameDelay:0;T.push(Ae(Q,1e3/($.framesDecoded||30),500)),k.push(Ae($.framesPerSecond,1,100)),P.push(we($,"framesReceived")),x.push(we($,"framesRendered")),B.push(Ae($.frameHeight,1,4400)),q.push(Ae($.frameWidth,1,7700));const Le=we($,"totalProcessingDelay");Y.push(Ae(Le,1e3/($.framesDecoded||30),12e4));const st=we($,"nackCount");z.push(st);const Ne=we($,"pliCount");J.push(Ne);const St=we($,"qpSum");Z.push(Ae(St,1/($.framesPerSecond||1),51)),ee.push(Ae($.framesDropped));const It=we($,"totalFreezesDuration");pe.push(Ae(It,1e3,3e4));const bt=we($,"jitterBufferEmittedCount"),Ft=we($,"jitterBufferDelay");Ft&&bt?D.push(Ae(Ft,1e3/bt,3e4)):D.push(0);const Ei=we($,"jitterBufferTargetDelay");Ei&&bt?N.push(Ae(Ei,1e3/bt,3e4)):N.push(0);const Gi=we($,"jitterBufferMinimumDelay");Gi&&bt?L.push(Ae(Gi,1e3/bt,3e4)):L.push(0)}}),c.rbr=o.join(","),c.mbrs=d.join(","),c.pbrs=h.join(","),c.pr=l.join(","),c.pl=p.join(","),c.plr=u.join(","),c.jd=f.join(","),c.fecr=_.join(","),c.retransr=m.join(","),c.baser=b.join(","),c.basel=S.join(","),c.recoverr=de.join(","),c.alll=S.join(","),c.totalc=v.join(","),n?(c.er=w.join(","),c.aolevel=y.join(","),c.asrc=E.join(","),c.scnt=A.join(","),c.sdura=R.join(",")):(c.dm=T.join(","),c.dfps=k.join(","),c.rfps=P.join(","),c.rh=B.join(","),c.rw=q.join(","),c.fpt=ke.join(","),c.ns=z.join(","),c.pliss=J.join(","),c.aqp=Z.join(","),c.ofimax=de.join(","),c.ofimin=de.join(","),c.dfimax=de.join(","),c.dfimin=de.join(","),c.rfimax=de.join(","),c.rfimin=de.join(","),c.vrstutter=pe.join(","),c.cdm=D.join(","),c.tdm=N.join(","),c.pdm=L.join(","),c.ofps=x.join(","),c.dfbd=ee.join(","))}catch($){}this.log({evetid:10080,traceid:t,rmtid:e,calid:a,args:this.data2String(G({calid:a,rmtid:e,tckid:i,traceid:t},c))})}reportNetworkMonitor(a){if(a.length<=0)return;const e=[],t=[],i=[],r=[],n=[],c=[],o=[],d=[],h=[],l=[];a.forEach((u,f)=>{var b;if(!u.timestamp)return;const m=(b=u._last)!=null&&b.timestamp?u.timestamp-u._last.timestamp:1e3;e.push(Ae(u.currentRoundTripTime,1e3)),t.push(Ae(u.availableOutgoingBitrate,8,2e8)),i.push(mt(Ae(u.bytesSent,8,2e7),m,25e6)),r.push(mt(Ae(u.bytesReceived,8,2e7),m,25e6)),n.push(0),c.push(0),f%5==0&&(o.push(""),d.push(""),h.push(""),l.push(""))});const p={ctm:Math.floor(a[0].timestamp||0),rtt:e.join(","),bsps:i.join(","),brps:r.join(","),cpu:o.join(","),mem:d.join(","),sysmem:h.join(","),systotalmem:l.join(","),audioonly:this.engine.isAudioOnly()?1:0};this.log({evetid:10071,args:this.data2String(G({asb:t.join(","),abms:n.join(","),vbms:c.join(",")},p))}),this.log({evetid:10081,args:this.data2String(G({},p))})}reportLoopAudioDelay(a,e){var f;const{AIAgent:t={},AIGrtn:i={},AIPub:r={},AISub:n={},pub:c={},sub:o={},grtn:d={}}=e||{};if(Object.keys(t).length===0)return;let h=0;h=Object.keys(d).length?(c.vTotalCost||0)+(c.upRTTHalf||0)+(d.totalCost||0)+(o.downRTTHalf||0)+(o.vTotalCost||0):(c.vEncPlugCost||0)+((c.timestampRecv||0)-(c.timestamp||0))+(o.vJitterBufferDelay||0)+(o.vDecPlugCost||0);const l={};let p=0;for(let m=0;m<10;m++){const b=`ngxRtcSeiCumulativeDelayKeyInternalRttHalf_${m}`,S=`ngxRtcSeiCumulativeDelayKeyGrtnNodeBefPacer_${m}`,v=`ngxRtcSeiCumulativeDelayKeyGrtnNodePacerCost_${m}`;if(!d.hasOwnProperty(b))break;p+=d[b]||0,p+=d[S]||0,p+=d[v]||0,l[`_gnd${m}`]=`gnd[${m}]: {${this.data2String({gnirh:d[b]||0,gnbp:d[S]||0,gnpc:d[v]||0})}}`}const u={};for(let m=0;m<10;m++){const b=`aigrtninternalrtthalf_${m}`,S=`aigrtnbeforepacer_${m}`,v=`aigrtnpacercost_${m}`;if(!i.hasOwnProperty(b))break;u[`_lgnd${m}`]=`lgnd[${m}]: {${this.data2String({gnirh:i[b]||0,gnbp:i[S]||0,gnpc:i[v]||0})}}`}this.log({evetid:10073,args:this.data2String(vt(G({tdlms:h+(t.aiagenttotalcost||0),_:`aiqud:{${this.data2String(vt(G({uid:((f=this.authInfo)==null?void 0:f.userId)||"",sid:r.aAIClientScentenceId||0,quct:65535*(r.aAIClientQuestionTimestampHEAD||0)+(r.aAIClientQuestionTimestampTAIL||0),anct:65535*(r.aAIClientAnswerTimestampHEAD||0)+(r.aAIClientAnswerTimestampTAIL||0),casc:r.aAIClientSourceCost||0,camc:r.aAIClientMixerCost||0,caec:r.aAIClientEncoderCost||0,cantc:r.aIClientNetsdkThrCost||0,caqtc:r.aIClientQosThrCost||0,capc:r.aIClientPacerCost||0,cuphr:r.aIClientUpRTTHalf||0},u),{qgac:0,ldhr:d.ngxRtcSeiCumulativeDelayKeyDownRttHalf_0||0,larc:n.aAILinuxReceiveCost||0,lanqc:n.aAILinuxNeteqCost||0,larsc:n.aAILinuxRemoteSourceCost||0,lapmc:n.aAILinuxPlayMixerCost||0,lapc:n.aAILinuxPlayCost||0,lsdnc:n.aIClinetSmartDenoise||0,asrc:t.aiasrcost||0,llmc:t.aillmcost||0,ttsc:t.aittscost||0,aamc:t.aimutecost||0,aatc:t.aiagenttotalcost||0}))}};`,ssrc:a,tpd:0,scc:r.aAIClientSourceCost||0,mxc:r.aAIClientMixerCost||0,encc:r.aAIClientEncoderCost||0,netc:r.aIClientNetsdkThrCost||0,qostc:r.aIClientQosThrCost||0,pacerc:r.aIClientPacerCost||0,uphr:r.aIClientUpRTTHalf||0},l),{agac:p,dnhr:o.downRTTHalf||0,tsd:o.vTotalCost||0,rcc:n.aAILinuxReceiveCost||0,nqc:n.aAILinuxNeteqCost||0,rscc:n.aAILinuxRemoteSourceCost||0,plmxc:n.aAILinuxPlayMixerCost||0,plc:n.aAILinuxPlayCost||0,dvd:0}))})}reportJoin(a,e,t=""){var l,p;const{start:i,rs:r=0,re:n=0}=e,c=Date.now()-i,o=n-r;let d=0;r&&(d=r-i);let h=0;n&&(h=n-r),this.log({evetid:10010,args:this.data2String({sesid:((l=this.authInfo)==null?void 0:l.sessionId)||"",joitm:c,rslt:a,gslbtm:0,dnstm:0,avcftm:0,gslbrslt:0,dnsrslt:0,avcfrslt:0,mode:2,jrtc:o,usrn:(p=this.authInfo)==null?void 0:p.userId,mgt:"cdn",cttc:d,iptc:h,ndn:1,gslbloc:1,ccag:0,ucag:0,cpg:0,upg:0,tid:t})})}reportJoinConnection(a){this.log({evetid:20002,args:this.data2String(G({transretrynum:0,ldnstc:0,tcptc:0,ssltc:0,url:""},a))})}reportLeave(a,e,t){this.log({evetid:10020,args:this.data2String({lvetm:a,rslt:e,tid:t})})}reportPublish(a,e,t,i,r,n,c,o,d,h,l){this.log({evetid:a?10032:10030,calid:t,args:this.data2String({calid:t,url:e,isvl:i?1:0,isvs:r?1:0,isvss:n?1:0,isaudio:c?1:0,rslt:o,tid:"123",pubtm:Date.now()-l,pctid:d,pubtid:h,isvp:0,isarecording:0,isad:0,isdc:0,pubretry:0,pbrttimes:0})})}reportPublishFirstPacket(a,e,t,i,r,n,c,o,d){const h=Date.now();this.log({evetid:a?10033:10031,calid:e,args:this.data2String({calid:e,fpst:h-t,tckid:n,est:t,pctid:c,pubtid:o,totaltm:h-r,jorm:d===yt.JOIN_CHANNEL?1:0,cptc:0,sptc:i-t,iptc:0,ipc2fptc:0,dctc:0,patc:0})})}reportUnpublish(a,e,t,i){var r;this.log({evetid:10040,args:this.data2String({calid:a,unpubtm:e,rslt:t,tid:i,sesid:((r=this.authInfo)==null?void 0:r.sessionId)||""})})}reportSubscribe(a,e,t,i,r,n,c,o,d,h){this.log({evetid:10050,calid:a,rmtid:e,args:this.data2String(G({calid:a,rmtid:e,isvl:t?1:0,isvs:i?1:0,isvss:r?1:0,isaudio:n?1:0,rslt:c,tid:o,subtm:d,isvp:0,isaplaying:0,isad:0,isdc:0,subretry:0,sbrttimes:0},h))})}reportSubscribeFirstPacket(a,e,t,i,r){this.log({evetid:a?10054:10051,calid:e,rmtid:t,args:this.data2String(G({calid:e,rmtid:t,tckid:i,cptc:0,iptc:0,ipc2fptc:0,dctc:0,patc:0},r))})}reportSubscribeFirstFrame(a,e,t,i,r){this.log({evetid:a?10055:10052,calid:e,rmtid:t,args:this.data2String(G({calid:e,rmtid:t,tckid:i},r))}),this.log({evetid:a?10058:10057,args:this.data2String(G({calid:e,rmtid:t,tckid:i},r))})}reportUnsubscribe(a,e,t,i,r){this.log({evetid:10060,calid:a,args:this.data2String({calid:a,rmtid:e,unsubtm:t,rslt:i,tid:r})})}reportMute(a,e,t){this.log({evetid:11030,args:this.data2String({calid:a,rmtid:"",enable:e?1:0,mt:t})})}reportRoleUpdate(a,e){this.log({evetid:11040,args:this.data2String({or:a||"",nr:e,ctm:Date.now(),rslt:0})})}reportRoleUpdateResult(a,e,t,i){this.log({evetid:11041,args:this.data2String({or:a||"",nr:e,ctm:t,rslt:i})})}reportVideoProfile(a){this.log({evetid:20074,args:this.data2String({pf:a,tckid:"sophon_camera_large"})})}reportScreenProfile(a){this.log({evetid:20074,args:this.data2String({pf:a,tckid:"sophon_screenshare"})})}reportError(a){this.log({evetid:10091,args:this.data2String({rslt:(a==null?void 0:a.code)||-1})})}reportWarning(a){this.log({evetid:10092,args:this.data2String({rslt:-1,errmsg:a})})}reportRoomServerEvent(a,e,t,i){this.log({evetid:20005,args:this.data2String({calid:"",rmtid:"",rt:a?0:1,dr:a?"s":"r",mt:e,ri:t,cs:1,srt:Date.now(),rspc:(i==null?void 0:i.code)||"",mc:JSON.stringify(i)})})}reportTranscodingError(a,e){this.log({evetid:10101,args:this.data2String({rslt:a,taskid:e})})}reportBye(a){var e;this.log({evetid:10093,args:this.data2String({rslt:a,sesid:((e=this.authInfo)==null?void 0:e.sessionId)||""})})}reportAudio(a,e,t){var i;this.log({evetid:80013,args:this.data2String({rslt:a?-1:0,adm:1,adt:0,adr:a?2:0,acms:e,adrpn:t})}),this.log({evetid:80014,args:this.data2String({sesid:((i=this.authInfo)==null?void 0:i.sessionId)||"",rslt:a?-1:0,adm:1,adt:0,adr:a?2:0,acms:e,adrpn:t})})}reportScreen(a,e){var t,i,r,n;this.log({evetid:90013,args:this.data2String({rslt:a?-1:0,vcms:e,vde:(t=a==null?void 0:a.code)!=null?t:-1,sesid:((i=this.authInfo)==null?void 0:i.sessionId)||""})}),this.log({evetid:90014,args:this.data2String({rslt:a?-1:0,vcms:e,vde:(r=a==null?void 0:a.code)!=null?r:-1,sesid:((n=this.authInfo)==null?void 0:n.sessionId)||""})})}reportScreenStop(a){this.log({evetid:90019,args:this.data2String({rslt:a?a.code||-1:0})}),this.log({evetid:90020,args:this.data2String({rslt:a?a.code||-1:0})})}reportSwitchCamera(a){var e;this.log({evetid:90025,args:this.data2String({rslt:0,td:a,sesid:((e=this.authInfo)==null?void 0:e.sessionId)||""})})}reportPublishProfile(a,e){this.log({evetid:10201,args:this.data2String(G({tckid:a},e))})}reportSDKCreated(a){this.log({evetid:70011,createtm:Date.now()-a,tm:a})}reportJoinInvoked(a){this.log({evetid:70012,jnnonce:a.nonce||"",jntoken:a.token||"",jntm:a.timestamp||""})}reportJoinResult(a){this.log({evetid:70013,rslt:a?a.code||-1:0,dnsrslt:0})}reportSTSResult(a,e){this.log({evetid:70014,rslt:a,asty:1,reqtm:Date.now()-e})}reportLeaveInvoked(){this.log({evetid:70015})}reportSEIMessage(a,e,t,i,r){this.log({evetid:40301,args:this.data2String({tm:Date.now(),sei_pt:a,sei_len:e,sei_rep:t,sei_delay:i,sei_key:r})})}reportConnectionLatencyEvent(a,e,t,i,r,n,c=!1){const o={ageniid:this.getCustomField("ageniid")},d=G({tm:r||Date.now(),ntptm:n||this.ntpClock.now(),stage:a,status:e,calid:t,tckid:i,cltp:1,http:c?1:0},o);this.log({evetid:12001,args:this.data2String(d)})}log(a){a&&(a.tm=new Date().getTime(),V.debug("[ConsoleLogger]","log",a),this.logClient.sendReport(a))}data2String(a){let e="";for(let t in a)e.length&&(e+="&"),e+=t.startsWith("_")?a[t]:`${t}=${a[t]}`;return e}};g(_i,"staticClient");let Fr=_i;const di=class di extends se{constructor(e){super();g(this,"ws");g(this,"socketStatus",0);g(this,"wsUrl","");g(this,"lastConnectStartTime",0);g(this,"maxConnectRetryCount",12);g(this,"connectRetryCount",0);g(this,"gotErr",!1);g(this,"closedByInvoke",!0);g(this,"isReconnecting",!1);g(this,"networkAvailableChecked",!0);g(this,"reconnectTimeoutId",0);this.maxConnectRetryCount=e!=null?e:12,this.onOpen=this.onOpen.bind(this),this.onMessage=this.onMessage.bind(this),this.onError=this.onError.bind(this),this.onClose=this.onClose.bind(this)}get connectUrl(){return this.wsUrl}get connectStatus(){return this.socketStatus}start(e){this.wsUrl=e,this.initWebSocket()}send(e){return!(!this.ws||this.socketStatus!==2)&&(this.ws.send(JSON.stringify(e)),!0)}close(){this.closedByInvoke=!0,this.uninitWebsocket()}reconnect(){this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=0),this.emit("onReconnectStart"),this.isReconnecting=!0,this.initWebSocket()}onOpen(e){V.info(`[${di.logName}]`,"onOpen"),this.socketStatus=2,this.connectRetryCount=0,this.networkAvailableChecked=!1,this.closedByInvoke=!1,this.gotErr=!1,this.isReconnecting=!1,this.emit("onOpen",e)}onMessage(e){this.emit("onMessage",e)}onError(e){this.isReconnecting&&this.emit("onReconnectFail",e),this.emit("onError",e),this.isReconnecting=!1,this.socketStatus!==2&&nt.isNetworkAvailable().then(t=>{t&&console.error(di.logName,"onError, Network is available, token may be invalid")})}onClose(e){return I(this,null,function*(){if(this.closedByInvoke)this.socketStatus=0;else{if(V.info(`[${di.logName}]`,`onClose, code: ${e.code}, reason: ${e.reason}, status: ${status}, retryCount: ${this.connectRetryCount}`),(yield nt.isNetworkAvailable())&&!this.networkAvailableChecked)return this.reconnect(),void(this.networkAvailableChecked=!0);this.connectRetryCount||this.emit("onNetworkError"),!this.reconnectTimeoutId&&(this.connectRetryCount+=1,this.connectRetryCount>this.maxConnectRetryCount?this.emit("onConnectFail"):Date.now()-this.lastConnectStartTime>=5e3?this.reconnect():this.reconnectTimeoutId=window.setTimeout(()=>{this.reconnect()},5e3)),this.socketStatus=0,this.emit("onClose",e)}})}initWebSocket(){this.uninitWebsocket(),this.socketStatus=1,this.lastConnectStartTime=Date.now(),this.ws=new WebSocket(this.wsUrl),this.ws.addEventListener("open",this.onOpen),this.ws.addEventListener("message",this.onMessage),this.ws.addEventListener("error",this.onError),this.ws.addEventListener("close",this.onClose)}uninitWebsocket(){this.ws&&(this.ws.removeEventListener("open",this.onOpen),this.ws.removeEventListener("message",this.onMessage),this.ws.removeEventListener("error",this.onError),this.ws.removeEventListener("close",this.onClose),this.ws.readyState!==WebSocket.CLOSED&&this.ws.close(),this.ws=void 0,this.socketStatus=0)}};g(di,"logName","Socket");let jr=di;var zr={exports:{}};(function(s,a){(function(e,t){var i="function",r="undefined",n="object",c="string",o="major",d="model",h="name",l="type",p="vendor",u="version",f="architecture",m="console",b="mobile",S="tablet",v="smarttv",_="wearable",w="embedded",y="Amazon",A="Apple",R="ASUS",E="BlackBerry",T="Browser",k="Chrome",P="Firefox",B="Google",q="Huawei",Y="LG",J="Microsoft",z="Motorola",Z="Opera",ee="Samsung",pe="Sharp",D="Sony",N="Xiaomi",L="Zebra",x="Facebook",de="Chromium OS",ke="Mac OS",$=" Browser",ge=function(ae){for(var re={},te=0;te<ae.length;te++)re[ae[te].toUpperCase()]=ae[te];return re},Me=function(ae,re){return typeof ae===c&&Re(re).indexOf(Re(ae))!==-1},Re=function(ae){return ae.toLowerCase()},Ie=function(ae,re){if(typeof ae===c)return ae=ae.replace(/^\s\s*/,""),typeof re===r?ae:ae.substring(0,500)},fe=function(ae,re){for(var te,Se,Oe,le,Fe,Q,Le=0;Le<re.length&&!Fe;){var st=re[Le],Ne=re[Le+1];for(te=Se=0;te<st.length&&!Fe&&st[te];)if(Fe=st[te++].exec(ae))for(Oe=0;Oe<Ne.length;Oe++)Q=Fe[++Se],typeof(le=Ne[Oe])===n&&le.length>0?le.length===2?typeof le[1]==i?this[le[0]]=le[1].call(this,Q):this[le[0]]=le[1]:le.length===3?typeof le[1]!==i||le[1].exec&&le[1].test?this[le[0]]=Q?Q.replace(le[1],le[2]):t:this[le[0]]=Q?le[1].call(this,Q,le[2]):t:le.length===4&&(this[le[0]]=Q?le[3].call(this,Q.replace(le[1],le[2])):t):this[le]=Q||t;Le+=2}},_e=function(ae,re){for(var te in re)if(typeof re[te]===n&&re[te].length>0){for(var Se=0;Se<re[te].length;Se++)if(Me(re[te][Se],ae))return te==="?"?t:te}else if(Me(re[te],ae))return te==="?"?t:te;return re.hasOwnProperty("*")?re["*"]:ae},he={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},Pe={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[u,[h,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[u,[h,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[h,u],[/opios[\/ ]+([\w\.]+)/i],[u,[h,Z+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[u,[h,Z+" GX"]],[/\bopr\/([\w\.]+)/i],[u,[h,Z]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[u,[h,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[u,[h,"Maxthon"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer|sleipnir)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim(?:browser|boat|jet))[\/ ]?([\d\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|duckduckgo|klar|helio|(?=comodo_)?dragon)\/([-\w\.]+)/i,/(heytap|ovi|115)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[h,u],[/quark(?:pc)?\/([-\w\.]+)/i],[u,[h,"Quark"]],[/\bddg\/([\w\.]+)/i],[u,[h,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[u,[h,"UC"+T]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[u,[h,"WeChat"]],[/konqueror\/([\w\.]+)/i],[u,[h,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[u,[h,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[u,[h,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[u,[h,"Smart Lenovo "+T]],[/(avast|avg)\/([\w\.]+)/i],[[h,/(.+)/,"$1 Secure "+T],u],[/\bfocus\/([\w\.]+)/i],[u,[h,P+" Focus"]],[/\bopt\/([\w\.]+)/i],[u,[h,Z+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[u,[h,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[u,[h,"Dolphin"]],[/coast\/([\w\.]+)/i],[u,[h,Z+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[u,[h,"MIUI"+$]],[/fxios\/([\w\.-]+)/i],[u,[h,P]],[/\bqihoobrowser\/?([\w\.]*)/i],[u,[h,"360"]],[/\b(qq)\/([\w\.]+)/i],[[h,/(.+)/,"$1Browser"],u],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[h,/(.+)/,"$1"+$],u],[/samsungbrowser\/([\w\.]+)/i],[u,[h,ee+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[u,[h,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[h,"Sogou Mobile"],u],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[h,u],[/(lbbrowser|rekonq)/i,/\[(linkedin)app\]/i],[h],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[u,h],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[h,x],u],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i],[h,u],[/\bgsa\/([\w\.]+) .*safari\//i],[u,[h,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[u,[h,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[u,[h,k+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[h,k+" WebView"],u],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[u,[h,"Android "+T]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[h,u],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[u,[h,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[u,h],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[h,[u,_e,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[h,u],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[h,"Netscape"],u],[/(wolvic|librewolf)\/([\w\.]+)/i],[h,u],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[u,[h,P+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i],[h,[u,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[h,[u,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[f,"amd64"]],[/(ia32(?=;))/i],[[f,Re]],[/((?:i[346]|x)86)[;\)]/i],[[f,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[f,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[f,"armhf"]],[/windows (ce|mobile); ppc;/i],[[f,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[f,/ower/,"",Re]],[/(sun4\w)[;\)]/i],[[f,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[f,Re]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[d,[p,ee],[l,S]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr])[-\w]+)/i,/sec-(sgh\w+)/i],[d,[p,ee],[l,b]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[d,[p,A],[l,b]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[d,[p,A],[l,S]],[/(macintosh);/i],[d,[p,A]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[d,[p,pe],[l,b]],[/(?:honor)([-\w ]+)[;\)]/i],[d,[p,"Honor"],[l,b]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[d,[p,q],[l,S]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[d,[p,q],[l,b]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite|pro)?)(?: bui|\))/i],[[d,/_/g," "],[p,N],[l,b]],[/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[d,/_/g," "],[p,N],[l,S]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[d,[p,"OPPO"],[l,b]],[/\b(opd2\d{3}a?) bui/i],[d,[p,"OPPO"],[l,S]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[d,[p,"Vivo"],[l,b]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[d,[p,"Realme"],[l,b]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[d,[p,z],[l,b]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[d,[p,z],[l,S]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[d,[p,Y],[l,S]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[d,[p,Y],[l,b]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[d,[p,"Lenovo"],[l,S]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[d,/_/g," "],[p,"Nokia"],[l,b]],[/(pixel c)\b/i],[d,[p,B],[l,S]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[d,[p,B],[l,b]],[/droid.+; (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[d,[p,D],[l,b]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[d,"Xperia Tablet"],[p,D],[l,S]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[d,[p,"OnePlus"],[l,b]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[d,[p,y],[l,S]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[d,/(.+)/g,"Fire Phone $1"],[p,y],[l,b]],[/(playbook);[-\w\),; ]+(rim)/i],[d,p,[l,S]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[d,[p,E],[l,b]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[d,[p,R],[l,S]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[d,[p,R],[l,b]],[/(nexus 9)/i],[d,[p,"HTC"],[l,S]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[p,[d,/_/g," "],[l,b]],[/droid [\w\.]+; ((?:8[14]9[16]|9(?:0(?:48|60|8[01])|1(?:3[27]|66)|2(?:6[69]|9[56])|466))[gqswx])\w*(\)| bui)/i],[d,[p,"TCL"],[l,S]],[/(itel) ((\w+))/i],[[p,Re],d,[l,_e,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[d,[p,"Acer"],[l,S]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[d,[p,"Meizu"],[l,b]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[d,[p,"Ulefone"],[l,b]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[d,[p,"Energizer"],[l,b]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[d,[p,"Cat"],[l,b]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[d,[p,"Smartfren"],[l,b]],[/droid.+; (a(?:015|06[35]|142p?))/i],[d,[p,"Nothing"],[l,b]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron|infinix|tecno|micromax|advan)[-_ ]?([-\w]*)/i,/; (imo) ((?!tab)[\w ]+?)(?: bui|\))/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[p,d,[l,b]],[/(imo) (tab \w+)/i,/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[p,d,[l,S]],[/(surface duo)/i],[d,[p,J],[l,S]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[d,[p,"Fairphone"],[l,b]],[/(u304aa)/i],[d,[p,"AT&T"],[l,b]],[/\bsie-(\w*)/i],[d,[p,"Siemens"],[l,b]],[/\b(rct\w+) b/i],[d,[p,"RCA"],[l,S]],[/\b(venue[\d ]{2,7}) b/i],[d,[p,"Dell"],[l,S]],[/\b(q(?:mv|ta)\w+) b/i],[d,[p,"Verizon"],[l,S]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[d,[p,"Barnes & Noble"],[l,S]],[/\b(tm\d{3}\w+) b/i],[d,[p,"NuVision"],[l,S]],[/\b(k88) b/i],[d,[p,"ZTE"],[l,S]],[/\b(nx\d{3}j) b/i],[d,[p,"ZTE"],[l,b]],[/\b(gen\d{3}) b.+49h/i],[d,[p,"Swiss"],[l,b]],[/\b(zur\d{3}) b/i],[d,[p,"Swiss"],[l,S]],[/\b((zeki)?tb.*\b) b/i],[d,[p,"Zeki"],[l,S]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[p,"Dragon Touch"],d,[l,S]],[/\b(ns-?\w{0,9}) b/i],[d,[p,"Insignia"],[l,S]],[/\b((nxa|next)-?\w{0,9}) b/i],[d,[p,"NextBook"],[l,S]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[p,"Voice"],d,[l,b]],[/\b(lvtel\-)?(v1[12]) b/i],[[p,"LvTel"],d,[l,b]],[/\b(ph-1) /i],[d,[p,"Essential"],[l,b]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[d,[p,"Envizen"],[l,S]],[/\b(trio[-\w\. ]+) b/i],[d,[p,"MachSpeed"],[l,S]],[/\btu_(1491) b/i],[d,[p,"Rotor"],[l,S]],[/(shield[\w ]+) b/i],[d,[p,"Nvidia"],[l,S]],[/(sprint) (\w+)/i],[p,d,[l,b]],[/(kin\.[onetw]{3})/i],[[d,/\./g," "],[p,J],[l,b]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[d,[p,L],[l,S]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[d,[p,L],[l,b]],[/smart-tv.+(samsung)/i],[p,[l,v]],[/hbbtv.+maple;(\d+)/i],[[d,/^/,"SmartTV"],[p,ee],[l,v]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[p,Y],[l,v]],[/(apple) ?tv/i],[p,[d,A+" TV"],[l,v]],[/crkey/i],[[d,k+"cast"],[p,B],[l,v]],[/droid.+aft(\w+)( bui|\))/i],[d,[p,y],[l,v]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[d,[p,pe],[l,v]],[/(bravia[\w ]+)( bui|\))/i],[d,[p,D],[l,v]],[/(mitv-\w{5}) bui/i],[d,[p,N],[l,v]],[/Hbbtv.*(technisat) (.*);/i],[p,d,[l,v]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[p,Ie],[d,Ie],[l,v]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[l,v]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[p,d,[l,m]],[/droid.+; (shield) bui/i],[d,[p,"Nvidia"],[l,m]],[/(playstation [345portablevi]+)/i],[d,[p,D],[l,m]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[d,[p,J],[l,m]],[/\b(sm-[lr]\d\d[05][fnuw]?s?)\b/i],[d,[p,ee],[l,_]],[/((pebble))app/i],[p,d,[l,_]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[d,[p,A],[l,_]],[/droid.+; (glass) \d/i],[d,[p,B],[l,_]],[/droid.+; (wt63?0{2,3})\)/i],[d,[p,L],[l,_]],[/droid.+; (glass) \d/i],[d,[p,B],[l,_]],[/(pico) (4|neo3(?: link|pro)?)/i],[p,d,[l,_]],[/; (quest( \d| pro)?)/i],[d,[p,x],[l,_]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[p,[l,w]],[/(aeobc)\b/i],[d,[p,y],[l,w]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[d,[l,b]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[d,[l,S]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[l,S]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[l,b]],[/(android[-\w\. ]{0,9});.+buil/i],[d,[p,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[u,[h,"EdgeHTML"]],[/(arkweb)\/([\w\.]+)/i],[h,u],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[u,[h,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna|servo)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[h,u],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[u,h]],os:[[/microsoft (windows) (vista|xp)/i],[h,u],[/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i],[h,[u,_e,he]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[u,_e,he],[h,"Windows"]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[u,/_/g,"."],[h,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[h,ke],[u,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[u,h],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish|openharmony)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[h,u],[/\(bb(10);/i],[u,[h,E]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[u,[h,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[u,[h,P+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[u,[h,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[u,[h,"watchOS"]],[/crkey\/([\d\.]+)/i],[u,[h,k+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[h,de],u],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[h,u],[/(sunos) ?([\w\.\d]*)/i],[[h,"Solaris"],u],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[h,u]]},ye=function(ae,re){if(typeof ae===n&&(re=ae,ae=t),!(this instanceof ye))return new ye(ae,re).getResult();var te=typeof e!==r&&e.navigator?e.navigator:t,Se=ae||(te&&te.userAgent?te.userAgent:""),Oe=te&&te.userAgentData?te.userAgentData:t,le=re?function(Q,Le){var st={};for(var Ne in Q)Le[Ne]&&Le[Ne].length%2==0?st[Ne]=Le[Ne].concat(Q[Ne]):st[Ne]=Q[Ne];return st}(Pe,re):Pe,Fe=te&&te.userAgent==Se;return this.getBrowser=function(){var Q,Le={};return Le[h]=t,Le[u]=t,fe.call(Le,Se,le.browser),Le[o]=typeof(Q=Le[u])===c?Q.replace(/[^\d\.]/g,"").split(".")[0]:t,Fe&&te&&te.brave&&typeof te.brave.isBrave==i&&(Le[h]="Brave"),Le},this.getCPU=function(){var Q={};return Q[f]=t,fe.call(Q,Se,le.cpu),Q},this.getDevice=function(){var Q={};return Q[p]=t,Q[d]=t,Q[l]=t,fe.call(Q,Se,le.device),Fe&&!Q[l]&&Oe&&Oe.mobile&&(Q[l]=b),Fe&&Q[d]=="Macintosh"&&te&&typeof te.standalone!==r&&te.maxTouchPoints&&te.maxTouchPoints>2&&(Q[d]="iPad",Q[l]=S),Q},this.getEngine=function(){var Q={};return Q[h]=t,Q[u]=t,fe.call(Q,Se,le.engine),Q},this.getOS=function(){var Q={};return Q[h]=t,Q[u]=t,fe.call(Q,Se,le.os),Fe&&!Q[h]&&Oe&&Oe.platform&&Oe.platform!="Unknown"&&(Q[h]=Oe.platform.replace(/chrome os/i,de).replace(/macos/i,ke)),Q},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return Se},this.setUA=function(Q){return Se=typeof Q===c&&Q.length>500?Ie(Q,500):Q,this},this.setUA(Se),this};ye.VERSION="1.0.40",ye.BROWSER=ge([h,u,o]),ye.CPU=ge([f]),ye.DEVICE=ge([d,p,l,m,b,v,S,_,w]),ye.ENGINE=ye.OS=ge([h,u]),s.exports&&(a=s.exports=ye),a.UAParser=ye;var Je=typeof e!==r&&(e.jQuery||e.Zepto);if(Je&&!Je.ua){var rt=new ye;Je.ua=rt.getResult(),Je.ua.get=function(){return rt.getUA()},Je.ua.set=function(ae){rt.setUA(ae);var re=rt.getResult();for(var te in re)Je.ua[te]=re[te]}}})(typeof window=="object"?window:Pi)})(zr,zr.exports);var bc=zr.exports,He=(s=>(s.KEEPALIVE="keepalive",s.JOINCHANNEL="joinchannel",s.NOTIFYJOIN="notifyjoin",s.NOTIFYSTATUS="notifystatus",s.STATUSREPORT="statusreport",s.LEAVECHANNEL="leavechannel",s.NOTIFYLEAVE="notifyleave",s.NOTIFYPUBLISH="notifypublish",s.BYE="bye",s.RECONNECT="reconnect",s.PUBLISH="publish",s.REFRESHURL="refreshurl",s.UNSUBSCRIBE="unsubscribe",s.ROLEUPDATE="roleupdate",s))(He||{});class vc{constructor(a,e){g(this,"authInfo");g(this,"userName");g(this,"seqIndex",0);this.authInfo=a,this.userName=e}get roleAuth(){if(this.authInfo.role){const{timestamp:a,nonce:e,token:t,role:i}=this.authInfo;return{timestamp:a,nonce:e,token:t,tokenrole:i}}}get adaptInfo(){var e,t,i,r;let a=new bc.UAParser().getResult();return{os_name:((e=a.os.name)==null?void 0:e.replace(" ",""))+"_"+((t=a.browser.name)==null?void 0:t.replace(" ","")),device_name:((i=a.device.model)==null?void 0:i.replace(" ",""))||"",brand_name:((r=a.device.vendor)==null?void 0:r.replace(" ",""))||"",device_key:window.navigator.userAgent,os_version:a.browser.version||"",sdk_version:"7.1.9",version:"v1"}}refreshAuthInfo(a){this.authInfo=a}getSeqIndex(){return this.seqIndex}createKeepAlivePackage(){return this.createBaseSendPackage("keepalive")}createJoinPackage(a){let e=this.createBaseSendPackage("joinchannel");return e.header.displayName=this.userName,e.header.clientversion=nt.getVersionNumber().toString(),e.header.platform="web",this.roleAuth&&(e.data.auth=this.roleAuth),this.adaptInfo&&(e.data.adapt=this.adaptInfo),a&&(e.data=G(G({},e.data),a)),e}crateLeavePackage(){return this.createBaseSendPackage("leavechannel")}createStatusPackage(a){let e=this.createBaseSendPackage("statusreport");return e.header.displayName=this.userName,e.data.status=a,e}createPublishPackage(){let a=this.createBaseSendPackage("publish");return a.data.users=[{}],this.roleAuth&&(a.data.auth=this.roleAuth),a}createRoleUpdatePackage(){let a=this.createBaseSendPackage("roleupdate");return a.header.displayName=this.userName,a}createReconnectPackage(a){let e=this.createBaseSendPackage("reconnect");return e.header.displayName=this.userName,e.header.clientversion=nt.getVersionNumber().toString(),e.header.platform="web",e.data=G(G({},e.data),a!=null?a:{}),this.roleAuth&&(e.data.auth=this.roleAuth),e}createRefreshUrlPackage(){let a=this.createBaseSendPackage("refreshurl");return a.header.displayName=this.userName,a}createResponsePackage(a,e){return{version:1,code:200,tid:a,msgtype:e}}createBaseSendPackage(a){var e;return++this.seqIndex,{version:1,msgtype:a,tid:dt(),header:{appid:this.authInfo.appId,channelid:this.authInfo.channelId,sessionid:(e=this.authInfo.sessionId)!=null?e:"",userid:this.authInfo.userId},data:{seq:this.seqIndex}}}}const ct=class ct extends se{constructor(e,t,i,r,n,c){super();g(this,"authInfo");g(this,"userName");g(this,"channelProfile");g(this,"clientRole");g(this,"slsReporter");g(this,"wsClient");g(this,"packageCreater");g(this,"keepAliveTimer",0);g(this,"packageCache",new Map);g(this,"isFirstConnect",!0);g(this,"aliveChecker",0);g(this,"reconnectData");g(this,"joinChannelExtraData");this.authInfo=e,this.userName=t,this.packageCreater=new vc(e,t),this.channelProfile=i,this.clientRole=r,this.slsReporter=n,this.wsClient=new jr(c),this.wsClient.on("onOpen",this.onOpen.bind(this)),this.wsClient.on("onMessage",this.onMessage.bind(this)),this.wsClient.on("onError",this.onError.bind(this)),this.wsClient.on("onClose",this.onClose.bind(this)),this.wsClient.on("onConnectFail",this.onConnectFail.bind(this)),this.wsClient.on("onAuthInvalid",this.onAuthInvalid.bind(this)),this.wsClient.on("onNetworkError",this.onNetworkError.bind(this)),this.wsClient.on("onReconnectStart",this.onReconnectStart.bind(this)),this.wsClient.on("onReconnectFail",this.onReconnectFail.bind(this))}get retryCount(){return this.wsClient.connectRetryCount}start(e,t){this.joinChannelExtraData=t,this.wsClient.start(e)}startKeepAlive(){this.keepAliveTimer===0&&(this.keepAliveTimer=window.setInterval(()=>{let e=this.packageCreater.createKeepAlivePackage();this.sendPackage(e)},5e3)),this.checkAlive()}stopKeepAlive(){this.keepAliveTimer!==0&&(clearInterval(this.keepAliveTimer),this.keepAliveTimer=0),this.aliveChecker&&(window.clearTimeout(this.aliveChecker),this.aliveChecker=0)}sendPkgCache(){this.packageCache.forEach(e=>{this.wsClient.send(e)})}leave(){let e=this.packageCreater.crateLeavePackage();this.sendPackage(e)}reportStatus(e){let t=this.packageCreater.createStatusPackage(e);this.sendPackage(t)}publish(e){const d=e,{l1ip:t}=d,i=jt(d,["l1ip"]);let r=this.packageCreater.createPublishPackage();r.data.users=[],r.data.l1ip=t,i.subscribe.signal=this.wsClient.connectUrl;const{tracks:n,resume:c}=i;let o="7.1.9";o&&(o=o.split("-")[0]),n.forEach(h=>{const{codec:l,ssrc:p}=h;h.userdata=JSON.stringify({sdk_version:o,codec:l}),h.ssrc=`${p}`,c&&(h.attr={reason:"reconnect"})}),r.data.users.push(i),this.sendPackage(r)}roleUpdate(e){let t=this.packageCreater.createRoleUpdatePackage();t.data.clientrole=e,this.sendPackage(t)}refreshUrl(e){const t=this.packageCreater.createRefreshUrlPackage();t.data=G(vt(G({},t.data),{sessionid:t.header.sessionid}),e),this.sendPackage(t)}refreshAuthInfo(e){this.authInfo=e,this.packageCreater.refreshAuthInfo(e)}close(){V.info(`[${ct.logName}] close`),this.stopKeepAlive(),this.wsClient.off("onOpen",this.onOpen.bind(this)),this.wsClient.off("onMessage",this.onMessage.bind(this)),this.wsClient.off("onError",this.onError.bind(this)),this.wsClient.off("onClose",this.onClose.bind(this)),this.wsClient.off("onConnectFail",this.onConnectFail.bind(this)),this.wsClient.off("onAuthInvalid",this.onAuthInvalid.bind(this)),this.wsClient.off("onReconnectStart"),this.wsClient.off("onReconnectFail"),this.wsClient.close()}sendPackage(e){[He.KEEPALIVE,He.RECONNECT,He.JOINCHANNEL].includes(e.msgtype)||this.packageCache.set(e.tid,e),this.wsClient.send(e),e.msgtype!==He.KEEPALIVE&&this.slsReporter.reportRoomServerEvent(!0,e.msgtype,e.tid,e)}updateReconnectData(e){this.reconnectData=e}onOpen(){if(V.info(`[${ct.logName}] onOpen`),this.isFirstConnect){let e=this.packageCreater.createJoinPackage(this.joinChannelExtraData);e.data.configure={channelprofile:this.channelProfile},this.channelProfile!==Pt.AliRtcSdkInteractiveLive&&this.channelProfile!==Pt.AliRtcSdkInteractiveWithLowLatencyLive||(e.data.configure.clientrole=this.clientRole),this.sendPackage(e)}else{this.stopKeepAlive();const e=this.packageCreater.createReconnectPackage(this.reconnectData);this.sendPackage(e)}}onMessage(e){try{let t=JSON.parse(e.data);this.packageCache.delete(t.tid),this.onRecvMessage(t),t!=null&&t.msgtype&&(t==null?void 0:t.msgtype)!==He.KEEPALIVE&&this.slsReporter.reportRoomServerEvent(!1,t.msgtype,t.tid,t)}catch(t){V.warn(`[${ct.logName}] onMessage err`,t,e)}}onError(e){V.warn(`[${ct.logName}] onError`,e),this.isFirstConnect&&this.onConnectFail()}onConnectFail(){V.warn(`[${ct.logName}] onConnectFail`);const e=new O(U.ERR_INNER,"Signaling connect failed.");this.isFirstConnect?this.emit("onJoinChannelResult",e):this.emit("onConnectFail",e)}onAuthInvalid(){V.warn(`[${ct.logName}] onAuthInvalid`),this.isFirstConnect&&this.emit("onAuthInvalid")}onNetworkError(){V.warn(`[${ct.logName}] onNetworkError`);const e=new O(U.ERR_INNER,"Network error, signaling connect failed.");this.emit("onNetworkError",e)}onClose(e){V.info(`[${ct.logName}] onClose`,e),this.stopKeepAlive()}onKeepAliveRsp(){this.emit("onKeepAliveRsp"),this.checkAlive()}onReconnectStart(){this.emit("onReconnectStart")}onReconnectFail(){this.emit("onReconnectFail",new O(U.ERR_INNER,"signaling reconnect failed."))}checkAlive(){window.clearTimeout(this.aliveChecker),this.aliveChecker=window.setTimeout(()=>{V.info(`[${ct.logName}] not alive, reconnect`),this.stopKeepAlive(),this.emit("onReconnectStart"),this.wsClient.reconnect()},3e4)}onRecvMessage(e){switch(e.msgtype!==He.KEEPALIVE&&V.info(`[${ct.logName}] recv msg: ${e.msgtype}`),e.msgtype){case He.JOINCHANNEL:this.onJoinResult(e);break;case He.KEEPALIVE:this.onKeepAliveRsp();break;case He.PUBLISH:this.onPublishResult(e);break;case He.NOTIFYJOIN:this.onNotifyJoin(e);break;case He.NOTIFYSTATUS:this.onNotifyStatus(e);break;case He.LEAVECHANNEL:this.onLeaveResult(e);break;case He.NOTIFYLEAVE:this.onNotifyLeave(e);break;case He.NOTIFYPUBLISH:this.onNotifyPublish(e);break;case He.STATUSREPORT:this.onStatusReport(e);break;case He.BYE:this.onBye(e);break;case He.ROLEUPDATE:this.onRoleUpdateResult(e);break;case He.REFRESHURL:this.onRefreshUrlResult(e);break;case He.RECONNECT:this.onReconnectResult(e);break;default:this.onUnknownMessage(e)}}onJoinResult(e){this.isFirstConnect=!1,this.emit("onJoinChannelResult",e)}onLeaveResult(e){this.emit("onLeaveResult",e.code,e.tid)}onPublishResult(e){this.emit("onPublishResult",e.code,e.tid,e.description)}onRoleUpdateResult(e){this.emit("onRoleUpdateResult",e.code,e.tid,e.description)}onRefreshUrlResult(e){this.emit("onRefreshUrlResult",e)}onReconnectResult(e){if(e.code===200)this.sendPkgCache(),this.startKeepAlive(),this.emit("onReconnectSuccess",e.data.users);else{const t=new O(U.ERR_INNER,`reconnect failed, code: ${e.code};description: ${e.description}`);e.code===403&&(t.code=403),this.emit("onReconnectFail",t),this.close()}}onNotifyJoin(e){let t=this.packageCreater.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e&&e.data&&e.data.users&&this.emit("onNotifyJoin",e.data.users)}onNotifyStatus(e){let t=this.packageCreater.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.status&&e.data.status.length&&this.emit("onNotifyStatus",e.data.status)}onNotifyLeave(e){let t=this.packageCreater.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.users&&e.data.users.length&&this.emit("onNotifyLeave",e.data.users)}onNotifyPublish(e){let t=this.packageCreater.createResponsePackage(e.tid,e.msgtype);this.wsClient.send(t),e.data&&e.data.users&&e.data.users.length&&this.emit("onNotifyPublish",e.data.users)}onStatusReport(e){this.emit("onStatusReport",e.code,e.tid,e.description)}onBye(e){this.stopKeepAlive(),this.emit("onBye",e.reason,e.description)}onUnknownMessage(e){this.emit("onUnknownMessage",e)}};g(ct,"logName","RSMessageCenter");let Wr=ct;var yc=Object.defineProperty,Ac=Object.getOwnPropertyDescriptor,$r=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?Ac(a,e):a,n=s.length-1;n>=0;n--)(i=s[n])&&(r=(t?i(a,e,r):i(r))||r);return t&&r&&yc(a,e,r),r};const Ji=(Ze=class extends se{constructor(e,t,i,r=kt.prod){super();g(this,"messageCenter");g(this,"authInfo");g(this,"userName");g(this,"channelProfile");g(this,"clientRole");g(this,"slsReporter");g(this,"reconnectData");g(this,"roomServerUri","");this.channelProfile=e,this.clientRole=t,this.slsReporter=i,this.reconnectData={role:{channelprofile:e,clientrole:t}};const n=r===kt.pre?Mi.pre:Mi.prod;this.roomServerUri=`wss://${n}/roomserver/v1/ws`}updateReconnectData(e){var t;this.reconnectData=e,(t=this.messageCenter)==null||t.updateReconnectData(this.reconnectData)}reset(){V.info("[roomsig] reset"),this.messageCenter&&(this.messageCenter.close(),this.messageCenter=void 0),this.authInfo=void 0}join(e,t,i,r){return I(this,null,function*(){return new Promise((n,c)=>{const o={};this.authInfo=e,this.userName=t,this.messageCenter=new Wr(e,t,this.channelProfile,this.clientRole,this.slsReporter,i),this.initMessageCenter(),this.messageCenter.once("onJoinChannelResult",h=>{var l,p,u;if(V.info(`[${Ze.logName}]`,"join result: ",h),o.taskretrynum=((l=this.messageCenter)==null?void 0:l.retryCount)||0,h.code==200){(p=this.messageCenter)==null||p.sendPkgCache(),(u=this.messageCenter)==null||u.startKeepAlive();let f=h.data;f.tid=h.tid,f.users=h.data.users,f.timestamp=h.timestamp,o.est&&(o.joinconnecttc=Date.now()-o.est),this.slsReporter.reportJoinConnection(o),n(f)}else this.reset(),c(this.handleSignalError(h.code,h.reason,U.ERR_JOIN_CHANNEL_FAILED))}),this.messageCenter.once("onAuthInvalid",()=>{this.reset(),c(new O(U.ERR_JOIN_BAD_TOKEN,"join failed because authentication failed"))}),V.info(`[${Ze.logName}]`,"start ws connecting roomserver and auto join when connected");const d={appid:this.authInfo.appId,callid:this.authInfo.sessionId,channelid:this.authInfo.channelId,userid:this.authInfo.userId,nonce:this.authInfo.nonce||"",timestamp:this.authInfo.timestamp,token:this.authInfo.token,authtype:"app",tid:dt()};e.role&&(d.tokenrole=e.role),o.est=Date.now(),this.messageCenter.start(this.roomServerUri+"?"+nt.queryingParam(d),r)})})}leave(){return V.info("[roomsig] leave .."),new Promise((e,t)=>{this.messageCenter?(this.messageCenter.on("onLeaveResult",(i,r)=>{V.info(`[${Ze.logName}]`,"recv leave response "+i),i===200?(this.updateReconnectData(),this.reset(),e({tid:r})):t(this.handleSignalError(i,"leave error"))}),V.info(`[${Ze.logName}]`,"send leave request"),this.messageCenter.leave()):(V.info(`[${Ze.logName}]`,"no message center, ok to leave"),e({tid:""}))})}publish(e){return new Promise((t,i)=>{var r;this.messageCenter?(this.messageCenter.once("onPublishResult",(n,c,o)=>{V.info(`[${Ze.logName}]`,"recv pubish response "+n),n===200?(this.updateReconnectData(vt(G({},this.reconnectData),{publish:{users:[e]}})),t({tid:c})):i(this.handleSignalError(n,`publish error, ${o}`))}),this.authInfo&&(e.sessionid=(r=this.authInfo.sessionId)!=null?r:""),e.callid||(e.callid=dt()),V.info(`[${Ze.logName}]`,"assign callid "+e.callid+" and send publish request"),this.messageCenter.publish(e)):i(this.handleSignalError(-1,"publish error, no message center"))})}roleUpdate(e){return new Promise((t,i)=>{this.messageCenter?(this.messageCenter.on("onRoleUpdateResult",(r,n,c)=>{var o,d;V.info(`[${Ze.logName}]`,"recv role update response "+r),r===200?((d=(o=this.reconnectData)==null?void 0:o.role)!=null&&d.clientrole&&(this.reconnectData.role.clientrole=e,this.updateReconnectData(this.reconnectData)),t({tid:n})):i(this.handleSignalError(r,`role update error, ${c}`))}),this.messageCenter.roleUpdate(e)):i(this.handleSignalError(-1,"role update error, no message center"))})}setChannelProfile(e){this.channelProfile=e}refreshUrl(e){return V.info(`[${Ze.logName}]`,"refreshUrl .."),new Promise((t,i)=>{this.messageCenter?(this.messageCenter.on("onRefreshUrlResult",r=>{const{code:n,description:c,data:o={}}=r||{};V.info("recv refresh url response "+n),n===200?t(o):i(this.handleSignalError(n,`refresh url error, ${c}`))}),V.info("send refresh url request"),this.messageCenter.refreshUrl(e)):i(this.handleSignalError(-1,"refresh url error, no message center"))})}reportStatus(e){return V.info(`[${Ze.logName}]`,"reportStatus "+e),new Promise((t,i)=>{this.messageCenter?(this.messageCenter.once("onStatusReport",(r,n)=>{r===200?t():i(new O(r,n))}),this.messageCenter.reportStatus(e)):i(new O(-1,"No messageCenter"))})}handleSignalError(e,t,i=U.ERR_INNER){return new O(i,`signal error: code - ${e}; description - ${t}`)}refreshAuthInfo(e){return I(this,null,function*(){var t;this.authInfo&&(this.authInfo=e,(t=this.messageCenter)==null||t.refreshAuthInfo(this.authInfo))})}initMessageCenter(){var e,t,i,r,n,c,o,d,h,l,p,u,f;(e=this.messageCenter)==null||e.on("onKeepAliveRsp",()=>{this.emit("onKeepAliveRsp")}),(t=this.messageCenter)==null||t.on("onNotifyJoin",m=>{this.emit("onNotifyJoin",m)}),(i=this.messageCenter)==null||i.on("onNotifyStatus",m=>{this.emit("onNotifyStatus",m)}),(r=this.messageCenter)==null||r.on("onNotifyLeave",m=>{this.emit("onNotifyLeave",m)}),(n=this.messageCenter)==null||n.on("onNotifyPublish",m=>{this.emit("onNotifyPublish",m)}),(c=this.messageCenter)==null||c.on("onBye",(m,b)=>{this.emit("onBye",m,b)}),(o=this.messageCenter)==null||o.on("onReconnectStart",()=>{this.emit("onReconnectStart")}),(d=this.messageCenter)==null||d.on("onReconnectSuccess",m=>{this.emit("onReconnectSuccess",m)}),(h=this.messageCenter)==null||h.on("onReconnectFail",m=>{this.emit("onReconnectFail",m)}),(l=this.messageCenter)==null||l.on("onConnectFail",m=>{this.emit("onConnectFail",m),this.reset()}),(p=this.messageCenter)==null||p.on("onNetworkError",m=>{this.emit("onNetworkError",m)}),(u=this.messageCenter)==null||u.on("onAuthInvalid",()=>{this.emit("onAuthInvalid")}),(f=this.messageCenter)==null||f.on("onUnknownMessage",m=>{this.emit("onUnknownMessage",m)})}},g(Ze,"logName","RoomServerSignaling"),Ze);$r([C()],Ji.prototype,"join",1),$r([C()],Ji.prototype,"publish",1),$r([C()],Ji.prototype,"roleUpdate",1);let Rc=Ji;const _c=6e5,wi=class wi extends se{constructor(e,t){super();g(this,"env");g(this,"authInfo");g(this,"timer");g(this,"slsReporter");g(this,"expiration",0);g(this,"skipTime",0);g(this,"requestToken",()=>I(this,null,function*(){if(this.skipTime=0,!this.authInfo)return;const{appId:e,channelId:t,userId:i,nonce:r="",token:n,timestamp:c,sessionId:o,role:d}=this.authInfo;let h="https://gw.rtn.aliyuncs.com";this.env===kt.pre&&(h="https://pgw.rtn.aliyuncs.com");const l=`${h}/gslb/v1/stsupdate?appid=${e}&channelid=${t}&userid=${i}&nonce=${r}&token=${n}&timestamp=${c}&session=${o}${d?`&tokenrole=${d}`:""}&slstoken=true&osstoken=true&tokensid=false`,p=Date.now();fetch(l).then(u=>u.json()).then(u=>{var f,m;if(u.code!==0)throw new Error;{const b=(f=u.data)==null?void 0:f.oss,S=(m=u.data)==null?void 0:m.sls;this.expiration=b.expiration||S.expiration,this.emit("onTokenUpdate",b,S),V.event(`[${wi.logName}]`,"getToken",b,S)}this.slsReporter.reportSTSResult(200,p)}).catch(u=>{this.slsReporter.reportSTSResult(-1,p),V.error(`[${wi.logName}]`,"getToken",u.message)})}));this.slsReporter=e,this.env=t}refreshAuthInfo(e){this.authInfo=e}startSTSUpdate(e){this.authInfo=e,this.requestToken(),this.timer&&clearInterval(this.timer),this.timer=window.setInterval(()=>{this.expiration&&Math.floor((Date.now()+9e5)/1e3)<this.expiration&&this.skipTime<12?this.skipTime+=1:this.requestToken()},_c)}clear(){this.timer&&clearInterval(this.timer)}};g(wi,"logName","StsManager");let Kr=wi;var wc=Object.defineProperty,Ec=Object.getOwnPropertyDescriptor;class Jr extends se{constructor(e,t,i,r=kt.prod){super();g(this,"signaling");g(this,"authInfo");g(this,"userName");g(this,"channelProfile");g(this,"clientRole");g(this,"env",kt.prod);g(this,"maxConnectRetryCount");g(this,"stsManager");g(this,"slsReporter");this.channelProfile=e,this.clientRole=t,this.env=r,this.slsReporter=i,this.stsManager=new Kr(i,r)}reset(){var e;V.info("[signalingmanager] reset"),(e=this.signaling)==null||e.reset(),this.stsManager.clear(),this.signaling=void 0,this.authInfo=void 0}join(e,t=e.userId,i,r,n){return this.maxConnectRetryCount=i,this.userName=t,new Promise((c,o)=>{this.signaling?o(new O(U.ERR_JOIN_ALREADY_JOINED,"already joined")):(V.info("[signalingmanager] create signaling"),this.signaling=new Rc(this.channelProfile,this.clientRole,this.slsReporter,this.env),this.initSignaling(),r&&(r.rs=Date.now()),this.signaling.join(e,t,i,n).then(d=>{this.authInfo=e,r&&(r.re=Date.now()),c(d)}).catch(d=>{this.reset(),o(d)}),this.stsManager.startSTSUpdate(e))})}retryJoin(){const e=this.authInfo;this.reset(),e&&this.join(e,this.userName,this.maxConnectRetryCount)}leave(){return new Promise((e,t)=>{this.signaling?this.signaling.leave().then(i=>{this.reset(),e(i)}).catch(i=>{t(i)}):e({tid:""})})}publish(e){return new Promise((t,i)=>{var r;this.signaling&&this.authInfo?(e.userid=this.authInfo.userId,e.displayname=(r=this.userName)!=null?r:this.authInfo.userId,this.signaling.publish(e).then(n=>{t(n)}).catch(n=>{i(n)})):i(new O(U.ERR_SDK_PUBLISH_NOT_JOIN_CHANNEL,"no signaling"))})}reportStatus(e){return new Promise((t,i)=>{this.signaling?this.signaling.reportStatus(e).then(()=>{t()}).catch(r=>{i(r)}):i(new O(-1,"no signaling"))})}setClientRole(e){return I(this,null,function*(){const t=this.clientRole;if(!this.signaling)return void(this.clientRole=e);const i=Date.now();try{const r=yield this.signaling.roleUpdate(e);return this.slsReporter.reportRoleUpdateResult(t,e,Date.now()-i,0),r}catch(r){this.slsReporter.reportRoleUpdateResult(t,e,Date.now()-i,r.code||-1)}})}setChannelProfile(e){this.signaling?this.signaling.setChannelProfile(e):this.channelProfile=e}refreshUrl(e){return this.signaling?this.signaling.refreshUrl(e):Promise.reject(new O(U.ERR_SDK_INVALID_STATE,"should join first"))}refreshAuthInfo(e){return I(this,null,function*(){var t;try{this.authInfo&&(this.authInfo=G(G({},this.authInfo),e),(t=this.signaling)==null||t.refreshAuthInfo(this.authInfo),this.stsManager.refreshAuthInfo(this.authInfo))}catch(i){throw i}})}initSignaling(){var e,t,i,r,n,c,o,d,h,l,p,u,f,m;(e=this.signaling)==null||e.on("onKeepAliveRsp",this.onKeepAliveRsp.bind(this)),(t=this.signaling)==null||t.on("onNotifyJoin",this.onNotifyJoin.bind(this)),(i=this.signaling)==null||i.on("onNotifyStatus",this.onNotifyStatus.bind(this)),(r=this.signaling)==null||r.on("onNotifyLeave",this.onNotifyLeave.bind(this)),(n=this.signaling)==null||n.on("onNotifyPublish",this.onNotifyPublish.bind(this)),(c=this.signaling)==null||c.on("onBye",this.onBye.bind(this)),(o=this.signaling)==null||o.on("onReconnectStart",this.onReconnectStart.bind(this)),(d=this.signaling)==null||d.on("onReconnectSuccess",this.onReconnectSuccess.bind(this)),(h=this.signaling)==null||h.on("onReconnectFail",this.onReconnectFail.bind(this)),(l=this.signaling)==null||l.on("onConnectFail",this.onConnectFail.bind(this)),(p=this.signaling)==null||p.on("onNetworkError",this.onNetworkError.bind(this)),(u=this.signaling)==null||u.on("onAuthInvalid",this.onAuthInvalid.bind(this)),(f=this.signaling)==null||f.on("onError",this.onError.bind(this)),(m=this.signaling)==null||m.on("onUnknownMessage",this.onUnknownMessage.bind(this))}onKeepAliveRsp(){this.emit("onKeepAliveRsp")}onNotifyJoin(e){this.emit("onNotifyJoin",e)}onNotifyStatus(e){this.emit("onNotifyStatus",e)}onNotifyLeave(e){this.emit("onNotifyLeave",e)}onNotifyPublish(e){this.emit("onNotifyPublish",e)}onBye(e,t){this.emit("onBye",e,t)}onConnectFail(e){this.reset(),this.emit("onConnectFail",e)}onNetworkError(e){this.emit("onNetworkError",e)}onAuthInvalid(){}onReconnectStart(){this.emit("onReconnectStart")}onReconnectSuccess(e){this.emit("onReconnectSuccess",e)}onReconnectFail(e){this.emit("onReconnectFail",e)}onError(e){this.emit("onError",e)}onUnknownMessage(e){this.emit("onUnknownMessage",e)}}g(Jr,"logName","SignalingManager"),((s,a,e,t)=>{for(var i,r=t>1?void 0:t?Ec(a,e):a,n=s.length-1;n>=0;n--)(i=s[n])&&(r=(t?i(a,e,r):i(r))||r);t&&r&&wc(a,e,r)})([C(H)],Jr.prototype,"publish",1);class ln{constructor(a){g(this,"taskProfile");g(this,"encodeParam");g(this,"users",[]);g(this,"backgroundColor",0);g(this,"backgrounds",[]);g(this,"watermarks",[]);g(this,"clockWidgets",[]);g(this,"cropMode");g(this,"mediaProcessMode");this.taskProfile=a}}class un{constructor(a,e,t){g(this,"userId");g(this,"streamType");g(this,"sourceType");this.userId=a,this.streamType=e,this.sourceType=t}}class pn{constructor(a,e,t,i=0,r=16777215,n=Ri.NOTO_SERIF_CJKSC_REGULAR){g(this,"x");g(this,"y");g(this,"fontSize");g(this,"zOrder");g(this,"fontColor");g(this,"fontType");this.x=a,this.y=e,this.fontSize=t,this.zOrder=i,this.fontColor=r,this.fontType=n}toJson(a,e){return{x:pt(this.x,a),y:pt(this.y,e),fonttype:this.fontType,fontsize:this.fontSize,fontcolor:Or(this.fontColor),zorder:this.zOrder}}}var mn=(s=>(s[s.NOT_DISPLAY=0]="NOT_DISPLAY",s[s.ALWAYS=1]="ALWAYS",s[s.WHEN_NO_VIDEO=2]="WHEN_NO_VIDEO",s))(mn||{});class Gr{constructor(a,e,t,i,r,n=0,c=1,o=1){g(this,"url");g(this,"x");g(this,"y");g(this,"width");g(this,"height");g(this,"alpha");g(this,"display",1);g(this,"zOrder");this.url=a,this.x=e,this.y=t,this.width=i,this.height=r,this.zOrder=n,this.alpha=c,this.display=o}toJson(a,e){return{url:this.url,alpha:this.alpha,display:this.display,x:pt(this.x,a),y:pt(this.y,e),width:pt(this.width,a),height:pt(this.height,e),zorder:this.zOrder}}}g(Gr,"DisplayType",mn);class gn{constructor(a,e,t,i,r=0,n=16777215,c=Ri.NOTO_SERIF_CJKSC_REGULAR){g(this,"text");g(this,"x");g(this,"y");g(this,"fontSize");g(this,"zOrder");g(this,"fontColor");g(this,"fontType");this.text=a,this.x=e,this.y=t,this.fontSize=i,this.zOrder=r,this.fontColor=n,this.fontType=c}toJson(a,e){return{text:this.text,x:pt(this.x,a),y:pt(this.y,e),fonttype:this.fontType,fontsize:this.fontSize,fontcolor:Or(this.fontColor),zorder:this.zOrder}}}class fn{constructor(a,e,t,i,r,n=0,c){g(this,"userId");g(this,"x");g(this,"y");g(this,"width");g(this,"height");g(this,"zOrder");g(this,"sourceType");g(this,"segmentType",Ai.LiveTranscodingNoBody);g(this,"images",[]);g(this,"texts",[]);this.userId=typeof a=="number"?a.toString():a,this.x=e,this.y=t,this.width=i,this.height=r,this.zOrder=n,c&&(this.sourceType=c)}toJson(a,e,t,i){const r={paneid:a,majorpane:0,x:pt(this.x,e),y:pt(this.y,t),width:pt(this.width,e),height:pt(this.height,t),zorder:this.zOrder,userid:this.userId,images:this.images.map(n=>n.toJson(e,t)),texts:this.texts.map(n=>n.toJson(e,t))};return this.sourceType&&yi[this.sourceType]?r.sourcetype=yi[this.sourceType]:r.sourcetype=yi[ci.LiveTranscodingCamera],this.segmentType&&i===$i.LiveTranscodingVirtualBackground?r.segmenttype=this.segmentType:r.segmenttype=Ai.LiveTranscodingNoBody,r}}class Tc{constructor(a){g(this,"_updateables");g(this,"_useWebworker");g(this,"_inited");g(this,"_active");g(this,"_previousRAFTime");g(this,"_previousWorkerTime");g(this,"_webWorkerString");g(this,"_webWorker");g(this,"_intervalThreshold");g(this,"_rafId");this._updateables=[],this._useWebworker=!1,this._inited=!1,this._active=!1,this._previousRAFTime=void 0,this._previousWorkerTime=void 0,this._intervalThreshold=a&&a>0&&a<=60?1/a:.1,this._webWorkerString=`
133
133
  var running = false;
134
134
  function tick(){
135
135
  postMessage(Date.now());