aliyun-rtc-sdk 7.2.0 → 7.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -4,9 +4,9 @@
|
|
|
4
4
|
`+((A=R.get("Content-Type"))!=null?A:"")+`
|
|
5
5
|
`+y+`
|
|
6
6
|
`;const E=(P,H)=>P[0].localeCompare(H[0]),T=P=>P[0].startsWith("x-log-")||P[0].startsWith("x-acs-");try{const P=[...R.entries()].filter(T).sort(E).map(H=>H[0]+":"+H[1]+`
|
|
7
|
-
`).join("");_+=P}catch(P){}_+=m,v.size>0&&(_+="?");try{_+=[...v.entries()].sort(E).map(P=>P[0]+"="+P[1]).join("&")}catch(P){}const k="LOG "+b+":"+gi.HmacSHA1(_,S).toString(gi.enc.Base64);R.set("Authorization",k),R.set("x-log-date",y)}("POST",n,s.accessKeyId,s.accessKeySecret,h,p,o,d);let u=Object.fromEntries(p);return{data:e,header:u}},new Promise((n,c)=>{var o=h=>{try{d(r.next(h))}catch(p){c(p)}},l=h=>{try{d(r.throw(h))}catch(p){c(p)}},d=h=>h.done?n(h.value):Promise.resolve(h.value).then(o,l);d((r=r.apply(t,i)).next())});var t,i,r}}}typeof window!="undefined"&&Mi(window,"stsPlugin",Zi);for(var er,Je=[],tr=0;tr<256;++tr)Je.push((tr+256).toString(16).slice(1));var ho=new Uint8Array(16);function uo(){if(!er&&!(er=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return er(ho)}const ra={randomUUID:typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function lt(s,a,e){if(ra.randomUUID&&!a&&!s)return ra.randomUUID();var t=(s=s||{}).random||(s.rng||uo)();if(t[6]=15&t[6]|64,t[8]=63&t[8]|128,a){e=e||0;for(var i=0;i<16;++i)a[e+i]=t[i];return a}return function(r,n=0){return(Je[r[n+0]]+Je[r[n+1]]+Je[r[n+2]]+Je[r[n+3]]+"-"+Je[r[n+4]]+Je[r[n+5]]+"-"+Je[r[n+6]]+Je[r[n+7]]+"-"+Je[r[n+8]]+Je[r[n+9]]+"-"+Je[r[n+10]]+Je[r[n+11]]+Je[r[n+12]]+Je[r[n+13]]+Je[r[n+14]]+Je[r[n+15]]).toLowerCase()}(t)}var po=/d{1,4}|D{3,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|W{1,2}|[LlopSZN]|"[^"]*"|'[^']*'/g,go=/\b(?:[A-Z]{1,3}[A-Z][TC])(?:[-+]\d{4})?|((?:Australian )?(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time)\b/g,mo=/[^-+\dA-Z]/g;function ir(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(sa[a]||a||sa.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"]()},l=function(){return s[r()+"FullYear"]()},d=function(){return s[r()+"Hours"]()},h=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 fo(s)},b={d:function(){return n()},dd:function(){return nt(n())},ddd:function(){return tt.dayNames[c()]},DDD:function(){return aa({y:l(),m:o(),d:n(),_:r(),dayName:tt.dayNames[c()],short:!0})},dddd:function(){return tt.dayNames[c()+7]},DDDD:function(){return aa({y:l(),m:o(),d:n(),_:r(),dayName:tt.dayNames[c()+7]})},m:function(){return o()+1},mm:function(){return nt(o()+1)},mmm:function(){return tt.monthNames[o()]},mmmm:function(){return tt.monthNames[o()+12]},yy:function(){return String(l()).slice(2)},yyyy:function(){return nt(l(),4)},h:function(){return d()%12||12},hh:function(){return nt(d()%12||12)},H:function(){return d()},HH:function(){return nt(d())},M:function(){return h()},MM:function(){return nt(h())},s:function(){return p()},ss:function(){return nt(p())},l:function(){return nt(u(),3)},L:function(){return nt(Math.floor(u()/10))},t:function(){return d()<12?tt.timeNames[0]:tt.timeNames[1]},tt:function(){return d()<12?tt.timeNames[2]:tt.timeNames[3]},T:function(){return d()<12?tt.timeNames[4]:tt.timeNames[5]},TT:function(){return d()<12?tt.timeNames[6]:tt.timeNames[7]},Z:function(){return t?"GMT":e?"UTC":bo(s)},o:function(){return(f()>0?"-":"+")+nt(100*Math.floor(Math.abs(f())/60)+Math.abs(f())%60,4)},p:function(){return(f()>0?"-":"+")+nt(Math.floor(Math.abs(f())/60),2)+":"+nt(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 nt(m())},N:function(){return So(s)}};return a.replace(po,function(S){return S in b?b[S]():S.slice(1,S.length-1)})}var sa={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"},tt={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"]},nt=function(s){var a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:2;return String(s).padStart(a,"0")},aa=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,l=new Date;l.setDate(l[i+"Date"]()-1);var d=new Date;return d.setDate(d[i+"Date"]()+1),o[i+"FullYear"]()===a&&o[i+"Month"]()===e&&o[i+"Date"]()===t?c?"Tdy":"Today":l[i+"FullYear"]()===a&&l[i+"Month"]()===e&&l[i+"Date"]()===t?c?"Ysd":"Yesterday":d[i+"FullYear"]()===a&&d[i+"Month"]()===e&&d[i+"Date"]()===t?c?"Tmw":"Tomorrow":r},fo=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)},So=function(s){var a=s.getDay();return a===0&&(a=7),a},bo=function(s){return(String(s).match(go)||[""]).pop().replace(mo,"").replace(/GMT\+0000/g,"UTC")},ri=(s=>(s.prod="rs.rtn.aliyuncs.com",s.pre="prs.rtn.aliyuncs.com",s))(ri||{});const Ni="7.2.0";class Ne{static getVersionNumber(){let a=Ni.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=lt();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=ri.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+=Ne.toString(a[t]);return e}static removeQueryString(a){if(!a)return a;let e=a.indexOf("?");return e>0?a.substring(0,e):a}}const{BrowserUtil:vo}=X.AliRTS,yo="EdgeHTML",na="Blink",Ro="Trident",Ao="Gecko",_o="WebKit",xi=(s,a)=>{const e=a.match(s);return e&&e.length>0&&e[1]||""},wo=[{test:[/\sedg\//i,[/edg([ea]|ios)/i]],describe(s){if(/\sedg\//i.test(s))return{name:na};const a=xi(/edge\/(\d+(\.?_?\d+)+)/i,s);return{name:yo,version:a}}},{test:[/trident/i],describe(s){const a={name:Ro},e=xi(/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:Ao},e=xi(/gecko\/(\d+(\.?_?\d+)+)/i,s);return e&&(a.version=e),a}},{test:[/(apple)?webkit\/537\.36/i],describe:()=>({name:na})},{test:[/(apple)?webkit/i],describe(s){const a={name:_o},e=xi(/webkit\/(\d+(\.?_?\d+)+)/i,s);return e&&(a.version=e),a}}],rr=(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),Eo=()=>{try{const s=navigator.userAgent||"",a=rr(wo,s);if(a){const e=a.describe(s);return`${e.name}/${e.version||vo.browserVersion}`}}catch(s){}return navigator.userAgent},Io=[{test:["wow64","win64","x64"],describe:()=>"amd64"},{test:["i686","x86"],describe:()=>"x86"},{test:["aarch64","arm64"],describe:()=>"arm64"},{test:["arm"],describe:()=>"arm"}],oa=()=>{let s="unknown";try{const a=navigator.userAgent||"",e=rr(Io,a);if(!e)return s;s=e.describe(a)}catch(a){}return s},To=[{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"}],Co=()=>{let s="Unknown";try{const a=navigator.userAgent||"",e=rr(To,a);if(!e)return s;s=e.describe(a)}catch(a){}return s};class ca{constructor(a){var e,t;this.timer=null,this.time=10,this.count=10,this.arr=[],this.time=(e=a.time)!=null?e:10,this.count=(t=a.count)!=null?t:10,a.host.startsWith("http://")||a.host.startsWith("https://")?this.url=a.host+"/logstores/"+a.logstore+"/track":this.url="https://"+a.project+"."+a.host+"/logstores/"+a.logstore+"/track",this.opt=a,a.installUnloadHook&&typeof a.installUnloadHook=="function"&&a.installUnloadHook(()=>{this.sendImmediateInner()})}assemblePayload(a){const e={__logs__:a};return this.opt.tags&&(e.__tags__=this.opt.tags),this.opt.topic&&(e.__topic__=this.opt.topic),this.opt.source&&(e.__source__=this.opt.source),JSON.stringify(e)}platformSend(){if(this.opt.sendPayload&&typeof this.opt.sendPayload=="function"){const a=this.assemblePayload(this.arr);this.opt.sendPayload(this.url,a)}}transString(a){let e={};for(let t in a)typeof a[t]=="object"?e[t]=JSON.stringify(a[t]):e[t]=String(a[t]);return e}sendImmediateInner(){this.arr&&this.arr.length>0&&(this.platformSend(),this.timer!=null&&(clearTimeout(this.timer),this.timer=null),this.arr=[])}sendInner(){if(this.timer)this.arr.length>=this.count&&(clearTimeout(this.timer),this.timer=null,this.sendImmediateInner());else{const a=this;this.arr.length>=this.count||this.time<=0?this.sendImmediateInner():this.timer=setTimeout(function(){a.sendImmediateInner()},1e3*this.time)}}send(a){const e=this.transString(a);this.arr.push(e),this.sendInner()}sendImmediate(a){const e=this.transString(a);this.arr.push(e),this.sendImmediateInner()}sendBatchLogs(a){const e=a.map(t=>this.transString(t));this.arr.push(...e),this.sendInner()}sendBatchLogsImmediate(a){const e=a.map(t=>this.transString(t));this.arr.push(...e),this.sendImmediateInner()}overwriteTransString(a){this.transString=a.transString}getOpt(){return this.opt}}function la(s,a){return new Promise((e,t)=>{const i=new window.XMLHttpRequest;i.onload=()=>{i.status>=200&&i.status<300?e():t(new Error(`HTTP ${i.status}: ${i.statusText}`))},i.onerror=()=>{t(new Error("Network error occurred"))},i.ontimeout=()=>{t(new Error("Request timeout"))},i.timeout=1e4,i.open("POST",`${s}?APIVersion=0.6.0`,!0),i.send(a)})}function ko(s,a,e=!1){return I(this,null,function*(){try{if(e||a.length>=32768)return void(yield la(s,a));(function(t,i){return!(!navigator||!navigator.sendBeacon)&&navigator.sendBeacon(`${t}?APIVersion=0.6.0`,i)})(s,a)||(yield la(s,a))}catch(t){const i=t instanceof Error?t:new Error(String(t));throw window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
|
|
7
|
+
`).join("");_+=P}catch(P){}_+=m,v.size>0&&(_+="?");try{_+=[...v.entries()].sort(E).map(P=>P[0]+"="+P[1]).join("&")}catch(P){}const k="LOG "+b+":"+gi.HmacSHA1(_,S).toString(gi.enc.Base64);R.set("Authorization",k),R.set("x-log-date",y)}("POST",n,s.accessKeyId,s.accessKeySecret,h,p,o,d);let u=Object.fromEntries(p);return{data:e,header:u}},new Promise((n,c)=>{var o=h=>{try{d(r.next(h))}catch(p){c(p)}},l=h=>{try{d(r.throw(h))}catch(p){c(p)}},d=h=>h.done?n(h.value):Promise.resolve(h.value).then(o,l);d((r=r.apply(t,i)).next())});var t,i,r}}}typeof window!="undefined"&&Mi(window,"stsPlugin",Zi);for(var er,Je=[],tr=0;tr<256;++tr)Je.push((tr+256).toString(16).slice(1));var ho=new Uint8Array(16);function uo(){if(!er&&!(er=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return er(ho)}const ra={randomUUID:typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function lt(s,a,e){if(ra.randomUUID&&!a&&!s)return ra.randomUUID();var t=(s=s||{}).random||(s.rng||uo)();if(t[6]=15&t[6]|64,t[8]=63&t[8]|128,a){e=e||0;for(var i=0;i<16;++i)a[e+i]=t[i];return a}return function(r,n=0){return(Je[r[n+0]]+Je[r[n+1]]+Je[r[n+2]]+Je[r[n+3]]+"-"+Je[r[n+4]]+Je[r[n+5]]+"-"+Je[r[n+6]]+Je[r[n+7]]+"-"+Je[r[n+8]]+Je[r[n+9]]+"-"+Je[r[n+10]]+Je[r[n+11]]+Je[r[n+12]]+Je[r[n+13]]+Je[r[n+14]]+Je[r[n+15]]).toLowerCase()}(t)}var po=/d{1,4}|D{3,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|W{1,2}|[LlopSZN]|"[^"]*"|'[^']*'/g,go=/\b(?:[A-Z]{1,3}[A-Z][TC])(?:[-+]\d{4})?|((?:Australian )?(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time)\b/g,mo=/[^-+\dA-Z]/g;function ir(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(sa[a]||a||sa.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"]()},l=function(){return s[r()+"FullYear"]()},d=function(){return s[r()+"Hours"]()},h=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 fo(s)},b={d:function(){return n()},dd:function(){return nt(n())},ddd:function(){return tt.dayNames[c()]},DDD:function(){return aa({y:l(),m:o(),d:n(),_:r(),dayName:tt.dayNames[c()],short:!0})},dddd:function(){return tt.dayNames[c()+7]},DDDD:function(){return aa({y:l(),m:o(),d:n(),_:r(),dayName:tt.dayNames[c()+7]})},m:function(){return o()+1},mm:function(){return nt(o()+1)},mmm:function(){return tt.monthNames[o()]},mmmm:function(){return tt.monthNames[o()+12]},yy:function(){return String(l()).slice(2)},yyyy:function(){return nt(l(),4)},h:function(){return d()%12||12},hh:function(){return nt(d()%12||12)},H:function(){return d()},HH:function(){return nt(d())},M:function(){return h()},MM:function(){return nt(h())},s:function(){return p()},ss:function(){return nt(p())},l:function(){return nt(u(),3)},L:function(){return nt(Math.floor(u()/10))},t:function(){return d()<12?tt.timeNames[0]:tt.timeNames[1]},tt:function(){return d()<12?tt.timeNames[2]:tt.timeNames[3]},T:function(){return d()<12?tt.timeNames[4]:tt.timeNames[5]},TT:function(){return d()<12?tt.timeNames[6]:tt.timeNames[7]},Z:function(){return t?"GMT":e?"UTC":bo(s)},o:function(){return(f()>0?"-":"+")+nt(100*Math.floor(Math.abs(f())/60)+Math.abs(f())%60,4)},p:function(){return(f()>0?"-":"+")+nt(Math.floor(Math.abs(f())/60),2)+":"+nt(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 nt(m())},N:function(){return So(s)}};return a.replace(po,function(S){return S in b?b[S]():S.slice(1,S.length-1)})}var sa={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"},tt={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"]},nt=function(s){var a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:2;return String(s).padStart(a,"0")},aa=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,l=new Date;l.setDate(l[i+"Date"]()-1);var d=new Date;return d.setDate(d[i+"Date"]()+1),o[i+"FullYear"]()===a&&o[i+"Month"]()===e&&o[i+"Date"]()===t?c?"Tdy":"Today":l[i+"FullYear"]()===a&&l[i+"Month"]()===e&&l[i+"Date"]()===t?c?"Ysd":"Yesterday":d[i+"FullYear"]()===a&&d[i+"Month"]()===e&&d[i+"Date"]()===t?c?"Tmw":"Tomorrow":r},fo=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)},So=function(s){var a=s.getDay();return a===0&&(a=7),a},bo=function(s){return(String(s).match(go)||[""]).pop().replace(mo,"").replace(/GMT\+0000/g,"UTC")},ri=(s=>(s.prod="rs.rtn.aliyuncs.com",s.pre="prs.rtn.aliyuncs.com",s))(ri||{});const Ni="7.2.1";class Ne{static getVersionNumber(){let a=Ni.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=lt();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=ri.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+=Ne.toString(a[t]);return e}static removeQueryString(a){if(!a)return a;let e=a.indexOf("?");return e>0?a.substring(0,e):a}}const{BrowserUtil:vo}=X.AliRTS,yo="EdgeHTML",na="Blink",Ro="Trident",Ao="Gecko",_o="WebKit",xi=(s,a)=>{const e=a.match(s);return e&&e.length>0&&e[1]||""},wo=[{test:[/\sedg\//i,[/edg([ea]|ios)/i]],describe(s){if(/\sedg\//i.test(s))return{name:na};const a=xi(/edge\/(\d+(\.?_?\d+)+)/i,s);return{name:yo,version:a}}},{test:[/trident/i],describe(s){const a={name:Ro},e=xi(/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:Ao},e=xi(/gecko\/(\d+(\.?_?\d+)+)/i,s);return e&&(a.version=e),a}},{test:[/(apple)?webkit\/537\.36/i],describe:()=>({name:na})},{test:[/(apple)?webkit/i],describe(s){const a={name:_o},e=xi(/webkit\/(\d+(\.?_?\d+)+)/i,s);return e&&(a.version=e),a}}],rr=(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),Eo=()=>{try{const s=navigator.userAgent||"",a=rr(wo,s);if(a){const e=a.describe(s);return`${e.name}/${e.version||vo.browserVersion}`}}catch(s){}return navigator.userAgent},Io=[{test:["wow64","win64","x64"],describe:()=>"amd64"},{test:["i686","x86"],describe:()=>"x86"},{test:["aarch64","arm64"],describe:()=>"arm64"},{test:["arm"],describe:()=>"arm"}],oa=()=>{let s="unknown";try{const a=navigator.userAgent||"",e=rr(Io,a);if(!e)return s;s=e.describe(a)}catch(a){}return s},To=[{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"}],Co=()=>{let s="Unknown";try{const a=navigator.userAgent||"",e=rr(To,a);if(!e)return s;s=e.describe(a)}catch(a){}return s};class ca{constructor(a){var e,t;this.timer=null,this.time=10,this.count=10,this.arr=[],this.time=(e=a.time)!=null?e:10,this.count=(t=a.count)!=null?t:10,a.host.startsWith("http://")||a.host.startsWith("https://")?this.url=a.host+"/logstores/"+a.logstore+"/track":this.url="https://"+a.project+"."+a.host+"/logstores/"+a.logstore+"/track",this.opt=a,a.installUnloadHook&&typeof a.installUnloadHook=="function"&&a.installUnloadHook(()=>{this.sendImmediateInner()})}assemblePayload(a){const e={__logs__:a};return this.opt.tags&&(e.__tags__=this.opt.tags),this.opt.topic&&(e.__topic__=this.opt.topic),this.opt.source&&(e.__source__=this.opt.source),JSON.stringify(e)}platformSend(){if(this.opt.sendPayload&&typeof this.opt.sendPayload=="function"){const a=this.assemblePayload(this.arr);this.opt.sendPayload(this.url,a)}}transString(a){let e={};for(let t in a)typeof a[t]=="object"?e[t]=JSON.stringify(a[t]):e[t]=String(a[t]);return e}sendImmediateInner(){this.arr&&this.arr.length>0&&(this.platformSend(),this.timer!=null&&(clearTimeout(this.timer),this.timer=null),this.arr=[])}sendInner(){if(this.timer)this.arr.length>=this.count&&(clearTimeout(this.timer),this.timer=null,this.sendImmediateInner());else{const a=this;this.arr.length>=this.count||this.time<=0?this.sendImmediateInner():this.timer=setTimeout(function(){a.sendImmediateInner()},1e3*this.time)}}send(a){const e=this.transString(a);this.arr.push(e),this.sendInner()}sendImmediate(a){const e=this.transString(a);this.arr.push(e),this.sendImmediateInner()}sendBatchLogs(a){const e=a.map(t=>this.transString(t));this.arr.push(...e),this.sendInner()}sendBatchLogsImmediate(a){const e=a.map(t=>this.transString(t));this.arr.push(...e),this.sendImmediateInner()}overwriteTransString(a){this.transString=a.transString}getOpt(){return this.opt}}function la(s,a){return new Promise((e,t)=>{const i=new window.XMLHttpRequest;i.onload=()=>{i.status>=200&&i.status<300?e():t(new Error(`HTTP ${i.status}: ${i.statusText}`))},i.onerror=()=>{t(new Error("Network error occurred"))},i.ontimeout=()=>{t(new Error("Request timeout"))},i.timeout=1e4,i.open("POST",`${s}?APIVersion=0.6.0`,!0),i.send(a)})}function ko(s,a,e=!1){return I(this,null,function*(){try{if(e||a.length>=32768)return void(yield la(s,a));(function(t,i){return!(!navigator||!navigator.sendBeacon)&&navigator.sendBeacon(`${t}?APIVersion=0.6.0`,i)})(s,a)||(yield la(s,a))}catch(t){const i=t instanceof Error?t:new Error(String(t));throw window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
|
|
8
8
|
`+i.message),console.error("Failed log data:",s)),i}})}let Po=class extends ca{constructor(a){const f=a,{maxRetries:e=10,retryDelay:t=2e3,backoffMultiplier:i=2,maxRetryDelay:r=3e5,enableLocalStorage:n=!0,maxStorageSize:c=1e3,storageKey:o="artc_reliable_logs",enableNetworkMonitor:l=!0,onNetworkChange:d=()=>{},forceXhrMode:h=!0,debug:p=!1}=f,u=Mt(f,["maxRetries","retryDelay","backoffMultiplier","maxRetryDelay","enableLocalStorage","maxStorageSize","storageKey","enableNetworkMonitor","onNetworkChange","forceXhrMode","debug"]);super(Object.assign({},u,{installUnloadHook:m=>{window.addEventListener("beforeunload",()=>{this.saveFailedLogs(),m()}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.saveFailedLogs()})},sendPayload:(m,b)=>I(this,null,function*(){return Promise.resolve()})}));g(this,"reliableConfig");g(this,"failedLogs",new Map);g(this,"networkStatus","online");g(this,"retryTimer",null);g(this,"originalSendPayload",null);this.reliableConfig={maxRetries:e,retryDelay:t,backoffMultiplier:i,maxRetryDelay:r,enableLocalStorage:n,maxStorageSize:c,storageKey:o,enableNetworkMonitor:l,onNetworkChange:d,forceXhrMode:h,debug:p},this.originalSendPayload=(m,b)=>I(this,null,function*(){return ko(m,b,h)}),this.getOpt().sendPayload=(m,b)=>I(this,null,function*(){return this.reliableSendAsync(m,b)}),this.initNetworkMonitor(),this.loadFailedLogs(),this.startRetryTimer()}reliableSendAsync(a,e){return I(this,null,function*(){const t=this.generateId();try{yield Promise.resolve(this.originalSendPayload(a,e)),this.debug(`Log ${t} sent successfully`)}catch(i){this.debug(`Log ${t} failed, adding to retry queue:`,i),this.addToFailedQueue(t,a,e,i)}})}addToFailedQueue(a,e,t,i){const r={id:a,data:{error:i.message},timestamp:Date.now(),retryCount:0,lastRetryTime:0,url:e,payload:t};this.failedLogs.set(a,r),this.scheduleRetry(r)}scheduleRetry(a){if(a.retryCount>=this.reliableConfig.maxRetries)return this.debug(`Log ${a.id} exceeded max retries, removing from queue`),void this.failedLogs.delete(a.id);const e=Math.min(this.reliableConfig.retryDelay*Math.pow(this.reliableConfig.backoffMultiplier,a.retryCount),this.reliableConfig.maxRetryDelay);this.debug(`Scheduling retry for log ${a.id} in ${e}ms (attempt ${a.retryCount+1}/${this.reliableConfig.maxRetries})`),setTimeout(()=>{this.retryLog(a)},e)}retryLog(a){return I(this,null,function*(){if(this.failedLogs.has(a.id)){a.retryCount++,a.lastRetryTime=Date.now();try{if(this.networkStatus==="offline")return this.debug(`Log ${a.id} retry skipped - network offline`),void this.scheduleRetry(a);yield this.originalSendPayload(a.url,a.payload),this.debug(`Log ${a.id} retry successful`),this.failedLogs.delete(a.id)}catch(e){this.debug(`Log ${a.id} retry failed:`,e),this.scheduleRetry(a)}}})}initNetworkMonitor(){this.reliableConfig.enableNetworkMonitor&&typeof window!="undefined"&&(this.networkStatus=navigator.onLine?"online":"offline",window.addEventListener("online",()=>{this.handleNetworkChange("online")}),window.addEventListener("offline",()=>{this.handleNetworkChange("offline")}),this.debug(`Network monitor initialized. Current status: ${this.networkStatus}`))}handleNetworkChange(a){const e=this.networkStatus;this.networkStatus=a,this.debug(`Network status changed: ${e} -> ${a}`),this.reliableConfig.onNetworkChange(a==="online"),a==="online"&&e==="offline"&&(this.debug("Network recovered, retrying failed logs"),this.retryAllFailedLogs())}retryAllFailedLogs(){this.failedLogs.size!==0&&(this.debug(`Retrying ${this.failedLogs.size} failed logs after network recovery`),Array.from(this.failedLogs.values()).forEach(a=>{setTimeout(()=>this.retryLog(a),100*Math.random())}))}startRetryTimer(){typeof window!="undefined"&&(this.retryTimer=window.setInterval(()=>{if(this.failedLogs.size>0&&this.networkStatus==="online"){const a=Date.now();Array.from(this.failedLogs.values()).forEach(e=>{a-e.lastRetryTime>this.reliableConfig.retryDelay&&this.retryLog(e)})}},this.reliableConfig.retryDelay),this.debug(`Retry timer started with interval ${this.reliableConfig.retryDelay}ms`))}loadFailedLogs(){if(this.reliableConfig.enableLocalStorage&&typeof localStorage!="undefined")try{const a=localStorage.getItem(this.reliableConfig.storageKey);if(a){const e=JSON.parse(a);e.forEach(t=>{this.failedLogs.set(t.id,t)}),this.debug(`Loaded ${e.length} failed logs from storage`),localStorage.removeItem(this.reliableConfig.storageKey),this.networkStatus==="online"&&this.retryAllFailedLogs()}}catch(a){this.debug("Failed to load failed logs from storage:",a)}}saveFailedLogs(){if(this.reliableConfig.enableLocalStorage&&typeof localStorage!="undefined"&&this.failedLogs.size!==0)try{const a=Array.from(this.failedLogs.values()).slice(-this.reliableConfig.maxStorageSize);localStorage.setItem(this.reliableConfig.storageKey,JSON.stringify(a)),this.debug(`Saved ${a.length} failed logs to storage`)}catch(a){this.debug("Failed to save failed logs to storage:",a)}}generateId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}debug(...a){this.reliableConfig.debug&&typeof console!="undefined"&&console.log("[ReliableWebTracker]",...a)}useStsPlugin(a){this.originalSendPayload=(e,t)=>I(this,null,function*(){return function(i,r,n){return I(this,null,function*(){try{i=i.slice(0,-6);const{data:c,header:o}=yield n.process(i,r);return new Promise((l,d)=>{const h=new window.XMLHttpRequest;h.onload=()=>{h.status>=200&&h.status<300?l():d(new Error(`HTTP ${h.status}: ${h.statusText}`))},h.onerror=()=>{d(new Error("Network error occurred"))},h.ontimeout=()=>{d(new Error("Request timeout"))},h.timeout=1e4,h.open("POST",i,!0);for(let p in o)h.setRequestHeader(p,o[p]);h.send(c)})}catch(c){const o=c instanceof Error?c:new Error(String(c));throw window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
|
|
9
|
-
`+o.message),console.error("Failed log data:",i)),o}})}(e,t,a)}),this.getOpt().sendPayload=(e,t)=>I(this,null,function*(){return this.reliableSendAsync(e,t)}),this.overwriteTransString(a)}getStatus(){return{networkStatus:this.networkStatus,failedLogsCount:this.failedLogs.size,isRetryActive:this.retryTimer!==null,config:this.reliableConfig}}retryAll(){this.debug("Manual retry triggered"),this.retryAllFailedLogs()}clearFailedLogs(){const a=this.failedLogs.size;this.failedLogs.clear(),this.debug(`Cleared ${a} failed logs`)}getFailedLogs(){return Array.from(this.failedLogs.values())}destroy(){this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=null),this.saveFailedLogs(),this.failedLogs.clear(),this.debug("WebTrackerBrowser destroyed")}};const{BrowserUtil:da,SystenUtil:ha}=X.AliRTS,Do=oa(),Oi=6e5,Vi={host:"cn-hangzhou.log.aliyuncs.com",project:"alivc-aio",logstore:"logger",time:10,count:10};function sr(){return ir(new Date,"HH:MM:ss.l")}function ua(){return ir(new Date,"isoDate")}var ar=(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))(ar||{});class Mo{constructor(){g(this,"tracker");g(this,"stsPlugin");g(this,"stsData");g(this,"stsExpiration",Date.now());g(this,"clientId",lt());g(this,"bSesid",lt());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.stsPlugin)return;this.logSequence+=1,a.unshift(this.getLogParams(710203,{log:`[${ua()} ${sr()}] [INF] beforeunload`,stat_log_seq:this.logSequence}));const e=`https://${Vi.project}.${Vi.host}/logstores/${Vi.logstore}`,t={__logs__:a.map(n=>this.stsPlugin.transString(n))},{data:i,header:r}=yield this.stsPlugin.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=sr();this.logLevel<=a&&e(i,...t);let r=Ne.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=lt(),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()},Oi)})}refreshSTSToken(){return I(this,null,function*(){if(!this.stsData||this.stsExpiration<=Date.now()+Oi){const a=yield this.requestSTSToken(),e=new Date(a==null?void 0:a.Expiration).getTime()||0,t=Date.now()+Oi;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:gi.MD5(e).toString(gi.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:ir(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:Oi,stsTokenFreshTime:void 0,refreshSTSToken:()=>{this.refreshSTSToken().then(r=>{e.accessKeyId=r.AccessKeyId,e.accessKeySecret=r.AccessKeySecret,e.securityToken=r.SecurityToken}).catch(()=>{})}},t=new Po(Vi),i=Zi(e);t.useStsPlugin(i),this.stsPlugin=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:Do,db:da.browserName,dm:da.browserVersion,install_uuid:this.clientId,logger_v:"0.0.1",os:ha.systemName,osv:ha.systemVersion,p_sesid:this.bSesid,sdk_version:Ni,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=sr(),t=`[${ua()} ${e}] ${a}`;this.sessionId&&this.tracker?this.sendLog(t):(this.logCache.push(t),this.logCache.length>=200&&this.logCache.shift())}}class N{static getLogger(){return this.logger||(this.logger=new Mo),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(N,"logger");var nr={exports:{}};(function(s,a){(function(e,t){var i="function",r="undefined",n="object",c="string",o="major",l="model",d="name",h="type",p="vendor",u="version",f="architecture",m="console",b="mobile",S="tablet",v="smarttv",R="wearable",w="embedded",y="Amazon",A="Apple",_="ASUS",E="BlackBerry",T="Browser",k="Chrome",P="Firefox",H="Google",q="Huawei",Y="LG",J="Microsoft",z="Motorola",Z="Opera",ee="Samsung",ge="Sharp",D="Sony",x="Xiaomi",L="Zebra",O="Facebook",de="Chromium OS",Pe="Mac OS",K=" Browser",me=function(ne){for(var re={},ie=0;ie<ne.length;ie++)re[ne[ie].toUpperCase()]=ne[ie];return re},Me=function(ne,re){return typeof ne===c&&_e(re).indexOf(_e(ne))!==-1},_e=function(ne){return ne.toLowerCase()},ke=function(ne,re){if(typeof ne===c)return ne=ne.replace(/^\s\s*/,""),typeof re===r?ne:ne.substring(0,500)},fe=function(ne,re){for(var ie,Se,Ve,ue,We,Q,Le=0;Le<re.length&&!We;){var at=re[Le],xe=re[Le+1];for(ie=Se=0;ie<at.length&&!We&&at[ie];)if(We=at[ie++].exec(ne))for(Ve=0;Ve<xe.length;Ve++)Q=We[++Se],typeof(ue=xe[Ve])===n&&ue.length>0?ue.length===2?typeof ue[1]==i?this[ue[0]]=ue[1].call(this,Q):this[ue[0]]=ue[1]:ue.length===3?typeof ue[1]!==i||ue[1].exec&&ue[1].test?this[ue[0]]=Q?Q.replace(ue[1],ue[2]):t:this[ue[0]]=Q?ue[1].call(this,Q,ue[2]):t:ue.length===4&&(this[ue[0]]=Q?ue[3].call(this,Q.replace(ue[1],ue[2])):t):this[ue]=Q||t;Le+=2}},we=function(ne,re){for(var ie in re)if(typeof re[ie]===n&&re[ie].length>0){for(var Se=0;Se<re[ie].length;Se++)if(Me(re[ie][Se],ne))return ie==="?"?t:ie}else if(Me(re[ie],ne))return ie==="?"?t:ie;return re.hasOwnProperty("*")?re["*"]:ne},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"},De={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[u,[d,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[u,[d,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[d,u],[/opios[\/ ]+([\w\.]+)/i],[u,[d,Z+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[u,[d,Z+" GX"]],[/\bopr\/([\w\.]+)/i],[u,[d,Z]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[u,[d,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[u,[d,"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],[d,u],[/quark(?:pc)?\/([-\w\.]+)/i],[u,[d,"Quark"]],[/\bddg\/([\w\.]+)/i],[u,[d,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[u,[d,"UC"+T]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[u,[d,"WeChat"]],[/konqueror\/([\w\.]+)/i],[u,[d,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[u,[d,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[u,[d,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[u,[d,"Smart Lenovo "+T]],[/(avast|avg)\/([\w\.]+)/i],[[d,/(.+)/,"$1 Secure "+T],u],[/\bfocus\/([\w\.]+)/i],[u,[d,P+" Focus"]],[/\bopt\/([\w\.]+)/i],[u,[d,Z+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[u,[d,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[u,[d,"Dolphin"]],[/coast\/([\w\.]+)/i],[u,[d,Z+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[u,[d,"MIUI"+K]],[/fxios\/([\w\.-]+)/i],[u,[d,P]],[/\bqihoobrowser\/?([\w\.]*)/i],[u,[d,"360"]],[/\b(qq)\/([\w\.]+)/i],[[d,/(.+)/,"$1Browser"],u],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[d,/(.+)/,"$1"+K],u],[/samsungbrowser\/([\w\.]+)/i],[u,[d,ee+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[u,[d,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[d,"Sogou Mobile"],u],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[d,u],[/(lbbrowser|rekonq)/i,/\[(linkedin)app\]/i],[d],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[u,d],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[d,O],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],[d,u],[/\bgsa\/([\w\.]+) .*safari\//i],[u,[d,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[u,[d,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[u,[d,k+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[d,k+" WebView"],u],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[u,[d,"Android "+T]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[d,u],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[u,[d,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[u,d],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[d,[u,we,{"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],[d,u],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[d,"Netscape"],u],[/(wolvic|librewolf)\/([\w\.]+)/i],[d,u],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[u,[d,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],[d,[u,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[d,[u,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[f,"amd64"]],[/(ia32(?=;))/i],[[f,_e]],[/((?: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/,"",_e]],[/(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,_e]]],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],[l,[p,ee],[h,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],[l,[p,ee],[h,b]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[l,[p,A],[h,b]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[l,[p,A],[h,S]],[/(macintosh);/i],[l,[p,A]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[l,[p,ge],[h,b]],[/(?:honor)([-\w ]+)[;\)]/i],[l,[p,"Honor"],[h,b]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[l,[p,q],[h,S]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[l,[p,q],[h,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],[[l,/_/g," "],[p,x],[h,b]],[/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[l,/_/g," "],[p,x],[h,S]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[l,[p,"OPPO"],[h,b]],[/\b(opd2\d{3}a?) bui/i],[l,[p,"OPPO"],[h,S]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[l,[p,"Vivo"],[h,b]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[l,[p,"Realme"],[h,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],[l,[p,z],[h,b]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[l,[p,z],[h,S]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[l,[p,Y],[h,S]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[l,[p,Y],[h,b]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[l,[p,"Lenovo"],[h,S]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[l,/_/g," "],[p,"Nokia"],[h,b]],[/(pixel c)\b/i],[l,[p,H],[h,S]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[l,[p,H],[h,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],[l,[p,D],[h,b]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[l,"Xperia Tablet"],[p,D],[h,S]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[l,[p,"OnePlus"],[h,b]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[l,[p,y],[h,S]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[l,/(.+)/g,"Fire Phone $1"],[p,y],[h,b]],[/(playbook);[-\w\),; ]+(rim)/i],[l,p,[h,S]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[l,[p,E],[h,b]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[l,[p,_],[h,S]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[l,[p,_],[h,b]],[/(nexus 9)/i],[l,[p,"HTC"],[h,S]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[p,[l,/_/g," "],[h,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],[l,[p,"TCL"],[h,S]],[/(itel) ((\w+))/i],[[p,_e],l,[h,we,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[l,[p,"Acer"],[h,S]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[l,[p,"Meizu"],[h,b]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[l,[p,"Ulefone"],[h,b]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[l,[p,"Energizer"],[h,b]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[l,[p,"Cat"],[h,b]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[l,[p,"Smartfren"],[h,b]],[/droid.+; (a(?:015|06[35]|142p?))/i],[l,[p,"Nothing"],[h,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,l,[h,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,l,[h,S]],[/(surface duo)/i],[l,[p,J],[h,S]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[l,[p,"Fairphone"],[h,b]],[/(u304aa)/i],[l,[p,"AT&T"],[h,b]],[/\bsie-(\w*)/i],[l,[p,"Siemens"],[h,b]],[/\b(rct\w+) b/i],[l,[p,"RCA"],[h,S]],[/\b(venue[\d ]{2,7}) b/i],[l,[p,"Dell"],[h,S]],[/\b(q(?:mv|ta)\w+) b/i],[l,[p,"Verizon"],[h,S]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[l,[p,"Barnes & Noble"],[h,S]],[/\b(tm\d{3}\w+) b/i],[l,[p,"NuVision"],[h,S]],[/\b(k88) b/i],[l,[p,"ZTE"],[h,S]],[/\b(nx\d{3}j) b/i],[l,[p,"ZTE"],[h,b]],[/\b(gen\d{3}) b.+49h/i],[l,[p,"Swiss"],[h,b]],[/\b(zur\d{3}) b/i],[l,[p,"Swiss"],[h,S]],[/\b((zeki)?tb.*\b) b/i],[l,[p,"Zeki"],[h,S]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[p,"Dragon Touch"],l,[h,S]],[/\b(ns-?\w{0,9}) b/i],[l,[p,"Insignia"],[h,S]],[/\b((nxa|next)-?\w{0,9}) b/i],[l,[p,"NextBook"],[h,S]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[p,"Voice"],l,[h,b]],[/\b(lvtel\-)?(v1[12]) b/i],[[p,"LvTel"],l,[h,b]],[/\b(ph-1) /i],[l,[p,"Essential"],[h,b]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[l,[p,"Envizen"],[h,S]],[/\b(trio[-\w\. ]+) b/i],[l,[p,"MachSpeed"],[h,S]],[/\btu_(1491) b/i],[l,[p,"Rotor"],[h,S]],[/(shield[\w ]+) b/i],[l,[p,"Nvidia"],[h,S]],[/(sprint) (\w+)/i],[p,l,[h,b]],[/(kin\.[onetw]{3})/i],[[l,/\./g," "],[p,J],[h,b]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[l,[p,L],[h,S]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[l,[p,L],[h,b]],[/smart-tv.+(samsung)/i],[p,[h,v]],[/hbbtv.+maple;(\d+)/i],[[l,/^/,"SmartTV"],[p,ee],[h,v]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[p,Y],[h,v]],[/(apple) ?tv/i],[p,[l,A+" TV"],[h,v]],[/crkey/i],[[l,k+"cast"],[p,H],[h,v]],[/droid.+aft(\w+)( bui|\))/i],[l,[p,y],[h,v]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[l,[p,ge],[h,v]],[/(bravia[\w ]+)( bui|\))/i],[l,[p,D],[h,v]],[/(mitv-\w{5}) bui/i],[l,[p,x],[h,v]],[/Hbbtv.*(technisat) (.*);/i],[p,l,[h,v]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[p,ke],[l,ke],[h,v]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[h,v]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[p,l,[h,m]],[/droid.+; (shield) bui/i],[l,[p,"Nvidia"],[h,m]],[/(playstation [345portablevi]+)/i],[l,[p,D],[h,m]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[l,[p,J],[h,m]],[/\b(sm-[lr]\d\d[05][fnuw]?s?)\b/i],[l,[p,ee],[h,R]],[/((pebble))app/i],[p,l,[h,R]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[l,[p,A],[h,R]],[/droid.+; (glass) \d/i],[l,[p,H],[h,R]],[/droid.+; (wt63?0{2,3})\)/i],[l,[p,L],[h,R]],[/droid.+; (glass) \d/i],[l,[p,H],[h,R]],[/(pico) (4|neo3(?: link|pro)?)/i],[p,l,[h,R]],[/; (quest( \d| pro)?)/i],[l,[p,O],[h,R]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[p,[h,w]],[/(aeobc)\b/i],[l,[p,y],[h,w]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[l,[h,b]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[l,[h,S]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[h,S]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[h,b]],[/(android[-\w\. ]{0,9});.+buil/i],[l,[p,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[u,[d,"EdgeHTML"]],[/(arkweb)\/([\w\.]+)/i],[d,u],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[u,[d,"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],[d,u],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[u,d]],os:[[/microsoft (windows) (vista|xp)/i],[d,u],[/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i],[d,[u,we,he]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[u,we,he],[d,"Windows"]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[u,/_/g,"."],[d,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[d,Pe],[u,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[u,d],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish|openharmony)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[d,u],[/\(bb(10);/i],[u,[d,E]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[u,[d,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[u,[d,P+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[u,[d,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[u,[d,"watchOS"]],[/crkey\/([\d\.]+)/i],[u,[d,k+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[d,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],[d,u],[/(sunos) ?([\w\.\d]*)/i],[[d,"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],[d,u]]},ye=function(ne,re){if(typeof ne===n&&(re=ne,ne=t),!(this instanceof ye))return new ye(ne,re).getResult();var ie=typeof e!==r&&e.navigator?e.navigator:t,Se=ne||(ie&&ie.userAgent?ie.userAgent:""),Ve=ie&&ie.userAgentData?ie.userAgentData:t,ue=re?function(Q,Le){var at={};for(var xe in Q)Le[xe]&&Le[xe].length%2==0?at[xe]=Le[xe].concat(Q[xe]):at[xe]=Q[xe];return at}(De,re):De,We=ie&&ie.userAgent==Se;return this.getBrowser=function(){var Q,Le={};return Le[d]=t,Le[u]=t,fe.call(Le,Se,ue.browser),Le[o]=typeof(Q=Le[u])===c?Q.replace(/[^\d\.]/g,"").split(".")[0]:t,We&&ie&&ie.brave&&typeof ie.brave.isBrave==i&&(Le[d]="Brave"),Le},this.getCPU=function(){var Q={};return Q[f]=t,fe.call(Q,Se,ue.cpu),Q},this.getDevice=function(){var Q={};return Q[p]=t,Q[l]=t,Q[h]=t,fe.call(Q,Se,ue.device),We&&!Q[h]&&Ve&&Ve.mobile&&(Q[h]=b),We&&Q[l]=="Macintosh"&&ie&&typeof ie.standalone!==r&&ie.maxTouchPoints&&ie.maxTouchPoints>2&&(Q[l]="iPad",Q[h]=S),Q},this.getEngine=function(){var Q={};return Q[d]=t,Q[u]=t,fe.call(Q,Se,ue.engine),Q},this.getOS=function(){var Q={};return Q[d]=t,Q[u]=t,fe.call(Q,Se,ue.os),We&&!Q[d]&&Ve&&Ve.platform&&Ve.platform!="Unknown"&&(Q[d]=Ve.platform.replace(/chrome os/i,de).replace(/macos/i,Pe)),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?ke(Q,500):Q,this},this.setUA(Se),this};ye.VERSION="1.0.40",ye.BROWSER=me([d,u,o]),ye.CPU=me([f]),ye.DEVICE=me([l,p,h,m,b,v,S,R,w]),ye.ENGINE=ye.OS=me([d,u]),s.exports&&(a=s.exports=ye),a.UAParser=ye;var qe=typeof e!==r&&(e.jQuery||e.Zepto);if(qe&&!qe.ua){var st=new ye;qe.ua=st.getResult(),qe.ua.get=function(){return st.getUA()},qe.ua.set=function(ne){st.setUA(ne);var re=st.getResult();for(var ie in re)qe.ua[ie]=re[ie]}}})(typeof window=="object"?window:ti)})(nr,nr.exports);var Lo=nr.exports,Ue=(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))(Ue||{});class Ui{constructor(a,e){g(this,"authInfo");g(this,"userName");g(this,"seqIndex",0);this.authInfo=a,this.userName=typeof e=="number"?e.toString():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}}}static get adaptInfo(){var e,t,i,r;let a=new Lo.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.2.0",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=Ne.getVersionNumber().toString(),e.header.platform="web",this.roleAuth&&(e.data.auth=this.roleAuth),e.data.adapt=Ui.adaptInfo,a&&(e.data=G(G({},e.data),a)),e}createLeavePackage(){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=Ne.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:lt(),header:{appid:this.authInfo.appId,channelid:this.authInfo.channelId,sessionid:(e=this.authInfo.sessionId)!=null?e:"",userid:this.authInfo.userId},data:{seq:this.seqIndex}}}}var mt=(s=>(s.pre="pre",s.prod="prod",s))(mt||{}),kt=(s=>(s.AliRtcSdkCommunication="communication",s.AliRtcSdkInteractiveLive="interactive_live",s.AliRtcSdkInteractiveWithLowLatencyLive="cdn_live",s))(kt||{}),Nt=(s=>(s.AliRtcSdkInteractive="interactive",s.AliRtcSdkLive="live",s))(Nt||{}),Rt=(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))(Rt||{}),Be=(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))(Be||{}),oe=(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))(oe||{}),At=(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))(At||{}),or=(s=>(s[s.AliRtcUserOfflineQuit=0]="AliRtcUserOfflineQuit",s[s.AliRtcUserOfflineDropped=1]="AliRtcUserOfflineDropped",s[s.AliRtcUserOfflineBecomeAudience=2]="AliRtcUserOfflineBecomeAudience",s))(or||{}),$t=(s=>(s[s.AliRtcAudioTrackNo=0]="AliRtcAudioTrackNo",s[s.AliRtcAudioTrackMic=1]="AliRtcAudioTrackMic",s[s.AliRtcAudioTrackDual=2]="AliRtcAudioTrackDual",s))($t||{}),ce=(s=>(s[s.AliRtcVideoTrackNo=0]="AliRtcVideoTrackNo",s[s.AliRtcVideoTrackCamera=1]="AliRtcVideoTrackCamera",s[s.AliRtcVideoTrackScreen=2]="AliRtcVideoTrackScreen",s[s.AliRtcVideoTrackBoth=3]="AliRtcVideoTrackBoth",s))(ce||{}),te=(s=>(s[s.AliRtcStatePublishIdle=0]="AliRtcStatePublishIdle",s[s.AliRtcStateNoPublish=1]="AliRtcStateNoPublish",s[s.AliRtcStatePublishing=2]="AliRtcStatePublishing",s[s.AliRtcStatePublished=3]="AliRtcStatePublished",s[s.AliRtcStateReconnecting=4]="AliRtcStateReconnecting",s))(te||{}),ae=(s=>(s[s.AliRtcStateSubscribeIdle=0]="AliRtcStateSubscribeIdle",s[s.AliRtcStateNoSubscribe=1]="AliRtcStateNoSubscribe",s[s.AliRtcStateSubscribing=2]="AliRtcStateSubscribing",s[s.AliRtcStateSubscribed=3]="AliRtcStateSubscribed",s[s.AliRtcStateReconnecting=4]="AliRtcStateReconnecting",s))(ae||{}),Ke=(s=>(s[s.AliRtcVideoStreamTypeNone=0]="AliRtcVideoStreamTypeNone",s[s.AliRtcVideoStreamTypeHigh=1]="AliRtcVideoStreamTypeHigh",s[s.AliRtcVideoStreamTypeLow=2]="AliRtcVideoStreamTypeLow",s))(Ke||{}),mi=(s=>(s[s.CAMERA_INVALID=-1]="CAMERA_INVALID",s[s.CAMERA_REAR=0]="CAMERA_REAR",s[s.CAMERA_FRONT=1]="CAMERA_FRONT",s))(mi||{});const pa="ALI_RTC_SDK_ALLOCATE_RESULT",di=class di{constructor(a,e,t){g(this,"result",null);g(this,"pms");let i=localStorage.getItem(pa);if(i){const u=JSON.parse(i);u.appId===e.appId&&u.expireTs-3e5>Date.now()?this.result=u.allocatedData:N.info(`[${di.logName}]`,"allocate","cached data is invalid")}const{appId:r,channelId:n,userId:c,timestamp:o,token:l,nonce:d}=e,h=new URLSearchParams({appid:r,channelid:n,userid:c,timestamp:`${o}`,token:l,nonce:d!=null?d:"",adapt:"true",clitype:"2"});t&&h.set("joinmode",t);const p=a===mt.pre?ri.pre:ri.prod;this.pms=fetch(`https://${p}/gslb/v1/allocate?${h.toString()}`,{method:"POST",body:JSON.stringify(Ui.adaptInfo)}).then(u=>u.json()).then(u=>{if(u.code===0){const f=u.data;this.result=f;const{ice_ufrag:m}=f.h5auth,[b,S]=atob(m).split("_"),v={appId:r,expireTs:1e3*parseInt(S),allocatedData:f};return N.info(`[${di.logName}]`,"got allocate result and save",f.h5auth.ice_ufrag),localStorage.setItem(pa,JSON.stringify(v)),f}return null}).catch(u=>(N.error(`[${di.logName}]`,"allocate",u),null))}};g(di,"logName","Allocator");let fi=di;var 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 V 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 V?e:new V((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 V(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 V(U.ERR_INVALID_ARGUMENTS,"element should be HtmlVideoElement")}throw new V(U.ERR_INVALID_ARGUMENTS,"element not founded")}throw new V(U.ERR_INVALID_ARGUMENTS,"element id should be string")}function cr(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 ma(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 lr(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 Kt(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}}class dr{constructor(a,e){g(this,"originTrack");g(this,"originVideo");g(this,"targetWidth");g(this,"targetHeight");g(this,"targetFrameRate");g(this,"targetCanvas");g(this,"animationFrameId");g(this,"resultTrack");this.targetWidth=e.width,this.targetHeight=e.height,this.targetFrameRate=e.frameRate,this.originTrack=a,this.originVideo=document.createElement("video"),this.originVideo.muted=!0,this.originVideo.autoplay=!0,this.originVideo.controls=!1,this.targetCanvas=document.createElement("canvas"),this.targetCanvas.width=this.targetWidth,this.targetCanvas.height=this.targetHeight}updateOptions(a){this.targetWidth=a.width,this.targetHeight=a.height,this.targetFrameRate=a.frameRate,this.targetCanvas.width=this.targetWidth,this.targetCanvas.height=this.targetHeight,this.resultTrack&&this.resultTrack.applyConstraints({frameRate:this.targetFrameRate})}dispose(){}getVideoTrack(){return this.resultTrack||(this.resultTrack=this.targetCanvas.captureStream().getVideoTracks()[0],this.resultTrack.applyConstraints({frameRate:this.targetFrameRate})),this.resultTrack}cancelAnimation(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=void 0)}getPositionAndSize(a,e,t,i){const r=e/a,n=i/t;let c=t,o=i,l=0,d=0;return n>r?(c=Math.round(o/r),l=Math.round((t-c)/2)):n<r&&(o=Math.round(c*r),d=Math.round((i-o)/2)),{x:l,y:d,width:c,height:o}}}class No extends dr{constructor(e,t){super(e,t);g(this,"targetCtx");this.targetCtx=this.targetCanvas.getContext("2d"),this.startRender=this.startRender.bind(this),this.stopRender=this.startRender.bind(this),this.initStream(e)}initStream(e){const t=new MediaStream;t.addTrack(e),this.originVideo.srcObject=t,this.originVideo.play(),this.originVideo.addEventListener("canplay",this.startRender),this.originVideo.addEventListener("pause",this.stopRender),this.originVideo.addEventListener("ended",this.stopRender)}startRender(){this.cancelAnimation();const e=()=>{if(!this.targetCtx)return;const t=this.getPositionAndSize(this.originVideo.videoWidth,this.originVideo.videoHeight,this.targetWidth,this.targetHeight);this.targetCtx.drawImage(this.originVideo,0,0,this.originVideo.videoWidth,this.originVideo.videoHeight,t.x,t.y,t.width,t.height),this.originVideo.paused||this.originVideo.ended||(this.animationFrameId=requestAnimationFrame(e))};e()}stopRender(){this.cancelAnimation()}dispose(){this.stopRender(),this.originVideo.removeEventListener("play",this.startRender),this.originVideo.removeEventListener("pause",this.stopRender),this.originVideo.removeEventListener("ended",this.stopRender),this.originVideo.pause(),this.originVideo.srcObject=null}}function fa(s,a,e){const t=s.createShader(a);if(t)return s.shaderSource(t,e),s.compileShader(t),s.getShaderParameter(t,s.COMPILE_STATUS)?t:(console.error(`An error occurred compiling the shaders: ${s.getShaderInfoLog(t)}`),s.deleteShader(t),null);console.error("create shader failed")}class Sa extends dr{constructor(e,t){super(e,t);g(this,"targetCtx");g(this,"targetTexture");g(this,"locationMap");this.targetCtx=this.targetCanvas.getContext("webgl2"),this.locationMap={},this.startRender=this.startRender.bind(this),this.stopRender=this.startRender.bind(this),this.updateBuffer=this.updateBuffer.bind(this),this.initGL(),this.initStream(e)}static isSupport(){return function(){let e;try{const t=document.createElement("canvas");t.width=1,t.height=1;const i={alpha:!1,depth:!1,stencil:!1,antialias:!1,preferLowPowerToHighPerformance:!0};e=t.getContext("webgl2",i)}catch(t){return!1}return!!e}()}initGL(){const e=this.targetCtx;if(!e)return;this.targetTexture=function(o){const l=o.createTexture();return o.bindTexture(o.TEXTURE_2D,l),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),l}(e);const t=function(o,l,d){const h=fa(o,o.VERTEX_SHADER,l),p=fa(o,o.FRAGMENT_SHADER,d),u=o.createProgram();if(u&&h&&p)return o.attachShader(u,h),o.attachShader(u,p),o.linkProgram(u),o.getProgramParameter(u,o.LINK_STATUS)?u:(console.error(`Unable to initialize the shader program: ${o.getProgramInfoLog(u)}`),null)}(e,`
|
|
9
|
+
`+o.message),console.error("Failed log data:",i)),o}})}(e,t,a)}),this.getOpt().sendPayload=(e,t)=>I(this,null,function*(){return this.reliableSendAsync(e,t)}),this.overwriteTransString(a)}getStatus(){return{networkStatus:this.networkStatus,failedLogsCount:this.failedLogs.size,isRetryActive:this.retryTimer!==null,config:this.reliableConfig}}retryAll(){this.debug("Manual retry triggered"),this.retryAllFailedLogs()}clearFailedLogs(){const a=this.failedLogs.size;this.failedLogs.clear(),this.debug(`Cleared ${a} failed logs`)}getFailedLogs(){return Array.from(this.failedLogs.values())}destroy(){this.retryTimer&&(clearInterval(this.retryTimer),this.retryTimer=null),this.saveFailedLogs(),this.failedLogs.clear(),this.debug("WebTrackerBrowser destroyed")}};const{BrowserUtil:da,SystenUtil:ha}=X.AliRTS,Do=oa(),Oi=6e5,Vi={host:"cn-hangzhou.log.aliyuncs.com",project:"alivc-aio",logstore:"logger",time:10,count:10};function sr(){return ir(new Date,"HH:MM:ss.l")}function ua(){return ir(new Date,"isoDate")}var ar=(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))(ar||{});class Mo{constructor(){g(this,"tracker");g(this,"stsPlugin");g(this,"stsData");g(this,"stsExpiration",Date.now());g(this,"clientId",lt());g(this,"bSesid",lt());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.stsPlugin)return;this.logSequence+=1,a.unshift(this.getLogParams(710203,{log:`[${ua()} ${sr()}] [INF] beforeunload`,stat_log_seq:this.logSequence}));const e=`https://${Vi.project}.${Vi.host}/logstores/${Vi.logstore}`,t={__logs__:a.map(n=>this.stsPlugin.transString(n))},{data:i,header:r}=yield this.stsPlugin.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=sr();this.logLevel<=a&&e(i,...t);let r=Ne.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=lt(),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()},Oi)})}refreshSTSToken(){return I(this,null,function*(){if(!this.stsData||this.stsExpiration<=Date.now()+Oi){const a=yield this.requestSTSToken(),e=new Date(a==null?void 0:a.Expiration).getTime()||0,t=Date.now()+Oi;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:gi.MD5(e).toString(gi.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:ir(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:Oi,stsTokenFreshTime:void 0,refreshSTSToken:()=>{this.refreshSTSToken().then(r=>{e.accessKeyId=r.AccessKeyId,e.accessKeySecret=r.AccessKeySecret,e.securityToken=r.SecurityToken}).catch(()=>{})}},t=new Po(Vi),i=Zi(e);t.useStsPlugin(i),this.stsPlugin=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:Do,db:da.browserName,dm:da.browserVersion,install_uuid:this.clientId,logger_v:"0.0.1",os:ha.systemName,osv:ha.systemVersion,p_sesid:this.bSesid,sdk_version:Ni,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=sr(),t=`[${ua()} ${e}] ${a}`;this.sessionId&&this.tracker?this.sendLog(t):(this.logCache.push(t),this.logCache.length>=200&&this.logCache.shift())}}class N{static getLogger(){return this.logger||(this.logger=new Mo),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(N,"logger");var nr={exports:{}};(function(s,a){(function(e,t){var i="function",r="undefined",n="object",c="string",o="major",l="model",d="name",h="type",p="vendor",u="version",f="architecture",m="console",b="mobile",S="tablet",v="smarttv",R="wearable",w="embedded",y="Amazon",A="Apple",_="ASUS",E="BlackBerry",T="Browser",k="Chrome",P="Firefox",H="Google",q="Huawei",Y="LG",J="Microsoft",z="Motorola",Z="Opera",ee="Samsung",ge="Sharp",D="Sony",x="Xiaomi",L="Zebra",O="Facebook",de="Chromium OS",Pe="Mac OS",K=" Browser",me=function(ne){for(var re={},ie=0;ie<ne.length;ie++)re[ne[ie].toUpperCase()]=ne[ie];return re},Me=function(ne,re){return typeof ne===c&&_e(re).indexOf(_e(ne))!==-1},_e=function(ne){return ne.toLowerCase()},ke=function(ne,re){if(typeof ne===c)return ne=ne.replace(/^\s\s*/,""),typeof re===r?ne:ne.substring(0,500)},fe=function(ne,re){for(var ie,Se,Ve,ue,We,Q,Le=0;Le<re.length&&!We;){var at=re[Le],xe=re[Le+1];for(ie=Se=0;ie<at.length&&!We&&at[ie];)if(We=at[ie++].exec(ne))for(Ve=0;Ve<xe.length;Ve++)Q=We[++Se],typeof(ue=xe[Ve])===n&&ue.length>0?ue.length===2?typeof ue[1]==i?this[ue[0]]=ue[1].call(this,Q):this[ue[0]]=ue[1]:ue.length===3?typeof ue[1]!==i||ue[1].exec&&ue[1].test?this[ue[0]]=Q?Q.replace(ue[1],ue[2]):t:this[ue[0]]=Q?ue[1].call(this,Q,ue[2]):t:ue.length===4&&(this[ue[0]]=Q?ue[3].call(this,Q.replace(ue[1],ue[2])):t):this[ue]=Q||t;Le+=2}},we=function(ne,re){for(var ie in re)if(typeof re[ie]===n&&re[ie].length>0){for(var Se=0;Se<re[ie].length;Se++)if(Me(re[ie][Se],ne))return ie==="?"?t:ie}else if(Me(re[ie],ne))return ie==="?"?t:ie;return re.hasOwnProperty("*")?re["*"]:ne},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"},De={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[u,[d,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[u,[d,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[d,u],[/opios[\/ ]+([\w\.]+)/i],[u,[d,Z+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[u,[d,Z+" GX"]],[/\bopr\/([\w\.]+)/i],[u,[d,Z]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[u,[d,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[u,[d,"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],[d,u],[/quark(?:pc)?\/([-\w\.]+)/i],[u,[d,"Quark"]],[/\bddg\/([\w\.]+)/i],[u,[d,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[u,[d,"UC"+T]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[u,[d,"WeChat"]],[/konqueror\/([\w\.]+)/i],[u,[d,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[u,[d,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[u,[d,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[u,[d,"Smart Lenovo "+T]],[/(avast|avg)\/([\w\.]+)/i],[[d,/(.+)/,"$1 Secure "+T],u],[/\bfocus\/([\w\.]+)/i],[u,[d,P+" Focus"]],[/\bopt\/([\w\.]+)/i],[u,[d,Z+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[u,[d,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[u,[d,"Dolphin"]],[/coast\/([\w\.]+)/i],[u,[d,Z+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[u,[d,"MIUI"+K]],[/fxios\/([\w\.-]+)/i],[u,[d,P]],[/\bqihoobrowser\/?([\w\.]*)/i],[u,[d,"360"]],[/\b(qq)\/([\w\.]+)/i],[[d,/(.+)/,"$1Browser"],u],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[d,/(.+)/,"$1"+K],u],[/samsungbrowser\/([\w\.]+)/i],[u,[d,ee+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[u,[d,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[d,"Sogou Mobile"],u],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[d,u],[/(lbbrowser|rekonq)/i,/\[(linkedin)app\]/i],[d],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[u,d],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[d,O],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],[d,u],[/\bgsa\/([\w\.]+) .*safari\//i],[u,[d,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[u,[d,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[u,[d,k+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[d,k+" WebView"],u],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[u,[d,"Android "+T]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[d,u],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[u,[d,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[u,d],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[d,[u,we,{"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],[d,u],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[d,"Netscape"],u],[/(wolvic|librewolf)\/([\w\.]+)/i],[d,u],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[u,[d,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],[d,[u,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[d,[u,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[f,"amd64"]],[/(ia32(?=;))/i],[[f,_e]],[/((?: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/,"",_e]],[/(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,_e]]],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],[l,[p,ee],[h,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],[l,[p,ee],[h,b]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[l,[p,A],[h,b]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[l,[p,A],[h,S]],[/(macintosh);/i],[l,[p,A]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[l,[p,ge],[h,b]],[/(?:honor)([-\w ]+)[;\)]/i],[l,[p,"Honor"],[h,b]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[l,[p,q],[h,S]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[l,[p,q],[h,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],[[l,/_/g," "],[p,x],[h,b]],[/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[l,/_/g," "],[p,x],[h,S]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[l,[p,"OPPO"],[h,b]],[/\b(opd2\d{3}a?) bui/i],[l,[p,"OPPO"],[h,S]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[l,[p,"Vivo"],[h,b]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[l,[p,"Realme"],[h,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],[l,[p,z],[h,b]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[l,[p,z],[h,S]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[l,[p,Y],[h,S]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[l,[p,Y],[h,b]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[l,[p,"Lenovo"],[h,S]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[l,/_/g," "],[p,"Nokia"],[h,b]],[/(pixel c)\b/i],[l,[p,H],[h,S]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[l,[p,H],[h,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],[l,[p,D],[h,b]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[l,"Xperia Tablet"],[p,D],[h,S]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[l,[p,"OnePlus"],[h,b]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[l,[p,y],[h,S]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[l,/(.+)/g,"Fire Phone $1"],[p,y],[h,b]],[/(playbook);[-\w\),; ]+(rim)/i],[l,p,[h,S]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[l,[p,E],[h,b]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[l,[p,_],[h,S]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[l,[p,_],[h,b]],[/(nexus 9)/i],[l,[p,"HTC"],[h,S]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[p,[l,/_/g," "],[h,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],[l,[p,"TCL"],[h,S]],[/(itel) ((\w+))/i],[[p,_e],l,[h,we,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[l,[p,"Acer"],[h,S]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[l,[p,"Meizu"],[h,b]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[l,[p,"Ulefone"],[h,b]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[l,[p,"Energizer"],[h,b]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[l,[p,"Cat"],[h,b]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[l,[p,"Smartfren"],[h,b]],[/droid.+; (a(?:015|06[35]|142p?))/i],[l,[p,"Nothing"],[h,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,l,[h,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,l,[h,S]],[/(surface duo)/i],[l,[p,J],[h,S]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[l,[p,"Fairphone"],[h,b]],[/(u304aa)/i],[l,[p,"AT&T"],[h,b]],[/\bsie-(\w*)/i],[l,[p,"Siemens"],[h,b]],[/\b(rct\w+) b/i],[l,[p,"RCA"],[h,S]],[/\b(venue[\d ]{2,7}) b/i],[l,[p,"Dell"],[h,S]],[/\b(q(?:mv|ta)\w+) b/i],[l,[p,"Verizon"],[h,S]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[l,[p,"Barnes & Noble"],[h,S]],[/\b(tm\d{3}\w+) b/i],[l,[p,"NuVision"],[h,S]],[/\b(k88) b/i],[l,[p,"ZTE"],[h,S]],[/\b(nx\d{3}j) b/i],[l,[p,"ZTE"],[h,b]],[/\b(gen\d{3}) b.+49h/i],[l,[p,"Swiss"],[h,b]],[/\b(zur\d{3}) b/i],[l,[p,"Swiss"],[h,S]],[/\b((zeki)?tb.*\b) b/i],[l,[p,"Zeki"],[h,S]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[p,"Dragon Touch"],l,[h,S]],[/\b(ns-?\w{0,9}) b/i],[l,[p,"Insignia"],[h,S]],[/\b((nxa|next)-?\w{0,9}) b/i],[l,[p,"NextBook"],[h,S]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[p,"Voice"],l,[h,b]],[/\b(lvtel\-)?(v1[12]) b/i],[[p,"LvTel"],l,[h,b]],[/\b(ph-1) /i],[l,[p,"Essential"],[h,b]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[l,[p,"Envizen"],[h,S]],[/\b(trio[-\w\. ]+) b/i],[l,[p,"MachSpeed"],[h,S]],[/\btu_(1491) b/i],[l,[p,"Rotor"],[h,S]],[/(shield[\w ]+) b/i],[l,[p,"Nvidia"],[h,S]],[/(sprint) (\w+)/i],[p,l,[h,b]],[/(kin\.[onetw]{3})/i],[[l,/\./g," "],[p,J],[h,b]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[l,[p,L],[h,S]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[l,[p,L],[h,b]],[/smart-tv.+(samsung)/i],[p,[h,v]],[/hbbtv.+maple;(\d+)/i],[[l,/^/,"SmartTV"],[p,ee],[h,v]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[p,Y],[h,v]],[/(apple) ?tv/i],[p,[l,A+" TV"],[h,v]],[/crkey/i],[[l,k+"cast"],[p,H],[h,v]],[/droid.+aft(\w+)( bui|\))/i],[l,[p,y],[h,v]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[l,[p,ge],[h,v]],[/(bravia[\w ]+)( bui|\))/i],[l,[p,D],[h,v]],[/(mitv-\w{5}) bui/i],[l,[p,x],[h,v]],[/Hbbtv.*(technisat) (.*);/i],[p,l,[h,v]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[p,ke],[l,ke],[h,v]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[h,v]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[p,l,[h,m]],[/droid.+; (shield) bui/i],[l,[p,"Nvidia"],[h,m]],[/(playstation [345portablevi]+)/i],[l,[p,D],[h,m]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[l,[p,J],[h,m]],[/\b(sm-[lr]\d\d[05][fnuw]?s?)\b/i],[l,[p,ee],[h,R]],[/((pebble))app/i],[p,l,[h,R]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[l,[p,A],[h,R]],[/droid.+; (glass) \d/i],[l,[p,H],[h,R]],[/droid.+; (wt63?0{2,3})\)/i],[l,[p,L],[h,R]],[/droid.+; (glass) \d/i],[l,[p,H],[h,R]],[/(pico) (4|neo3(?: link|pro)?)/i],[p,l,[h,R]],[/; (quest( \d| pro)?)/i],[l,[p,O],[h,R]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[p,[h,w]],[/(aeobc)\b/i],[l,[p,y],[h,w]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[l,[h,b]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[l,[h,S]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[h,S]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[h,b]],[/(android[-\w\. ]{0,9});.+buil/i],[l,[p,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[u,[d,"EdgeHTML"]],[/(arkweb)\/([\w\.]+)/i],[d,u],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[u,[d,"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],[d,u],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[u,d]],os:[[/microsoft (windows) (vista|xp)/i],[d,u],[/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i],[d,[u,we,he]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[u,we,he],[d,"Windows"]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[u,/_/g,"."],[d,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[d,Pe],[u,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[u,d],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish|openharmony)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[d,u],[/\(bb(10);/i],[u,[d,E]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[u,[d,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[u,[d,P+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[u,[d,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[u,[d,"watchOS"]],[/crkey\/([\d\.]+)/i],[u,[d,k+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[d,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],[d,u],[/(sunos) ?([\w\.\d]*)/i],[[d,"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],[d,u]]},ye=function(ne,re){if(typeof ne===n&&(re=ne,ne=t),!(this instanceof ye))return new ye(ne,re).getResult();var ie=typeof e!==r&&e.navigator?e.navigator:t,Se=ne||(ie&&ie.userAgent?ie.userAgent:""),Ve=ie&&ie.userAgentData?ie.userAgentData:t,ue=re?function(Q,Le){var at={};for(var xe in Q)Le[xe]&&Le[xe].length%2==0?at[xe]=Le[xe].concat(Q[xe]):at[xe]=Q[xe];return at}(De,re):De,We=ie&&ie.userAgent==Se;return this.getBrowser=function(){var Q,Le={};return Le[d]=t,Le[u]=t,fe.call(Le,Se,ue.browser),Le[o]=typeof(Q=Le[u])===c?Q.replace(/[^\d\.]/g,"").split(".")[0]:t,We&&ie&&ie.brave&&typeof ie.brave.isBrave==i&&(Le[d]="Brave"),Le},this.getCPU=function(){var Q={};return Q[f]=t,fe.call(Q,Se,ue.cpu),Q},this.getDevice=function(){var Q={};return Q[p]=t,Q[l]=t,Q[h]=t,fe.call(Q,Se,ue.device),We&&!Q[h]&&Ve&&Ve.mobile&&(Q[h]=b),We&&Q[l]=="Macintosh"&&ie&&typeof ie.standalone!==r&&ie.maxTouchPoints&&ie.maxTouchPoints>2&&(Q[l]="iPad",Q[h]=S),Q},this.getEngine=function(){var Q={};return Q[d]=t,Q[u]=t,fe.call(Q,Se,ue.engine),Q},this.getOS=function(){var Q={};return Q[d]=t,Q[u]=t,fe.call(Q,Se,ue.os),We&&!Q[d]&&Ve&&Ve.platform&&Ve.platform!="Unknown"&&(Q[d]=Ve.platform.replace(/chrome os/i,de).replace(/macos/i,Pe)),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?ke(Q,500):Q,this},this.setUA(Se),this};ye.VERSION="1.0.40",ye.BROWSER=me([d,u,o]),ye.CPU=me([f]),ye.DEVICE=me([l,p,h,m,b,v,S,R,w]),ye.ENGINE=ye.OS=me([d,u]),s.exports&&(a=s.exports=ye),a.UAParser=ye;var qe=typeof e!==r&&(e.jQuery||e.Zepto);if(qe&&!qe.ua){var st=new ye;qe.ua=st.getResult(),qe.ua.get=function(){return st.getUA()},qe.ua.set=function(ne){st.setUA(ne);var re=st.getResult();for(var ie in re)qe.ua[ie]=re[ie]}}})(typeof window=="object"?window:ti)})(nr,nr.exports);var Lo=nr.exports,Ue=(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))(Ue||{});class Ui{constructor(a,e){g(this,"authInfo");g(this,"userName");g(this,"seqIndex",0);this.authInfo=a,this.userName=typeof e=="number"?e.toString():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}}}static get adaptInfo(){var e,t,i,r;let a=new Lo.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.2.1",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=Ne.getVersionNumber().toString(),e.header.platform="web",this.roleAuth&&(e.data.auth=this.roleAuth),e.data.adapt=Ui.adaptInfo,a&&(e.data=G(G({},e.data),a)),e}createLeavePackage(){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=Ne.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:lt(),header:{appid:this.authInfo.appId,channelid:this.authInfo.channelId,sessionid:(e=this.authInfo.sessionId)!=null?e:"",userid:this.authInfo.userId},data:{seq:this.seqIndex}}}}var mt=(s=>(s.pre="pre",s.prod="prod",s))(mt||{}),kt=(s=>(s.AliRtcSdkCommunication="communication",s.AliRtcSdkInteractiveLive="interactive_live",s.AliRtcSdkInteractiveWithLowLatencyLive="cdn_live",s))(kt||{}),Nt=(s=>(s.AliRtcSdkInteractive="interactive",s.AliRtcSdkLive="live",s))(Nt||{}),Rt=(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))(Rt||{}),Be=(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))(Be||{}),oe=(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))(oe||{}),At=(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))(At||{}),or=(s=>(s[s.AliRtcUserOfflineQuit=0]="AliRtcUserOfflineQuit",s[s.AliRtcUserOfflineDropped=1]="AliRtcUserOfflineDropped",s[s.AliRtcUserOfflineBecomeAudience=2]="AliRtcUserOfflineBecomeAudience",s))(or||{}),$t=(s=>(s[s.AliRtcAudioTrackNo=0]="AliRtcAudioTrackNo",s[s.AliRtcAudioTrackMic=1]="AliRtcAudioTrackMic",s[s.AliRtcAudioTrackDual=2]="AliRtcAudioTrackDual",s))($t||{}),ce=(s=>(s[s.AliRtcVideoTrackNo=0]="AliRtcVideoTrackNo",s[s.AliRtcVideoTrackCamera=1]="AliRtcVideoTrackCamera",s[s.AliRtcVideoTrackScreen=2]="AliRtcVideoTrackScreen",s[s.AliRtcVideoTrackBoth=3]="AliRtcVideoTrackBoth",s))(ce||{}),te=(s=>(s[s.AliRtcStatePublishIdle=0]="AliRtcStatePublishIdle",s[s.AliRtcStateNoPublish=1]="AliRtcStateNoPublish",s[s.AliRtcStatePublishing=2]="AliRtcStatePublishing",s[s.AliRtcStatePublished=3]="AliRtcStatePublished",s[s.AliRtcStateReconnecting=4]="AliRtcStateReconnecting",s))(te||{}),ae=(s=>(s[s.AliRtcStateSubscribeIdle=0]="AliRtcStateSubscribeIdle",s[s.AliRtcStateNoSubscribe=1]="AliRtcStateNoSubscribe",s[s.AliRtcStateSubscribing=2]="AliRtcStateSubscribing",s[s.AliRtcStateSubscribed=3]="AliRtcStateSubscribed",s[s.AliRtcStateReconnecting=4]="AliRtcStateReconnecting",s))(ae||{}),Ke=(s=>(s[s.AliRtcVideoStreamTypeNone=0]="AliRtcVideoStreamTypeNone",s[s.AliRtcVideoStreamTypeHigh=1]="AliRtcVideoStreamTypeHigh",s[s.AliRtcVideoStreamTypeLow=2]="AliRtcVideoStreamTypeLow",s))(Ke||{}),mi=(s=>(s[s.CAMERA_INVALID=-1]="CAMERA_INVALID",s[s.CAMERA_REAR=0]="CAMERA_REAR",s[s.CAMERA_FRONT=1]="CAMERA_FRONT",s))(mi||{});const pa="ALI_RTC_SDK_ALLOCATE_RESULT",di=class di{constructor(a,e,t){g(this,"result",null);g(this,"pms");let i=localStorage.getItem(pa);if(i){const u=JSON.parse(i);u.appId===e.appId&&u.expireTs-3e5>Date.now()?this.result=u.allocatedData:N.info(`[${di.logName}]`,"allocate","cached data is invalid")}const{appId:r,channelId:n,userId:c,timestamp:o,token:l,nonce:d}=e,h=new URLSearchParams({appid:r,channelid:n,userid:c,timestamp:`${o}`,token:l,nonce:d!=null?d:"",adapt:"true",clitype:"2"});t&&h.set("joinmode",t);const p=a===mt.pre?ri.pre:ri.prod;this.pms=fetch(`https://${p}/gslb/v1/allocate?${h.toString()}`,{method:"POST",body:JSON.stringify(Ui.adaptInfo)}).then(u=>u.json()).then(u=>{if(u.code===0){const f=u.data;this.result=f;const{ice_ufrag:m}=f.h5auth,[b,S]=atob(m).split("_"),v={appId:r,expireTs:1e3*parseInt(S),allocatedData:f};return N.info(`[${di.logName}]`,"got allocate result and save",f.h5auth.ice_ufrag),localStorage.setItem(pa,JSON.stringify(v)),f}return null}).catch(u=>(N.error(`[${di.logName}]`,"allocate",u),null))}};g(di,"logName","Allocator");let fi=di;var 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 V 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 V?e:new V((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 V(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 V(U.ERR_INVALID_ARGUMENTS,"element should be HtmlVideoElement")}throw new V(U.ERR_INVALID_ARGUMENTS,"element not founded")}throw new V(U.ERR_INVALID_ARGUMENTS,"element id should be string")}function cr(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 ma(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 lr(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 Kt(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}}class dr{constructor(a,e){g(this,"originTrack");g(this,"originVideo");g(this,"targetWidth");g(this,"targetHeight");g(this,"targetFrameRate");g(this,"targetCanvas");g(this,"animationFrameId");g(this,"resultTrack");this.targetWidth=e.width,this.targetHeight=e.height,this.targetFrameRate=e.frameRate,this.originTrack=a,this.originVideo=document.createElement("video"),this.originVideo.muted=!0,this.originVideo.autoplay=!0,this.originVideo.controls=!1,this.targetCanvas=document.createElement("canvas"),this.targetCanvas.width=this.targetWidth,this.targetCanvas.height=this.targetHeight}updateOptions(a){this.targetWidth=a.width,this.targetHeight=a.height,this.targetFrameRate=a.frameRate,this.targetCanvas.width=this.targetWidth,this.targetCanvas.height=this.targetHeight,this.resultTrack&&this.resultTrack.applyConstraints({frameRate:this.targetFrameRate})}dispose(){}getVideoTrack(){return this.resultTrack||(this.resultTrack=this.targetCanvas.captureStream().getVideoTracks()[0],this.resultTrack.applyConstraints({frameRate:this.targetFrameRate})),this.resultTrack}cancelAnimation(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=void 0)}getPositionAndSize(a,e,t,i){const r=e/a,n=i/t;let c=t,o=i,l=0,d=0;return n>r?(c=Math.round(o/r),l=Math.round((t-c)/2)):n<r&&(o=Math.round(c*r),d=Math.round((i-o)/2)),{x:l,y:d,width:c,height:o}}}class No extends dr{constructor(e,t){super(e,t);g(this,"targetCtx");this.targetCtx=this.targetCanvas.getContext("2d"),this.startRender=this.startRender.bind(this),this.stopRender=this.startRender.bind(this),this.initStream(e)}initStream(e){const t=new MediaStream;t.addTrack(e),this.originVideo.srcObject=t,this.originVideo.play(),this.originVideo.addEventListener("canplay",this.startRender),this.originVideo.addEventListener("pause",this.stopRender),this.originVideo.addEventListener("ended",this.stopRender)}startRender(){this.cancelAnimation();const e=()=>{if(!this.targetCtx)return;const t=this.getPositionAndSize(this.originVideo.videoWidth,this.originVideo.videoHeight,this.targetWidth,this.targetHeight);this.targetCtx.drawImage(this.originVideo,0,0,this.originVideo.videoWidth,this.originVideo.videoHeight,t.x,t.y,t.width,t.height),this.originVideo.paused||this.originVideo.ended||(this.animationFrameId=requestAnimationFrame(e))};e()}stopRender(){this.cancelAnimation()}dispose(){this.stopRender(),this.originVideo.removeEventListener("play",this.startRender),this.originVideo.removeEventListener("pause",this.stopRender),this.originVideo.removeEventListener("ended",this.stopRender),this.originVideo.pause(),this.originVideo.srcObject=null}}function fa(s,a,e){const t=s.createShader(a);if(t)return s.shaderSource(t,e),s.compileShader(t),s.getShaderParameter(t,s.COMPILE_STATUS)?t:(console.error(`An error occurred compiling the shaders: ${s.getShaderInfoLog(t)}`),s.deleteShader(t),null);console.error("create shader failed")}class Sa extends dr{constructor(e,t){super(e,t);g(this,"targetCtx");g(this,"targetTexture");g(this,"locationMap");this.targetCtx=this.targetCanvas.getContext("webgl2"),this.locationMap={},this.startRender=this.startRender.bind(this),this.stopRender=this.startRender.bind(this),this.updateBuffer=this.updateBuffer.bind(this),this.initGL(),this.initStream(e)}static isSupport(){return function(){let e;try{const t=document.createElement("canvas");t.width=1,t.height=1;const i={alpha:!1,depth:!1,stencil:!1,antialias:!1,preferLowPowerToHighPerformance:!0};e=t.getContext("webgl2",i)}catch(t){return!1}return!!e}()}initGL(){const e=this.targetCtx;if(!e)return;this.targetTexture=function(o){const l=o.createTexture();return o.bindTexture(o.TEXTURE_2D,l),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),l}(e);const t=function(o,l,d){const h=fa(o,o.VERTEX_SHADER,l),p=fa(o,o.FRAGMENT_SHADER,d),u=o.createProgram();if(u&&h&&p)return o.attachShader(u,h),o.attachShader(u,p),o.linkProgram(u),o.getProgramParameter(u,o.LINK_STATUS)?u:(console.error(`Unable to initialize the shader program: ${o.getProgramInfoLog(u)}`),null)}(e,`
|
|
10
10
|
attribute vec2 a_position;
|
|
11
11
|
attribute vec2 a_texCoord;
|
|
12
12
|
|
|
@@ -129,9 +129,9 @@ onmessage = function(evt) {
|
|
|
129
129
|
`);return n<0?`${i}${r}`:`${i.slice(0,n)}${r}${i.slice(n)}`}(e.stack,this.marker))})}updateOptions(a){this.options=G(G({},this.options),a)}setReady(){this.initArmsLogger(!0),this.isReady=!0,this.queue.length&&this.queue.forEach(a=>{var e;(e=this.armsLogger)==null||e.error(this.helper.MediaboxWrapperQueue(a.msg),{filename:a.file,lineno:a.line,colno:a.col})})}report(a,e){var t;(t=this.armsLogger)==null||t.error(this.helper.MediaboxWrapperInitiative(a),e)}destroy(){this.isDestroyed=!0}}var Ce=(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))(Ce||{}),Qe=(s=>(s.Local="local-device-status-change",s.Remote="remote-device-status-change",s))(Qe||{}),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||{}),Tr=(s=>(s.Audio="rts audio",s.VideoLarge="rts video",s))(Tr||{}),Ot=(s=>(s.Add="add",s.Delete="delete",s.Replace="replace",s.Stop="stop",s.UnPublish="unpublish",s))(Ot||{}),Si=(s=>(s[s.Camera=0]="Camera",s[s.Screen=1]="Screen",s[s.Image=2]="Image",s))(Si||{}),Bi=(s=>(s[s.Microphone=0]="Microphone",s[s.Screen=1]="Screen",s[s.Mixed=2]="Mixed",s))(Bi||{}),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||{}),_t=(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))(_t||{});function ai(){}const Qt=class Qt{static getInstance(){var a;return Qt.instance||(Qt.instance=new AudioContext),(a=Qt.instance.resume())==null||a.then(ai,ai).catch(ai),Qt.instance}};g(Qt,"instance");let Gt=Qt;const Hi=()=>{var a;const s=Gt.getInstance();s.state!=="running"&&s.state!=="closed"&&((a=s.resume())==null||a.then(ai,ai).catch(ai)),window.removeEventListener("mousedown",Hi),window.removeEventListener("touchstart",Hi)};window.addEventListener("mousedown",Hi),window.addEventListener("touchstart",Hi);class Wo extends se{constructor(){super();g(this,"audioContext");g(this,"stream");g(this,"sourceNode");g(this,"analyser");this.audioContext=Gt.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,l){let d,h=o,p=0;const u=r.createAnalyser();u.fftSize=256;const f=new Uint8Array(u.frequencyBinCount);n.connect(u),u.connect(c);const m=()=>{d&&window.clearInterval(d)},b=()=>{r.state==="suspended"&&r.resume(),d=window.setInterval(()=>{u.getByteFrequencyData(f);let S=Math.round(f.reduce((v,R)=>v+R)/f.length);S=Math.min(100,S),p=S,l&&l(S)},h)};return b(),{updateInterval:S=>{m(),h=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 Xa 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 Wo}get userId(){return this.uid}get displayname(){return this.name}createCallId(e=!1){this.callId&&!e||(this.callId=Ne.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 Ya{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)}}}const C=(s,a)=>(e,t,i)=>{const r=i.value;return i.value=function(...n){var h;const c=`[${((h=e.constructor)==null?void 0:h.logName)||""}]`,o=Date.now();let l=[];if(s)try{l=s(n)}catch(p){}N.interface(c,t,...l);const d=r.apply(this,n);return Promise.resolve(d).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){}}N.interfaceResult(c,t,!(f&&m),Date.now()-o+"ms",u)}}),d},i},B=s=>s,Qa="customVideoProfile",Za="customScreenProfile",Cr={width:1280,height:720,frameRate:30,maxBitrate:2e3},en={width:1920,height:1080,frameRate:30,maxBitrate:2600};var bi=(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))(bi||{});const $o={1e4:Be.AliEngineLocalDeviceExceptionTypeUnknown,2e4:Be.AliEngineLocalDeviceExceptionTypeUnknown,10001:Be.AliEngineLocalDeviceExceptionTypeMicNotAvailable,10002:Be.AliEngineLocalDeviceExceptionTypeMicAuthFail,10003:Be.AliEngineLocalDeviceExceptionTypeMicOpenFail,10005:Be.AliEngineLocalDeviceExceptionTypeCameraAuthFail,10004:Be.AliEngineLocalDeviceExceptionTypeVideoDeviceException,10006:Be.AliEngineLocalDeviceExceptionTypeCameraOpenFail,10010:Be.AliEngineLocalDeviceExceptionTypeDisplayException,10011:Be.AliEngineLocalDeviceExceptionTypeDisplayException,10012:Be.AliEngineLocalDeviceExceptionTypeDisplayException,10013:Be.AliEngineLocalDeviceExceptionTypeDisplayException,10014:Be.AliEngineLocalDeviceExceptionTypeDisplayException,10019:Be.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||{}),dt=(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))(dt||{});const tn=(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)})},wt=s=>{Promise.race([xt(100),s._playPromise||Promise.resolve()]).catch(()=>{}).then(()=>{s.srcObject=null,s._playPromise=void 0})};var kr=(s=>(s[s.AliEngineDataMsgNone=0]="AliEngineDataMsgNone",s[s.AliEngineDataMsgMusicProgress=1]="AliEngineDataMsgMusicProgress",s[s.AliEngineDataMsgCustom=2]="AliEngineDataMsgCustom",s))(kr||{});class Fi{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 Fi(r,n,t,i)}}class ji{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 Fi(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 vi{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,l=15&e.getUint8(1),d=e.getUint16(2);return new vi(d,t,n,i,r,c,o,l)}}class zi{constructor(a,e){g(this,"_body");g(this,"_header",new vi);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=vi.parse(e);let i=new ArrayBuffer(0);return a.byteLength-4>=t.payloadLength&&(i=a.slice(4,4+t.payloadLength)),new zi(t,i)}}const Pr=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 rn=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 ji(0,0,0);a.write(1,Uint8Array.from([0]).buffer),a.write(2,Uint16Array.from([0]).buffer),rn++,a.write(3,Uint32Array.from([rn]).buffer);const e=new ji;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;Fi.parse(a.slice(0,4));const e=ji.parse(a.slice(4))[30];if(!e)return;const t=ji.parse(e),i=t[2],r=t[3],n=t[4],c=t[5];return c.byteLength!==0?new Vt(c,Pr(i),Pr(n),Pr(r)):void 0}}var Ko=Object.defineProperty,Jo=Object.getOwnPropertyDescriptor,Ee=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?Jo(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&&Ko(a,e,r),r};class yi extends se{constructor(){super();g(this,"_state");g(this,"time");this._state=te.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 Re=(St=class extends Xa{constructor(e){const{rtsManager:t,localStreamManager:i,slsReporter:r,signalingManager:n,audioVolumeIndicationInterval:c,parameter:o}=e;super("","",t,c);g(this,"sessionId","");g(this,"traceId","");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",lt());g(this,"signalingManager");g(this,"shouldPublish",!1);g(this,"monitorTimerId");g(this,"monitorDataCache",{});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",l=>{this.onTrackEnd(l)}),this.streamManager.on("publishupdate",()=>{this.publishUpdate()}),this.audioPubState=new yi,this.audioPubState.on("change",(l,d,h)=>{this.emit("audioPublishStateChanged",l,d,h)}),this.videoPubState=new yi,this.videoPubState.on("change",(l,d,h)=>{this.emit("videoPublishStateChanged",l,d,h)}),this.videoSmallPubState=new yi,this.videoSmallPubState.on("change",(l,d,h)=>{this.emit("dualStreamPublishStateChanged",l,d,h)}),this.screenPubState=new yi,this.screenPubState.on("change",(l,d,h)=>{this.emit("screenPublishStateChanged",l,d,h)}),this.dataPubState=new yi,this.dataPubState.on("change",(l,d,h)=>{this.emit("dataPublishStateChanged",l,d,h)}),this.startStreamMonitor(),this.createCallId()}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.sessionId=e.sessionId||Ne.createCallid("web"),this.updatePubId()}setVideoProfile(e){return I(this,null,function*(){yield this.streamManager.setVideoProfile(Qa,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(Za,e)})}setCameraDirection(e){if(e===mi.CAMERA_FRONT)this.streamManager.setCameraVideoConstraints({facingMode:"user"});else{if(e!==mi.CAMERA_REAR)throw new V(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=lt()}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*(){Zr(St.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)&&(wt(e),this.previewElements.splice(this.previewElements.indexOf(e),1)),this.screenPreviewElements.includes(e)&&(wt(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,l=!t&&!e&&!i&&r,d=!n&&!c&&o;try{l&&d?yield this.startCameraAndMic():l?yield this.startCameraCapture():d&&(yield this.startAudioCapture())}catch(h){const p=h.errorCode;let u=U.ERR_CAMERA_OPEN_FAIL;throw l?((p===bi.ERROR_DEVICE_VIDEODEVICE_NOTALLOWED||bi.ERROR_DEVICE_NOTALLOWED)&&(u=U.ERR_CAMERA_AUTH_FAIL),u=U.ERR_CAMERA_OPEN_FAIL):((p===bi.ERROR_DEVICE_AUDIODEVICE_NOTALLOWED||bi.ERROR_DEVICE_NOTALLOWED)&&(u=U.ERR_MIC_AUTH_FAIL),u=U.ERR_MIC_OPEN_FAIL),new V(u,`auto open fail: ${h.message}`)}})}setViewConfig(e,t){if(e){if(![ce.AliRtcVideoTrackCamera,ce.AliRtcVideoTrackScreen].includes(t))throw new V(U.ERR_INVALID_ARGUMENTS,"set view config invalid track",{track:t});e.forEach(i=>{this.setPreviewElement({videoElement:i,screen:t===ce.AliRtcVideoTrackScreen})})}else t===ce.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 V(U.ERR_INVALID_ARGUMENTS,"no video element found",{videoElement:t});return r?(tn(t,r.mediaStream),this.setPreviewElement(e),r.mediaStream):void N.info(`[${St.logName}]`,"preview no stream founded")}catch(r){const n=U.ERR_INNER;throw V.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),wt(t);else{const c=this.screenPreviewElements.findIndex(o=>o===t);c>=0&&(this.screenPreviewElements.splice(c,1),wt(t))}}else i&&(this.previewElements.forEach(n=>{wt(n)}),this.previewElements=[]),r&&(this.screenPreviewElements.forEach(n=>{wt(n)}),this.screenPreviewElements=[])}resumePublish(){return I(this,null,function*(){this.shouldPublish&&(this.createCallId(!0),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];wt(r)}else if(e.screen)for(let i=0;i<this.screenPreviewElements.length;i++){const r=this.screenPreviewElements[i];wt(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=$o[t.errorCode];throw i&&(e.audio?this.emit("localDeviceException",Rt.AliEngineLocalDeviceTypeMic,i,""):e.video?this.emit("localDeviceException",Rt.AliEngineLocalDeviceTypeCamera,i,""):e.screen?this.emit("localDeviceException",Rt.AliEngineLocalDeviceTypeDisplay,i,""):this.emit("localDeviceException",Rt.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){e&&(this.dc=e,this.dc.datachannel&&(this.dc.datachannel.binaryType="arraybuffer"))}publishDataChannel(){return I(this,null,function*(){if(this.dataPubState.state!==te.AliRtcStatePublishing){this.dataPubState.setState(te.AliRtcStatePublishing);try{const e=yield this.rtsManager.publishAddDataChannel(this.url);e?(this.updateDataChannel(e),this.dataPubState.setState(te.AliRtcStatePublished)):(this.dataPubState.setState(te.AliRtcStateNoPublish),this.emit("publishDataError",new V(U.ERR_INNER,"publishDataError")))}catch(e){N.error("[LocalUser]","publishDataChannel error",e),this.dataPubState.setState(te.AliRtcStateNoPublish)}}})}startPublish(){return I(this,arguments,function*(e=!1,t=_t.MANUAL){var l;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)try{const d=new Date().getTime();r&&this.audioPubState.setState(te.AliRtcStatePublishing),n&&this.videoPubState.setState(te.AliRtcStatePublishing),c&&this.videoSmallPubState.setState(te.AliRtcStatePublishing),o&&this.screenPubState.setState(te.AliRtcStatePublishing),this.publishPromise=this.rtsManager.publish(this,e,t);const{traceId:h,l1ip:p}=yield this.publishPromise;this.streamTracks=this.rtsManager.publishingTracks,this.traceId=h;const u={type:Ot.Add,userid:this.userId,sessionid:this.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:h};(l=this.parameter.data)!=null&&l.enablePubDataChannel&&this.publishDataChannel().then(()=>{this.syncPublishToRoomServer(u,i,d)}),h&&(this.traceId=h),r&&this.reportAudioProfile(),n&&this.reportVideoProfile(),o&&this.reportScreenProfile(),yield this.syncPublishToRoomServer(u,i,d),r&&this.audioPubState.setState(te.AliRtcStatePublished),n&&this.videoPubState.setState(te.AliRtcStatePublished),c&&this.videoSmallPubState.setState(te.AliRtcStatePublished),o&&this.screenPubState.setState(te.AliRtcStatePublished)}catch(d){throw r&&this.audioPubState.setState(te.AliRtcStateNoPublish),n&&this.videoPubState.setState(te.AliRtcStateNoPublish),c&&this.videoSmallPubState.setState(te.AliRtcStateNoPublish),o&&this.screenPubState.setState(te.AliRtcStateNoPublish),d}else N.event(`[${St.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,l,d;if(N.info(`[${St.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 h=(n=this.streamTracks)==null?void 0:n.find(({ssrc:R,type:w,msid:y})=>w==="audio"&&R&&y===M.Audio),p=yield this.compareAndPublish(h,t.audio,M.Audio);p&&(i=p);const u=(c=this.streamTracks)==null?void 0:c.find(({ssrc:R,type:w,msid:y})=>w==="video"&&R&&y===M.VideoLarge),f=yield this.compareAndPublish(u,t.video,M.VideoLarge);f&&(i=f);const m=(o=this.streamTracks)==null?void 0:o.find(({ssrc:R,type:w,msid:y})=>w==="video"&&R&&y===M.VideoSmall),b=yield this.compareAndPublish(m,t.videoSmall,M.VideoSmall);b&&(i=b);const S=(l=this.streamTracks)==null?void 0:l.find(({ssrc:R,type:w,msid:y})=>w==="video"&&R&&y===M.Screen),v=yield this.compareAndPublish(S,t.screen,M.Screen);v&&(i=v),(d=this.parameter.data)!=null&&d.enablePubDataChannel&&!this.dc&&(yield this.publishDataChannel()),i||e!==_t.RECONNECT?i&&(yield this.syncPublishToRoomServer(i,t,r)):this.syncPublishToRoomServer({type:Ot.Add,userid:this.userId,sessionid:this.sessionId,displayname:this.name,pubid:this.publishId,subscribe:{signal:"",pullstreamurl:this.url},callid:this.callId,tracks:this.rtsManager.publishingTracks,traceid:this.traceId},t,Date.now())}catch(h){const{code:p}=h!=null?h:{},u=this.url;throw p===403&&u&&(yield this.refreshPushStreamUrl(),i=yield this.publishUpdate()),h}return i})}syncPublishToRoomServer(e,t,i){return I(this,null,function*(){var o;if(!e)return void N.event(`[${St.logName}]`,"sync publish to room server failed because no publishInfo");let r=e;if(this.dc){const c=e,{tracks:l}=c,d=Mt(c,["tracks"]);r=yt(G({},d),{tracks:[...l,{type:"data",msid:M.Data,ssrc:`web_${this.callId.substring(0,8)}_${((o=this.dc.datachannel)==null?void 0:o.id)||"0"}`,codec:"text"}]})}const n=yield this.signalingManager.publish(r);e.signaltid=n.tid})}refreshPushStreamUrl(){return I(this,null,function*(){const e=new V(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*(){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,l=(t==null?void 0:t.vMsid)===M.Screen;n&&this.audioPubState.setState(te.AliRtcStatePublishing),c&&this.videoPubState.setState(te.AliRtcStatePublishing),o&&this.videoSmallPubState.setState(te.AliRtcStatePublishing),l&&this.screenPubState.setState(te.AliRtcStatePublishing);try{const d=yield this.rtsManager.publishAdd(this,e,t,!1,!0);d&&(this.traceId=d),n&&(this.audioPubState.setState(te.AliRtcStatePublished),this.reportAudioProfile()),c&&(this.videoPubState.setState(te.AliRtcStatePublished),this.reportVideoProfile()),o&&this.videoSmallPubState.setState(te.AliRtcStatePublished),l&&(this.screenPubState.setState(te.AliRtcStatePublished),this.reportScreenProfile()),this.streamTracks=this.rtsManager.publishingTracks;const h={type:Ot.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:d};return this.reportSelfDeviceStatus(),this.monitorTimerId||this.startStreamMonitor(),h}catch(d){let h=U.ERR_SDK_PUBLISH_INVAILD;if(n&&(this.audioPubState.setState(te.AliRtcStateNoPublish),h=U.ERR_SDK_PUBLISH_AUDIO_STREAM_FAILED),c&&(this.videoPubState.setState(te.AliRtcStateNoPublish),h=U.ERR_SDK_PUBLISH_VIDEO_STREAM_FAILED),o&&(this.videoSmallPubState.setState(te.AliRtcStateNoPublish),h=U.ERR_SDK_PUBLISH_DUAL_STREAM_FAILED),l&&(this.screenPubState.setState(te.AliRtcStateNoPublish),h=U.ERR_SDK_PUBLISH_SCEEN_SHARE_FAILED),d.errorCode===15006&&r<3)return this.publishAdd(e,t,i,r+1);throw V.fromError(d,h,"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:Ot.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 V.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:Ot.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(te.AliRtcStateNoPublish),e.video&&(e.vMsid===M.VideoSmall?this.videoSmallPubState.setState(te.AliRtcStateNoPublish):this.videoPubState.setState(te.AliRtcStateNoPublish)),e.screen&&this.screenPubState.setState(te.AliRtcStateNoPublish),t.tracks=this.streamTracks,this.reportSelfDeviceStatus(),t}catch(i){throw V.fromError(i,U.ERR_INNER,"publish delete tracks failed")}})}publishStop(){return I(this,null,function*(){N.info(`[${St.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(te.AliRtcStateNoPublish),i&&this.videoPubState.setState(te.AliRtcStateNoPublish),r&&this.videoSmallPubState.setState(te.AliRtcStateNoPublish),n&&this.screenPubState.setState(te.AliRtcStateNoPublish),this.traceId="",Object.keys(this.monitorDataCache).forEach(o=>{this.reportPublishMonitor(o)}),this.streamTracks=[];const c={type:Ot.Stop,userid:this.userId,sessionid:this.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 V.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:Ot.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(te.AliRtcStateNoPublish),r&&this.videoPubState.setState(te.AliRtcStateNoPublish),n&&this.videoSmallPubState.setState(te.AliRtcStateNoPublish),c&&this.screenPubState.setState(te.AliRtcStateNoPublish),this.traceId="",this.clearStream()}return this.dc&&(this.rtsManager.publishStopDataChannel(this.url,this.dc),this.dataPubState.setState(te.AliRtcStateNoPublish),this.dc=void 0),this.slsReporter.reportUnpublish(this.callId||"",e,0,""),t}catch(i){throw V.fromError(i,U.ERR_INNER,"unpublish failed")}})}reportSelfDeviceStatus(){this.emit(Qe.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),Ya.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.traceId||"",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(l=>{l.type==="media-source"||l.type==="media-playout"?l.id&&(this.pcMediaStatsMap[l.id]=l):l.type==="candidate-pair"&&l.state==="succeeded"&&(n=l)}),((e=this.candidateDataCache)==null?void 0:e.length)>0){const l=this.candidateDataCache[this.candidateDataCache.length-1]||{},t=l,{_last:d}=t;c=Mt(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(l=>{var d;return((d=this.monitorDataCache[l])==null?void 0:d.length)>0});(this.streamTracks||[]).forEach(l=>{const d=l.msid;if(!d)return;let h;o.includes(d)&&(o=o.filter(p=>p!==d)),h=d===M.Audio?this.rtsManager.getPublishAudioStats(this.url):this.rtsManager.getPublishVideoStats(this.url,d),h.then(p=>{if(!p.timestamp)return;this.monitorDataCache[d]||(this.monitorDataCache[d]=[]);const u=this.getMediaStats(p.mediaSourceId);p._source=u;const f=this.monitorDataCache[d];let m;if((f==null?void 0:f.length)>0){const S=f[f.length-1]||{},b=S,{_last:v}=b;m=Mt(b,["_last"])}(f==null?void 0:f.length)>=30&&this.reportPublishMonitor(d),p._last=m,p._codec=l.codec||"",this.monitorDataCache[d].push(p)})}),o.forEach(l=>{this.reportPublishMonitor(l)})}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(te.AliRtcStatePublishIdle),this.videoPubState.setState(te.AliRtcStatePublishIdle),this.videoSmallPubState.setState(te.AliRtcStatePublishIdle),this.screenPubState.setState(te.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 V(U.ERR_INNER,"data channel publish is not enabled");if(!this.dc)throw new V(U.ERR_INNER,"data channel is not ready");const t=function(r,n){let c=0;const o=[];for(;c<r.byteLength;){const l=Math.min(n,r.byteLength-c),d=r.slice(c,c+l);o.push(d),c+=l}return o}(e.toBuffer(),1156);t.forEach((r,n)=>{const c=new zi(new vi(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:$t.AliRtcAudioTrackMic})}const t=[];if(this.hasCameraTrackInMS){const n=yield this.rtsManager.getPublishVideoStats(this.url,M.VideoLarge);n&&t.push({track:ce.AliRtcVideoTrackCamera,streamType:Ke.AliRtcVideoStreamTypeHigh,stats:n})}if(this.hasCameraDualTrackInMS){const n=yield this.rtsManager.getPublishVideoStats(this.url,M.VideoSmall);n&&t.push({track:ce.AliRtcVideoTrackCamera,streamType:Ke.AliRtcVideoStreamTypeLow,stats:n})}if(this.hasScreenTrackInMS){const n=yield this.rtsManager.getPublishVideoStats(this.url,M.Screen);n&&t.push({track:ce.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}})}markReconnect(e){const t=[],i=this.streamManager.publishStreams;!i.audio||e&&!e.includes(M.Audio)||t.push(this.audioPubState),!i.video||e&&!e.includes(M.VideoLarge)||t.push(this.videoPubState),!i.screen||e&&!e.includes(M.Screen)||t.push(this.screenPubState),!this.dc||e&&!e.includes(M.Data)||t.push(this.dataPubState),t.forEach(r=>{r.setState(te.AliRtcStateReconnecting)})}markReconnected(e){var r;const t=[],i=this.streamManager.publishStreams;if(!i.audio||e&&!e.includes(M.Audio)||t.push(this.audioPubState),!i.video||e&&!e.includes(M.VideoLarge)||t.push(this.videoPubState),!i.screen||e&&!e.includes(M.Screen)||t.push(this.screenPubState),this.dc&&(!e||e.includes(M.Data))&&(t.push(this.dataPubState),(r=this.parameter.data)==null?void 0:r.enablePubDataChannel)){const n=this.rtsManager.getDatachannelByMsid({url:this.url,msid:M.Data});this.updateDataChannel(n)}this.publishUpdate(_t.RECONNECT),t.forEach(n=>{n.setState(te.AliRtcStatePublished)})}},g(St,"logName","LocalUser"),St);Ee([C()],Re.prototype,"clearPublishState",1),Ee([C()],Re.prototype,"clear",1),Ee([C(B)],Re.prototype,"startDefaultCameraAndMic",1),Ee([C()],Re.prototype,"setViewConfig",1),Ee([C()],Re.prototype,"startCameraCapture",1),Ee([C()],Re.prototype,"stopCameraCapture",1),Ee([C()],Re.prototype,"startAudioCapture",1),Ee([C()],Re.prototype,"stopAudioCapture",1),Ee([C()],Re.prototype,"startCameraAndMic",1),Ee([C()],Re.prototype,"stopPreview",1),Ee([C()],Re.prototype,"resumePublish",1),Ee([C()],Re.prototype,"createLocalStream",1),Ee([C()],Re.prototype,"stopLocalStream",1),Ee([C()],Re.prototype,"updateDataChannel",1),Ee([C(B)],Re.prototype,"startPublish",1),Ee([C()],Re.prototype,"updateStreams",1),Ee([C(([s])=>[s])],Re.prototype,"syncPublishToRoomServer",1),Ee([C()],Re.prototype,"refreshPushStreamUrl",1),Ee([C(([s,a,e])=>[JSON.stringify(e)])],Re.prototype,"publishAdd",1),Ee([C(([s,a])=>[JSON.stringify(a)])],Re.prototype,"publishReplace",1),Ee([C(B)],Re.prototype,"publishDeleteTracks",1),Ee([C()],Re.prototype,"publishStop",1),Ee([C()],Re.prototype,"unPublish",1),Ee([C(([s,a,e])=>[s.length,a,e])],Re.prototype,"sendSEI",1),Ee([C(B)],Re.prototype,"markReconnect",1),Ee([C(B)],Re.prototype,"markReconnected",1);let Go=Re;var ht=(s=>(s.OPUS="opus",s.H264="H264",s.H265="H265",s.AV1="AV1",s.UNKNOWN="",s))(ht||{}),le=(s=>(s[s.NotSubscribe=0]="NotSubscribe",s[s.Subscribing=1]="Subscribing",s[s.Subscribed=2]="Subscribed",s))(le||{}),qt=(s=>(s.VideoTrackEnded="videoTrackEnded",s.AudioTrackEnded="audioTrackEnded",s.ScreenTrackEnded="screenTrackEnded",s))(qt||{});const sn=s=>I(this,null,function*(){return yield X.AliRTS.createStream({custom:!0,mediaStream:s})}),Ri=s=>I(this,null,function*(){const a=(e=>{const t=new MediaStream;return t.addTrack(e),t})(s);return yield sn(a)});var qo=Object.defineProperty,Xo=Object.getOwnPropertyDescriptor;class Dr extends se{constructor(){super();g(this,"audioInfo",{subscribeState:le.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:ht.UNKNOWN});g(this,"videoLargeInfo",{subscribeState:le.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:ht.UNKNOWN});g(this,"videoSmallInfo",{subscribeState:le.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:ht.UNKNOWN});g(this,"screenInfo",{subscribeState:le.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:ht.UNKNOWN});g(this,"dataInfo",{subscribeState:le.NotSubscribe,ssrc:"",msid:"",pt:0,red:0,codec:ht.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===le.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===le.Subscribed}get isAudioSubscribing(){return this.audioInfo.subscribeState===le.Subscribing}get isVideoSubscribed(){return this.isVideoLargeSubscribed||this.isVideoSmallSubscribed}get isVideoSubscribing(){return this.isVideoLargeSubscribing||this.isVideoSmallSubscribing}get isVideoLargeSubscribed(){return this.videoLargeInfo.subscribeState===le.Subscribed}get isVideoLargeSubscribing(){return this.videoLargeInfo.subscribeState===le.Subscribing}get isVideoSmallSubscribed(){return this.videoSmallInfo.subscribeState===le.Subscribed}get isVideoSmallSubscribing(){return this.videoSmallInfo.subscribeState===le.Subscribing}get isScreenSubscribed(){return this.screenInfo.subscribeState===le.Subscribed}get isScreenSubscribing(){return this.screenInfo.subscribeState===le.Subscribing}get isDataSubscribed(){return this.dataInfo.subscribeState===le.Subscribed}get isDataSubscribing(){return this.dataInfo.subscribeState===le.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:ht.UNKNOWN}get audioTrackInfo(){return this.hasAudio?$t.AliRtcAudioTrackMic:$t.AliRtcAudioTrackNo}get videoTrackInfo(){return this.hasVideo&&this.hasScreen?ce.AliRtcVideoTrackBoth:this.hasVideo?ce.AliRtcVideoTrackCamera:this.hasScreen?ce.AliRtcVideoTrackScreen:ce.AliRtcVideoTrackNo}updateTracks(e){let t="",i="",r="",n="",c="";return e?(e.forEach(o=>{var p;let l=ht.UNKNOWN;const d=((p=o==null?void 0:o.attr)==null?void 0:p.reason)==="reconnect";if(o.userdata){const{codec:u}=JSON.parse(o.userdata);u&&(l=u)}var h;(h=o.msid)===M.Audio||h===Tr.Audio?(t=o.ssrc,this.audioInfo.msid=o.msid,this.audioInfo.codec=l,(d||this.audioInfo.ssrc!==t)&&(this.audioInfo.subscribeState=le.NotSubscribe)):(u=>u===M.VideoSmall)(o.msid)?(r=o.ssrc,this.videoSmallInfo.msid=o.msid,this.videoSmallInfo.codec=l,(d||this.videoSmallInfo.ssrc!==r)&&(this.videoSmallInfo.subscribeState=le.NotSubscribe)):(u=>u===M.VideoLarge||u===Tr.VideoLarge)(o.msid)?(i=o.ssrc,this.videoLargeInfo.msid=o.msid,this.videoLargeInfo.codec=l,(d||this.videoLargeInfo.ssrc!==i)&&(this.videoLargeInfo.subscribeState=le.NotSubscribe)):(u=>u===M.Screen)(o.msid)?(n=o.ssrc,this.screenInfo.msid=o.msid,this.screenInfo.codec=l,(d||this.screenInfo.ssrc!==n)&&(this.screenInfo.subscribeState=le.NotSubscribe)):(u=>u===M.Data)(o.msid)&&(c=o.ssrc,this.dataInfo.msid=o.msid,this.dataInfo.codec=l,(d||this.dataInfo.ssrc!==c)&&(this.dataInfo.subscribeState=le.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=le.Subscribing),e.vMsid!==this.videoLargeInfo.msid&&e.vMsid||(this.videoLargeInfo.subscribeState=le.Subscribing)),e.screen&&(this.screenInfo.subscribeState=le.Subscribing),e.audio&&(this.audioInfo.subscribeState=le.Subscribing),e.data&&(this.dataInfo.subscribeState=le.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?le.Subscribed:le.NotSubscribe),e.vMsid!==this.videoLargeInfo.msid&&e.vMsid||(this.videoLargeInfo.subscribeState=e.video?le.Subscribed:le.NotSubscribe)),e.screen!==void 0&&(this.screenInfo.subscribeState=e.screen?le.Subscribed:le.NotSubscribe),e.audio!==void 0&&(this.audioInfo.subscribeState=e.audio?le.Subscribed:le.NotSubscribe),e.data!==void 0&&(this.dataInfo.subscribeState=e.data?le.Subscribed:le.NotSubscribe),{audioInfo:this.audioInfo,videoLargeInfo:this.videoLargeInfo,videoSmallInfo:this.videoSmallInfo,screenInfo:this.screenInfo,dataInfo:this.dataInfo}}updateRemoteUserDeviceStatus(e){let t=Ya.parseStatus(e);const{audioDisable:i,videoDisable:r,screenDisable:n}=t;return this.userStatus?(this.userStatus.audioDisable!=i&&(this.userStatus.audioDisable=i,this.emit(Qe.Remote,i?Ce.MuteAudio:Ce.UnmuteAudio)),this.userStatus.videoDisable!=r&&(this.userStatus.videoDisable=r,this.emit(Qe.Remote,r?Ce.MuteVideo:Ce.UnmuteVideo)),this.userStatus.screenDisable!=n&&(this.userStatus.screenDisable=n,this.emit(Qe.Remote,n?Ce.MuteScreen:Ce.UnmuteScreen))):(this.userStatus=t,this.emit(Qe.Remote,i?Ce.MuteAudio:Ce.UnmuteAudio),this.emit(Qe.Remote,r?Ce.MuteVideo:Ce.UnmuteVideo),this.emit(Qe.Remote,n?Ce.MuteScreen:Ce.UnmuteScreen)),!1}}g(Dr,"logName","RemoteStreamInfo"),((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);t&&r&&qo(a,e,r)})([C()],Dr.prototype,"updateRemoteTrackSubState",1);class an{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 Yo=Object.defineProperty,Qo=Object.getOwnPropertyDescriptor,je=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?Qo(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&&Yo(a,e,r),r};class ni extends se{constructor(){super();g(this,"state");g(this,"time");g(this,"_enabled");this.state=ae.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 He=(Ge=class extends Xa{constructor(e){var u;const{userId:t,displayName:i,rtsManager:r,usersViewMap:n,slsReporter:c,signalingManager:o,localUser:l,audioVolumeIndicationInterval:d,playoutVolume:h,parameter:p}=e;super(t,i,r,d);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",Ke.AliRtcVideoStreamTypeHigh);g(this,"audioMuted",!1);g(this,"playoutVolume",1);g(this,"playoutGainNode");g(this,"audioSubState");g(this,"videoSubState");g(this,"videoLargeSubState",new ni);g(this,"videoSmallSubState",new ni);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,"traceId","");g(this,"handleAudioContextSuspended",e=>{e.target.state==="suspended"&&this.emit("remoteAudioPlayError",this.uid,"AudioContext suspended")});g(this,"onDataChannelMessage",e=>{var r;const t=zi.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 l=0;l<this.dcMsgWaitingPieces.length;l++){const d=this.dcMsgWaitingPieces[l];new Uint8Array(c,o,d.byteLength).set(new Uint8Array(d)),o+=d.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||N.event(`[${Ge.logName}]`,`parse data channel message fail, piece count: ${this.dcMsgWaitingPieces.length+1}`)}i&&(N.event(`[${Ge.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",V.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 Dr,this.remoteUserInfo=new an(this),this.parameter=p,this.streamInfo.on(Qe.Remote,f=>{this.emit(Qe.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=l,this.audioSubState=new ni,this.audioSubState.on("change",(f,m,b)=>{this.emit("audioSubscribeStateChanged",this.uid,f,m,b)}),this.videoSubState=new ni,this.videoSubState.on("change",(f,m,b)=>{this.emit("videoSubscribeStateChanged",this.uid,f,m,b)}),this.screenSubState=new ni,this.screenSubState.on("change",(f,m,b)=>{this.emit("screenSubscribeStateChanged",this.uid,f,m,b)}),this.dataSubState=new ni,this.dataSubState.on("change",(f,m,b)=>{this.emit("dataSubscribeStateChanged",this.uid,f,m,b)}),this.playoutVolume=h}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=Gt.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(){return this.streamInfo.hasAudio}get hasVideoTrack(){return this.streamInfo.hasVideo}get hasVideoLargeTrack(){return this.streamInfo.hasVideoLarge}get hasVideoSmallTrack(){return this.streamInfo.hasVideoSmall}get hasScreenTrack(){return this.streamInfo.hasScreen}get isAudioSubscribing(){return this.streamInfo.isAudioSubscribed||this.streamInfo.isAudioSubscribing}get isVideoSubscribing(){return this.streamInfo.isVideoSubscribed||this.streamInfo.isVideoSubscribing}get isVideoLargeSubscribing(){return this.streamInfo.isVideoLargeSubscribed||this.streamInfo.isVideoLargeSubscribing}get isVideoSmallSubscribing(){return this.streamInfo.isVideoSmallSubscribed||this.streamInfo.isVideoSmallSubscribing}get isScreenSubscribing(){return this.streamInfo.isScreenSubscribed||this.streamInfo.isScreenSubscribing}get isDataSubscribing(){return this.streamInfo.isDataSubscribed||this.streamInfo.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!==ce.AliRtcVideoTrackScreen&&t!==ce.AliRtcVideoTrackCamera)throw new V(U.ERR_INVALID_ARGUMENTS,"track is not AliRtcVideoTrackScreen or AliRtcVideoTrackCamera");e?cr(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===ce.AliRtcVideoTrackScreen?this.viewMap.screenViews.push(i):this.viewMap.cameraViews.push(i),this.play(i,t===ce.AliRtcVideoTrackScreen)}):(this.stopPlayAll(t===ce.AliRtcVideoTrackScreen),t===ce.AliRtcVideoTrackScreen?this.viewMap.screenViews=[]:this.viewMap.cameraViews=[])}clear(e=!0){return I(this,null,function*(){Zr(Ge.prototype,this,"clear").call(this),this.stopPlayAudio(),this.stopStreamMonitor(),e&&this.subscribeDeleteAllTracks(this.streamUrl).catch(t=>{N.event(`[${Ge.logName}]`,`stopSubscribeAllTracks error: ${t.message||t}`)}),this.clearStream(),this.clearScreenStream(),this.playoutGainNode&&(this.playoutGainNode.disconnect(),this.playoutGainNode=void 0,Gt.getInstance().removeEventListener("statechange",this.handleAudioContextSuspended)),this.streamInfo.removeAllListeners(Qe.Remote)})}updateRemoteUserDeviceStatus(e){this.streamInfo.updateRemoteUserDeviceStatus(e)}updateRemoteTracks(e,t,i,r){return I(this,null,function*(){return this.remoteCallId=e,this.streamUrl&&this.streamInfo.hasTrack||(this.streamUrl=t),this.streamInfo.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:l,video:d,vMsid:h}=c,p=[];(d||l)&&p.push({audio:l,video:d,vMsid:h}),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;let r=new Date().getTime(),n="";try{e.audio&&this.audioSubState.setState(ae.AliRtcStateSubscribing),e.video&&(this.videoSubState.currentState!==ae.AliRtcStateSubscribeIdle&&this.videoSubState.currentState!==ae.AliRtcStateNoSubscribe||this.videoSubState.setState(ae.AliRtcStateSubscribing)),e.screen&&this.screenSubState.setState(ae.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:d}=l;if(n&&(this.traceId=n),e.audio){const u=d.audioTrack;u&&(this.audioTrack=u,(o=d.mediaStream)==null||o.removeTrack(u),this.playAudio(),this.audioVolumeIndicationInterval&&this.audioLevelMonitor.start(u,this.audioVolumeIndicationInterval)),this.audioSubState.getEnabled()||this.toggleAudio(!1),this.audioSubState.setState(ae.AliRtcStateSubscribed)}e.video&&(this.updateStream(d,this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing),this.videoSubState.getEnabled()||this.toggleVideo(!1),this.videoSubState.setState(ae.AliRtcStateSubscribed),e.vMsid===M.VideoSmall?this.videoSmallSubState.setState(ae.AliRtcStateSubscribed):this.videoLargeSubState.setState(ae.AliRtcStateSubscribed)),e.screen&&(this.updateScreenStream(d),this.videoSubState.getEnabled()||this.toggleScreen(!1),this.screenSubState.setState(ae.AliRtcStateSubscribed));const h=new Date().getTime()-r,p=Date.now();setTimeout(()=>{this.slsReporter.reportSubscribe(this.callId,this.remoteCallId,!!e.video&&e.vMsid===M.VideoLarge,!!e.video&&e.vMsid===M.VideoSmall,!!e.screen,!!e.audio,0,"",h,{pctid:this.rtsManager.pcTraceId,subtid:this.traceId,ajsub:t===be.Join?1:0,url:this.streamUrl,est:r},p)},6e3),this.startStreamMonitor(),l.isHTTP&&l.statsCheckPromise&&(yield Promise.race([l.statsCheckPromise,xt(1500)]))}catch(l){const d=new Date().getTime()-r;e.audio&&this.audioSubState.setState(ae.AliRtcStateNoSubscribe),e.video&&this.videoSubState.setState(ae.AliRtcStateNoSubscribe),e.screen&&this.screenSubState.setState(ae.AliRtcStateNoSubscribe),l&&(l.message=`user(${this.uid}) subscribe error, ${(l==null?void 0:l.message)||""}`);let h=U.ERR_INNER;e.audio&&(h=U.ERR_SDK_SUBSCRIBE_AUDIO_STREAM_FAILED),e.video&&(h=e.vMsid===M.VideoSmall?U.ERR_SDK_SUBSCRIBE_DUAL_STREAM_FAILED:U.ERR_SDK_SUBSCRIBE_VIDEO_STREAM_FAILED),e.screen&&(h=U.ERR_SDK_SUBSCRIBE_SCREEN_SHARE_FAILED),this.slsReporter.reportSubscribe(this.callId,this.remoteCallId,!!e.video&&e.vMsid===M.VideoLarge,!!e.video&&e.vMsid===M.VideoSmall,!!e.screen,!!e.audio,h,"",d,{pctid:this.rtsManager.pcTraceId,subtid:"",ajsub:t===be.Join?1:0,url:this.streamUrl,est:r});const p=V.fromError(l,h);throw this.emit("remoteSubscribeError",p),p}})}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(l=>this.subscribeDeleteProxy(l))),e.data&&this.subscribeDeleteDataChannel())})}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(ae.AliRtcStateNoSubscribe)),e.video===!0&&(r.video=!1,e.vMsid===M.VideoSmall?(this.videoSmallSubState.setState(ae.AliRtcStateNoSubscribe),this.videoLargeSubState.currentState!==ae.AliRtcStateNoSubscribe&&this.videoLargeSubState.currentState!==ae.AliRtcStateSubscribeIdle||this.videoSubState.setState(ae.AliRtcStateNoSubscribe)):(this.videoLargeSubState.setState(ae.AliRtcStateNoSubscribe),this.videoSmallSubState.currentState!==ae.AliRtcStateNoSubscribe&&this.videoSmallSubState.currentState!==ae.AliRtcStateSubscribeIdle||this.videoSubState.setState(ae.AliRtcStateNoSubscribe))),e.screen===!0&&(r.screen=!1,this.screenSubState.setState(ae.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 V.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=Gt.getInstance();return e.state!=="running"&&e.resume(),this.audioElement?this.audioElement.play():this.playAudio()})}resumeVideo(e){return I(this,null,function*(){return e&&e!==ce.AliRtcVideoTrackCamera&&e!==ce.AliRtcVideoTrackBoth?e&&e!==ce.AliRtcVideoTrackScreen&&e!==ce.AliRtcVideoTrackBoth?void 0:this.playAll(!0):this.playAll()})}resumePlay(){this.playAudio(),this.playAll(),this.playAll(!0)}stopSubscribe(e){return I(this,null,function*(){let t=new Date().getTime();try{e?yield this.subscribeDeleteTracks(e):yield this.subscribeDeleteAllTracks(this.streamUrl),this.slsReporter.reportUnsubscribe(this.callId,this.remoteCallId,new Date().getTime()-t,0,"")}catch(i){throw this.slsReporter.reportUnsubscribe(this.callId,this.remoteCallId,new Date().getTime()-t,0,""),i}})}subscribeDeleteAllTracks(e){return I(this,null,function*(){var r,n,c,o;const{callId:t,remoteCallId:i}=this;if((this.isAudioSubscribing||this.isVideoSubscribing||this.isScreenSubscribing||this.dc)&&e)try{yield this.subscribeDeleteTracks({audio:this.isAudioSubscribing,video:this.isVideoSubscribing,screen:this.isScreenSubscribing,data:!!this.dc}),this.restore();const l={callid:t,remoteCallid:i,remoteStream:this.stream};return this.callId="",l}catch(l){if(((o=(c=(n=(r=l==null?void 0:l.extraInfo)==null?void 0:r.parsedData)==null?void 0:n.streams)==null?void 0:c[0])==null?void 0:o.res_code)!==404)throw V.fromError(l,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=()=>{N.event(`[${Ge.logName}]`,`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(()=>{N.event(`[${Ge.logName}]`,`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.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(ae.AliRtcStateSubscribing),this.rtsManager.subscribeAddDataChannel(this.streamUrl).then(e=>{if(e)return this.dataChannelConnected(e),this.dataSubState.setState(ae.AliRtcStateSubscribed),void this.streamInfo.updateRemoteTrackSubState({data:!0});throw new Error("no dc founded")}).catch(e=>{const t=V.fromError(e,U.ERR_INNER,"subscribe data failed");this.emit("remoteSubscribeError",t),this.dataSubState.setState(ae.AliRtcStateNoSubscribe)}))}subscribeDeleteDataChannel(){if(this.dc){try{this.rtsManager.subscribeDeleteDatachannel(this.streamUrl,this.dc)}catch(e){}this.dcMsgWaitingPieces=[],this.dc.off("message",this.onDataChannelMessage),this.dc.off("error",this.onDataChannelError),this.dataSubState.setState(ae.AliRtcStateNoSubscribe),this.dc=void 0,this.streamInfo.updateRemoteTrackSubState({data:!1})}}getRetryOptions(){var i,r;const e={};this.wantSubAudio&&this.streamInfo.hasAudio&&(e.audio=!0,e.aMsid=((i=this.streamInfo.getAudioInfo())==null?void 0:i.msid)||M.Audio),this.wantSubVideo&&this.streamInfo.hasVideo&&(this.defaultVideoStreamType===Ke.AliRtcVideoStreamTypeLow&&this.streamInfo.hasVideoSmall?(e.video=!0,e.vMsid=M.VideoSmall):this.streamInfo.hasVideoLarge&&(e.video=!0,e.vMsid=((r=this.streamInfo.getVideoLargeInfo())==null?void 0:r.msid)||M.VideoLarge)),this.wantSubScreen&&this.streamInfo.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,l,d,h;const t=Date.now(),i={},r={};return this.wantSubAudio&&!this.isAudioSubscribing&&this.streamInfo.hasAudio&&this.audioSubState.currentState!==ae.AliRtcStateReconnecting?(i.audio=!0,i.aMsid=((n=this.streamInfo.getAudioInfo())==null?void 0:n.msid)||M.Audio):this.wantSubAudio&&this.streamInfo.hasAudio||!this.isAudioSubscribing||(r.audio=!0,r.aMsid=((c=this.streamInfo.getAudioInfo())==null?void 0:c.msid)||M.Audio),this.wantSubVideo&&this.streamInfo.hasVideo?(this.defaultVideoStreamType===Ke.AliRtcVideoStreamTypeLow&&!this.isVideoSmallSubscribing&&this.streamInfo.hasVideoSmall&&this.videoSmallSubState.currentState!==ae.AliRtcStateReconnecting?(i.video=!0,i.vMsid=M.VideoSmall):this.isVideoLargeSubscribing||!this.streamInfo.hasVideoLarge||this.defaultVideoStreamType===Ke.AliRtcVideoStreamTypeLow&&this.isVideoSmallSubscribing||this.videoLargeSubState.currentState===ae.AliRtcStateReconnecting||(i.video=!0,i.vMsid=((o=this.streamInfo.getVideoLargeInfo())==null?void 0:o.msid)||M.VideoLarge),this.defaultVideoStreamType===Ke.AliRtcVideoStreamTypeLow&&this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing&&this.streamInfo.hasVideoSmall?(r.video=!0,r.vMsid=M.VideoLarge):this.defaultVideoStreamType===Ke.AliRtcVideoStreamTypeHigh&&this.isVideoLargeSubscribing&&this.isVideoSmallSubscribing&&(r.video=!0,r.vMsid=M.VideoSmall)):this.wantSubVideo&&this.streamInfo.hasVideo||!this.isVideoSubscribing||(r.video=!0,r.vMsid=this.streamInfo.isVideoSmallSubscribed||this.streamInfo.isVideoSmallSubscribing?M.VideoSmall:((l=this.streamInfo.getVideoLargeInfo())==null?void 0:l.msid)||M.VideoLarge),this.wantSubScreen&&!this.isScreenSubscribing&&this.streamInfo.hasScreen&&this.screenSubState.currentState!==ae.AliRtcStateReconnecting?i.screen=!0:this.wantSubScreen&&this.streamInfo.hasScreen||!this.isScreenSubscribing||(r.screen=!0),(d=this.parameter.data)!=null&&d.enableSubDataChannel&&!this.isDataSubscribing&&this.streamInfo.hasData&&this.dataSubState.currentState!==ae.AliRtcStateReconnecting?i.data=!0:(h=this.parameter.data)!=null&&h.enableSubDataChannel&&this.streamInfo.hasData||!this.isDataSubscribing||(r.data=!0),this.dc&&i.data&&this.subscribeDeleteDataChannel(),(i.audio||i.video||i.screen||i.data)&&(this.createCallId(),this.subscribe(i,e,t)),(r.audio||r.video||r.screen)&&this.subscribeDeleteTracks(r),{addOption:i,deleteOption:r}}handleAutoPlayFailed(){N.event(`[${Ge.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===ce.AliRtcVideoTrackScreen?this.screenStream:this.stream)==null?void 0:n.mediaStream;e.srcObject===r&&this.play(e,t===ce.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||(N.event(`[${Ge.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){N.event(`[${Ge.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;N.event(`[${Ge.logName}]`,"try play audio"),(i=this.audioElement)==null||i.play().then(()=>{N.event(`[${Ge.logName}]`,"play audio success")}).catch(()=>{this.handleAutoPlayFailed()})})()}else N.event(`[${Ge.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&&tn(e,r.mediaStream,i).catch(n=>{n.code!==20&&n.name!=="AbortError"&&this.handleVideoPlayFailded(e,t?ce.AliRtcVideoTrackScreen:ce.AliRtcVideoTrackCamera)})}stopPlayAll(e=!1){e?this.viewMap.screenViews.forEach(t=>{wt(t)}):this.viewMap.cameraViews.forEach(t=>{wt(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;const e=[];if(this.isAudioSubscribing){const c=yield this.rtsManager.getSubscribeAudioStats(this.streamUrl);c&&e.push({uid:this.uid,track:$t.AliRtcAudioTrackMic,stats:c})}const t=[];if(this.streamInfo.isVideoLargeSubscribed){const c=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,((i=this.streamInfo.getVideoLargeInfo())==null?void 0:i.msid)||M.VideoLarge);c&&t.push({uid:this.uid,track:ce.AliRtcVideoTrackCamera,streamType:Ke.AliRtcVideoStreamTypeHigh,stats:c})}if(this.streamInfo.isVideoSmallSubscribed){const c=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,((r=this.streamInfo.getVideoSmallInfo())==null?void 0:r.msid)||M.VideoSmall);c&&t.push({uid:this.uid,track:ce.AliRtcVideoTrackCamera,streamType:Ke.AliRtcVideoStreamTypeLow,stats:c})}if(this.isScreenSubscribing){const c=yield this.rtsManager.getSubscribeVideoStats(this.streamUrl,((n=this.streamInfo.getScreenInfo())==null?void 0:n.msid)||M.Screen);c&&t.push({uid:this.uid,track:ce.AliRtcVideoTrackScreen,stats:c})}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){e&&(this.slsReporter.reportSubscribeMonitor(this.callId,this.remoteCallId,this.traceId,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 h;if(!c.timestamp)return;this.monitorDataCache[i]||(this.monitorDataCache[i]=[]);const o=this.monitorDataCache[i];let l;if((o==null?void 0:o.length)>0){const p=o[o.length-1]||{},d=p,{_last:u}=d;l=Mt(d,["_last"])}(o==null?void 0:o.length)>=30&&this.reportSubscribeMonitor(i),c._last=l,c._codec=t.codec,n&&(c._source=(h=this.localUser)==null?void 0:h.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)})}markReconnect(e){const t=[];!this.isAudioSubscribing||e&&!e.includes(this.streamInfo.getAudioInfo().msid)||t.push(this.audioSubState),this.isVideoSubscribing&&(!e||e.includes(this.streamInfo.getVideoLargeInfo().msid)||e.includes(this.streamInfo.getVideoSmallInfo().msid))&&t.push(this.videoSubState),!this.isScreenSubscribing||e&&!e.includes(this.streamInfo.getScreenInfo().msid)||t.push(this.screenSubState),!this.isDataSubscribing||e&&!e.includes(M.Data)||t.push(this.dataSubState),t.forEach(i=>{i.setState(ae.AliRtcStateReconnecting)})}markReconnected(e){const t=[],i=this.streamInfo.getAudioInfo().msid||M.Audio;if(this.isAudioSubscribing&&(!e||e.includes(i))){t.push(this.audioSubState);const o=this.rtsManager.getStreamByMsid({url:this.streamUrl,aMsid:i});o&&o.audioTrack&&(this.audioTrack=o.audioTrack,this.audioVolumeIndicationInterval>0&&(this.audioLevelMonitor.stop(),this.audioLevelMonitor.start(this.audioTrack,this.audioVolumeIndicationInterval)),this.playAudio())}const r=this.streamInfo.getVideoLargeInfo().msid||M.VideoLarge,n=this.streamInfo.getVideoSmallInfo().msid||M.VideoSmall;if(this.isVideoSubscribing&&(!e||e.includes(r)||e.includes(n))){t.push(this.videoSubState);const o=this.rtsManager.getStreamByMsid({url:this.streamUrl,vMsid:this.streamInfo.isVideoSmallSubscribed||this.streamInfo.isVideoSmallSubscribing?n:r});o&&o.mediaStream&&(this.stream=o,this.playAll(!1))}const c=this.streamInfo.getScreenInfo().msid||M.Screen;if(this.isScreenSubscribing&&(!e||e.includes(c))){t.push(this.screenSubState);const o=this.rtsManager.getStreamByMsid({url:this.streamUrl,vMsid:c});o&&o.mediaStream&&(this.screenStream=o,this.playAll(!0))}if(this.isDataSubscribing&&(!e||e.includes(this.streamInfo.getDataInfo().msid))){t.push(this.dataSubState);const o=this.rtsManager.getDatachannelByMsid({url:this.streamUrl,msid:this.streamInfo.getDataInfo().msid||M.Data});this.dataChannelConnected(o)}t.forEach(o=>{o.setState(ae.AliRtcStateSubscribed)}),e||this.updateSubscribe(be.Reconnect)}},g(Ge,"logName","RemoteUser"),Ge);je([C()],He.prototype,"clear",1),je([C()],He.prototype,"updateRemoteUserDeviceStatus",1),je([C()],He.prototype,"updateRemoteTracks",1),je([C(B)],He.prototype,"subscribe",1),je([C()],He.prototype,"subscribeProxy",1),je([C(B)],He.prototype,"subscribeDeleteProxy",1),je([C()],He.prototype,"restore",1),je([C(B)],He.prototype,"resumeAudio",1),je([C(B)],He.prototype,"stopSubscribe",1),je([C(B)],He.prototype,"subscribeDeleteAllTracks",1),je([C()],He.prototype,"clearStream",1),je([C()],He.prototype,"clearScreenStream",1),je([C()],He.prototype,"updateSubscribe",1),je([C()],He.prototype,"playAudio",1),je([C()],He.prototype,"stopPlayAudio",1),je([C((s,a,e)=>[typeof s=="string"?s:s==null?void 0:s.nodeType,a||"-",e||"-"])],He.prototype,"play",1),je([C()],He.prototype,"stopPlayAll",1),je([C(B)],He.prototype,"markReconnect",1),je([C(B)],He.prototype,"markReconnected",1);let Zo=He;var Ut=(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))(Ut||{});class ec extends se{constructor(){super(...arguments);g(this,"plugins",new Map)}add(e,t){if(this.plugins.has(e.name))throw new V(Ut.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 V(Ut.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 tc=Object.defineProperty,ic=Object.getOwnPropertyDescriptor,ze=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?ic(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&&tc(a,e,r),r};const Wi=([s])=>{const{remoteUser:a,options:e}=s;return[`user(${a.userId})`,e]},Fe=(Te=class extends se{constructor(e,t,i){var r,n;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");g(this,"traceIdMap",{});this.localStreamManager=e,this.slsReporter=t,this.parameter=i,this.rts=X.AliRTS.createClient({singlePcConfig:{usePcReconnect:!0},datachannelDelayOpen:!0,signalDatachannelInitOptions:(r=i==null?void 0:i.net)!=null&&r.datachannelInitOptions?(n=i==null?void 0:i.net)==null?void 0:n.datachannelInitOptions:void 0}),this.addRTSListener()}addRTSListener(){this.rts.on("connectStatusChange",e=>{var t,i,r,n;if(N.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;N.event(`[${Te.logName}]`,"dcReadyState:",c),c==="open"&&this.dcResolve&&this.dcResolve(!0)}this.rtsDisconnected=!1,this.setConnected(!0)}}),this.rts.on("reconnect",e=>{var t,i,r;N.debug(`[${Te.logName}]`,"reconnect",e),this.emit("reconnect",e.type,(t=e.extraInfo)==null?void 0:t.url,(r=(i=e.extraInfo)==null?void 0:i.msids)==null?void 0:r.map(n=>n.name))}),this.rts.on("reconnectFinish",e=>{var t;N.debug(`[${Te.logName}]`,"reconnectFinish",e),this.emit("reconnectFinish",(e==null?void 0:e.type)||"pc",e==null?void 0:e.latestUrl,(t=e==null?void 0:e.msids)==null?void 0:t.map(i=>i.name));try{this.emit("connected",!0,this._rtsPeerConnectionType)}catch(i){N.error(`[${Te.logName}]`,"emit connected error:",i)}}),this.rts.on("datachannelStatusChange",e=>{N.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=>{N.event(`[${Te.logName}]`,"rts onError event:",e)}),this.rts.on("reconnect",e=>{N.event(`[${Te.logName}]`,"rts reconnect event:",e)}),this.rts.on("traceId",({url:e,traceId:t})=>{e&&t&&this.traceIdMap[e]!==t&&(this.traceIdMap[e]=t,this.emit("traceIdUpdated",e,t))})}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===ht.H265?(t=RTCRtpSender.getCapabilities("video"))==null?void 0:t.codecs.some(n=>n.mimeType==="video/H265"):e===ht.H264?(i=RTCRtpSender.getCapabilities("video"))==null?void 0:i.codecs.some(n=>n.mimeType==="video/H264"):e===ht.AV1&&((r=RTCRtpSender.getCapabilities("video"))==null?void 0:r.codecs.some(n=>n.mimeType==="video/AV1"))}changeVideoCodec(e){this.supportVideoCodec(e)?(N.info(`[${Te.logName}]`,"changeVideoCodec to:",e),ht.H265===e&&(this.setSenderPreferredVideoCodecH265(),this.setReceiverPreferredVideoCodecH265())):N.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(r){return I(this,arguments,function*(e,t=!1,i=_t.MANUAL){let n;const c=Date.now(),o=e.url,l=e.callId;this.startConnect();const{publishStream:d,videoSmallStream:h,screenStream:p,vMsid:u}=yield this.localStreamManager.createHTTPPublishStream();if(!d)return N.warn(`[${Te.logName}]`,"publishStream is null"),{traceId:"",l1ip:n};const f=this.getPubMsid(d,{vMsid:u});f.answerSdpHook=w=>{const y=/\d+\.\d+\.\d+\.\d+(?=\s+1106|\s+8000)/.exec(w);return y!=null&&y[0]&&(n=y[0]),w},this.handleHTTPConfig(f),this._rtsPeerConnectionType="publish";let m=!d.hasVideo,b=u,S="";const v=Date.now();try{S=yield this.rts.publish(lr(o,this.preferredPubL1Ip),d,f)}catch(w){this.setConnected(!1);const y=2e3-(Date.now()-v);throw y<=0?this.emit("disconnected"):setTimeout(()=>{this.emit("disconnected")},y),this.slsReporter.reportPublish(t,o,l,d.hasVideo&&(!u||u===M.VideoLarge),d.hasVideo&&u===M.VideoSmall,d.hasVideo&&u===M.Screen,d.hasAudio,(w==null?void 0:w.errorCode)||-1,this.pcTraceId,"",v,v),V.fromRtsError(w)}S&&(this._pcTraceId=S),N.event(`[${Te.logName}]`,"rts publish success",S);const R=Date.now();setTimeout(()=>{this.slsReporter.reportPublish(t,o,l,d.hasVideo&&(!u||u===M.VideoLarge),d.hasVideo&&u===M.VideoSmall,d.hasVideo&&u===M.Screen,d.hasAudio,0,this.pcTraceId,e.traceId,v,R)},6e3),this.slsReporter.reportConnectionLatencyEvent(ot.HANDLE_PUB_TASK,dt.START,l,S,c),this.slsReporter.reportConnectionLatencyEvent(ot.HANDLE_PUB_TASK,dt.END,l,S,Date.now());try{const w=Date.now();return this._pcTraceId=S,this.setConnected(!0),this._publishingTracks=this.rts.getPublishTrackInfoList(),h&&(yield this.publishAdd(e,h,{vMsid:M.VideoSmall},t),m=!1,b=M.VideoSmall),p&&(yield this.publishAdd(e,p,{vMsid:M.Screen},t),m=!1,b=M.Screen),yield this.waitPublishSender(o,m,b),this.slsReporter.reportPublishFirstPacket(t,l,v,w,this._localJoinTime,m?M.Audio:f.vMsid,S||"",S||"",i),{traceId:S,l1ip:n}}catch(w){throw this.setConnected(!1),V.fromError(w)}})}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(l=>!(l.bytesSent>0)&&c<r?(c++,new Promise(d=>setTimeout(()=>d(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(o,l,d){return I(this,arguments,function*(e,t,i,r=!1,n=!1,c=_t.MANUAL){var m,b,S,v;const h=e.url,p=e.callId;yield this.dcConnectingPromise;const u=Date.now(),f=this.getPubMsid(t,i);try{const R=yield ma(w=>I(this,null,function*(){return w>0&&N.event(`[${Te.logName}]`,`publishAdd retry times: ${w}`),this.isConnected?(yield this.dcConnectingPromise,this.rts.publishAdd([G({url:h,stream:t,updateSourceStream:!1},f)])):Promise.reject(new V(U.ERR_INNER,"rts not connected"))}),10,0,w=>(w==null?void 0:w.errorCode)===15006);if(R){const w=Date.now(),[y]=R,A=Date.now();return setTimeout(()=>{var _,E,T,k;this.slsReporter.reportPublish(!1,h,p,((_=f.vMsid)==null?void 0:_[0])===M.VideoLarge,((E=f.vMsid)==null?void 0:E[0])===M.VideoSmall,((T=f.vMsid)==null?void 0:T[0])===M.Screen,((k=f.aMsid)==null?void 0:k[0])===M.Audio,0,this.pcTraceId,y.traceId||"",u,A)},6e3),y.traceId&&(this._pcTraceId=y.traceId),this.updatePublishingTracks(y.trackInfoList),n&&(yield this.waitPublishSender(h,!t.hasVideo,t.hasVideo?i==null?void 0:i.vMsid:i==null?void 0:i.aMsid)),this.slsReporter.reportPublishFirstPacket(r,p,u,w,this._localJoinTime,(t.hasVideo?i==null?void 0:i.vMsid:i==null?void 0:i.aMsid)||"",this.pcTraceId,y.traceId||"",c),y.traceId||""}}catch(R){throw this.slsReporter.reportPublish(!1,h,p,((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,(R==null?void 0:R.errorCode)||-1,this.pcTraceId,"",u),R!=null&&R.errorCode?V.fromRtsError(R):V.fromError(R)}return""})}publishDelete(e,t){return I(this,null,function*(){var l,d,h,p,u,f,m,b;yield this.dcConnectingPromise;const i=(d=(l=this.publishingTracks)==null?void 0:l.find(({msid:S})=>S===M.Audio))==null?void 0:d.msid,r=(p=(h=this.publishingTracks)==null?void 0:h.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),N.event(Te.logName,"publishDelete",{streamUrl:e,aMsid:o,vMsid:c});try{const[S]=(yield this.rts.publishDeleteTracks([{url:e,aMsid:o,vMsid:c}]))||[];return N.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 V.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 l=yield this.rts.publishReplaceTracks([{url:e,stream:t,vMsid:r,aMsid:n}]),[d]=l;return this.updatePublishingTracks(d.trackInfoList),((o=(c=d==null?void 0:d.trackInfoList)==null?void 0:c[0])==null?void 0:o.trackId)||""}catch(l){throw V.fromRtsError(l)}})}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:lr(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,l,d,h,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),(d=(l=this.parameter)==null?void 0:l.net)==null?void 0:d.mediaTimeout){const u=(p=(h=this.parameter)==null?void 0:h.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=l=>{const d=l.replace(/(a=rtpmap:(\d+).*\r\n)/g,`$1a=rtcp-fb:$2 rrtr\r
|
|
130
130
|
`);return d.includes(`a=rtcp-rsize\r
|
|
131
131
|
`)?d:d.replace(/(m=(video|audio).*\r\n)/g,`$1a=rtcp-rsize\r
|
|
132
|
-
`)});try{this.startConnect();const l=yield this.rts.subscribe(lr(r,this.preferredSubL1Ip),n);return this._pcTraceId=l.traceId,this.setConnected(!0),{traceId:l.traceId,stream:l}}catch(l){throw this.setConnected(!1),this.emit("disconnected"),V.fromRtsError(l)}})}subscribeAdd(e){return I(this,null,function*(){var n,c,o,l;const{remoteUser:t,options:i}=e,r=yt(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 ma(d=>I(this,null,function*(){return yield this.dcConnectingPromise,d>0&&N.event(`[${Te.logName}]`,`subscribeAdd retry times: ${d}`),this.isConnected?this.rts.subscribeAdd([r]):Promise.reject()}),10,100,d=>{var h,p,u,f;return(d==null?void 0:d.errorCode)===15006||(d==null?void 0:d.errorCode)===15004&&((f=(u=(p=(h=d.extraInfo)==null?void 0:h.parsedData)==null?void 0:p.streams)==null?void 0:u[0])==null?void 0:f.res_code)===404}))[0]}catch(d){if(((l=(o=(c=(n=d==null?void 0:d.extraInfo)==null?void 0:n.parsedData)==null?void 0:c.streams)==null?void 0:o[0])==null?void 0:l.res_code)===508)return this.emit("subscribeexceeds"),null;throw V.fromRtsError(d)}})}subscribeDelete(e){return I(this,null,function*(){var n,c,o,l;const{remoteUser:t,options:i}=e,r=yt(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 N.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(d){if(((l=(o=(c=(n=d==null?void 0:d.extraInfo)==null?void 0:n.parsedData)==null?void 0:c.streams)==null?void 0:o[0])==null?void 0:l.res_code)===404)return;throw V.fromRtsError(d)}})}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})}subscribeDeleteDatachannel(e,t){return I(this,null,function*(){let i;try{i=yield this.rts.subscribeDeleteDatachannel({url:e,msid:M.Data,datachannel:t})}catch(r){}return i})}publish(r){return I(this,arguments,function*(e,t=!1,i=_t.MANUAL){const n=e.url;let c,o="";if(this.connecting&&(yield this.connectingPromise),this.connected){yield this.dcConnectingPromise;let l,d=!1;const{audio:h,video:p,videoSmall:u,screen:f}=this.localStreamManager.publishStreams;h&&(o=yield this.publishAdd(e,h,{aMsid:M.Audio},t),d=!0,l=M.Audio,yield xt(100)),p&&(o=yield this.publishAdd(e,p,{vMsid:M.VideoLarge},t),d=!1,l=M.VideoLarge,yield xt(100)),u&&(o=yield this.publishAdd(e,u,{vMsid:M.VideoSmall},t),d=!1,l=M.VideoSmall,yield xt(100)),f&&(o=yield this.publishAdd(e,f,{isScreen:!0,vMsid:M.Screen},t),d=!1,l=M.Screen),l&&(yield this.waitPublishSender(n,d,l))}else{const l=yield this.httpPublish(e,t,i);o=l.traceId,c=l.l1ip}return{traceId:o,l1ip:c}})}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,dt.START,t,c,i,0,r),this.slsReporter.reportConnectionLatencyEvent(ot.HANDLE_SUB_TASK,dt.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:l}=e;if(o.video&&o.screen)throw new V(U.ERR_INNER,"subscribe error, video and screen cannot be subscribed at the same time");let d;this.connecting&&(yield this.connectingPromise);let h=Date.now();this.connected?d=yield this.subscribeAdd(e):(c=!0,d=yield this.httpSubscribe(e)),this.reportSubscribeLatency(o,i,h,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 R=((w,y)=>{let A=0;const _=()=>{let E;return m&&!b&&(E=this.rts.getSubscribeAudioStats(l.streamUrl).then(T=>{if(T.packetsReceived>0)b=Date.now(),N.debug(`[${Te.logName}]`,l.userId,"Stats 音频首包");else if(!f)return A<w&&(A++,new Promise(k=>setTimeout(()=>k(_()),y)));return!0})),f&&!v&&(E=this.rts.getSubscribeVideoStats(l.streamUrl,u).then(T=>(!S&&T.packetsReceived>0&&(S=Date.now(),N.debug(`[${Te.logName}]`,l.userId,"Stats 视频首包")),T.framesDecoded>0?(v=Date.now(),N.debug(`[${Te.logName}]`,l.userId,"Stats 视频首帧数据"),!0):A<w?(A++,new Promise(k=>setTimeout(()=>k(_()),y))):(N.event(`[${Te.logName}]`,l.userId,"尝试获取首帧数据失败"),!1)))),Promise.resolve(E)};return _()})(20,100);return R.then(()=>{S&&this.slsReporter.reportSubscribeFirstPacket(t===be.Resume,i,r,u,{fprt:S-h,ifsprtc:v?v-h:0,ajsub:t===be.Join?1:0,pctid:this.pcTraceId,subtid:(d==null?void 0:d.traceId)||"",sstc:p-h}),v&&this.slsReporter.reportSubscribeFirstFrame(t===be.Resume,i,r,u,{fvfrt:v-h,fp2fftc:v-S,ajsub:t===be.Join?1:0,tffrtc:t===be.Join?v-this.localJoinTime:v-n,pctid:this.pcTraceId,subtid:(d==null?void 0:d.traceId)||"",fvfdtc:v-h}),b&&(this.slsReporter.reportConnectionLatencyEvent(ot.FIRST_REMOTE,dt.DECODED,i,M.Audio,b),this.slsReporter.reportSubscribeFirstPacket(t===be.Resume,i,r,M.Audio,{fprt:b-h,ifsprtc:b-h,ajsub:t===be.Join?1:0,pctid:this.pcTraceId,subtid:(d==null?void 0:d.traceId)||"",sstc:p-h}))}),d&&(d.isHTTP=c,d.statsCheckPromise=R),d})}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){var t;return(t=this.rts.commonController.datachannelManager)==null?void 0:t.getByMsid(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);ze([C(B)],Fe.prototype,"startConnect",1),ze([C()],Fe.prototype,"updatePublishingTracks",1),ze([C(B,B)],Fe.prototype,"httpPublish",1),ze([C(B,B)],Fe.prototype,"waitPublishSender",1),ze([C(([s,a,e])=>[s,JSON.stringify(e)],B)],Fe.prototype,"publishAdd",1),ze([C(B,B)],Fe.prototype,"publishDelete",1),ze([C(([s,a,e])=>[s,JSON.stringify(e)])],Fe.prototype,"publishReplace",1),ze([C(B)],Fe.prototype,"publishStop",1),ze([C(B)],Fe.prototype,"publishAddDataChannel",1),ze([C(B)],Fe.prototype,"publishStopDataChannel",1),ze([C()],Fe.prototype,"unpublish",1),ze([C(Wi,({traceId:s})=>s)],Fe.prototype,"httpSubscribe",1),ze([C(Wi,({traceId:s})=>s)],Fe.prototype,"subscribeAdd",1),ze([C(Wi)],Fe.prototype,"subscribeDelete",1),ze([C(B)],Fe.prototype,"subscribeAddDataChannel",1),ze([C(B)],Fe.prototype,"subscribeDeleteDatachannel",1),ze([C(B)],Fe.prototype,"publish",1),ze([C(Wi)],Fe.prototype,"subscribe",1),ze([C()],Fe.prototype,"sendSEI",1);let rc=Fe;class Mr{constructor(a=Cr){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 Oe=(s=>(s[s.AliRtcSdkStreamTypeCapture=0]="AliRtcSdkStreamTypeCapture",s[s.AliRtcSdkStreamTypeScreen=1]="AliRtcSdkStreamTypeScreen",s))(Oe||{});class Lr 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,l,d,h,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===Oe.AliRtcSdkStreamTypeScreen?this.stop():(r&&((l=this.originVideoTrack)==null||l.stop()),n&&((d=this.originAudioTrack)==null||d.stop())),r&&(this.originVideoTrack=r,(h=this.originVideoTrack)==null||h.addEventListener("ended",this.onVideoTrackEnded),this.videoSource=t||Si.Camera,this.updateVideoTrack(r)),n&&(this.originAudioTrack=n,(p=this.originAudioTrack)==null||p.addEventListener("ended",this.onAudioTrackEnded),this.audioSource=i||Bi.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,l,d,h,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 Ri(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 Ri(this._targetVideoTrack)):(this._publishVideoStream=void 0,(o=this.previewStream)==null||o.deleteTracks({video:!0})),this._targetDualVideoTrack?((d=(l=this._publishDualVideoStream)==null?void 0:l.videoTrack)==null?void 0:d.id)!==this._targetDualVideoTrack.id&&(this._publishDualVideoStream=yield Ri(this._targetDualVideoTrack),this._videoMuted?this._publishDualVideoStream.disableVideo():this._publishDualVideoStream.enableVideo()):this._publishDualVideoStream=void 0,this._targetAudioTrack?((p=(h=this._publishAudioStream)==null?void 0:h.audioTrack)==null?void 0:p.id)!==this._targetAudioTrack.id&&(this._publishAudioStream=yield Ri(this._targetAudioTrack),this.setAudioMuted(this._audioMuted),this.previewStream?(u=this.previewStream)==null||u.mergeStream(this._publishAudioStream):this._previewStream=yield Ri(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 Mr(this.type===Oe.AliRtcSdkStreamTypeScreen?en:Cr)),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 Mr(this.type===Oe.AliRtcSdkStreamTypeScreen?en:Cr)),this._profileManager.setContentHint(this.currentVideoTrack,e)}updateAudioProfile(e){return I(this,null,function*(){this._profileManager||(this._profileManager=new Mr),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 sc=Object.defineProperty,ac=Object.getOwnPropertyDescriptor,ft=(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&&sc(a,e,r),r};const ut=(Ht=class extends se{constructor(e,t){super();g(this,"pluginManager");g(this,"slsReporter");g(this,"publishingCameraVideoStream");g(this,"publishingScreenVideoStream");g(this,"cameraStreamInfo",new Lr(Oe.AliRtcSdkStreamTypeCapture));g(this,"screenStreamInfo",new Lr(Oe.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",qt.VideoTrackEnded)})),this.cameraStreamInfo.on("audiotrackended",()=>I(this,null,function*(){yield this.stopLocalStream({audio:!0}),this.emit("trackended",qt.AudioTrackEnded)})),this.screenStreamInfo.on("videotrackended",()=>I(this,null,function*(){yield this.stopLocalStream({screen:!0}),this.emit("trackended",qt.ScreenTrackEnded)})),this.pluginManager.on("added",i=>I(this,null,function*(){if(N.info(`[${Ht.logName}]`,"plugin added",i.name),!i.isSupported("7.2.0"))return console.warn(`${i.name} is not supported!!!`),void i.emit("unsupported");try{yield i.init()}catch(r){i.emit("error",V.fromError(r,Ut.AliRtcPluginErrorInitError))}i.streamType===Oe.AliRtcSdkStreamTypeCapture&&(this.cameraStreamInfo.addPlugin(i),yield this.cameraStreamInfo.process(this.streamInfos)),i.streamType===Oe.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 h;const{screen:t,mediaStream:i,videoProfile:r,screenProfile:n}=e;let{video:c,audio:o}=e;const l=(p=>{const{audio:u,video:f,screen:m}=p;if(f&&m)throw new V(U.ERR_INNER,"create stream error, cannot create video && screen together");return!!(f||u||m)})(e);let d;if(l){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{d=yield X.AliRTS.createStream({audio:o,video:c,screen:t,custom:!!i,mediaStream:i,skipProfile:!0}),N.info(`[${Ht.logName}]`,"createLocalStream",{audio:o,video:c,screen:t,custom:!!i,time:Date.now()-p}),o&&!i&&this.slsReporter.reportAudio(null,Date.now()-p,((h=d==null?void 0:d.audioTrack)==null?void 0:h.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(d,Si.Screen,Bi.Screen),yield this.setScreenProfile(n||Za),this.setScreenContentHint(),this.publishingScreenVideoStream=void 0;else if(yield this.cameraStreamInfo.updateSource(d,Si.Camera,Bi.Microphone),d.hasVideo&&(yield this.setVideoProfile(r||Qa),this.setVideoContentHint(),this.publishingCameraVideoStream=void 0),d.hasAudio&&typeof o=="boolean"){const u=this.cameraStreamInfo.audioProfile;u&&(yield d.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(),d})}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,l,d,h;let e,t,i,r,n=!1;const c=this.publishStreams;try{if(!(c.audio||c.video||c.videoSmall||c.screen))throw N.error(`[${Ht.logName}]`,"no tracks founded"),new V(U.ERR_SDK_PUBLISH_INVAILD,"no tracks founded");const p=new MediaStream;(o=c.audio)!=null&&o.audioTrack&&p.addTrack(c.audio.audioTrack),(l=c.video)!=null&&l.videoTrack?(p.addTrack(c.video.videoTrack),i=c.videoSmall,r=c.screen):(d=c.screen)!=null&&d.videoTrack&&(t=M.Screen,p.addTrack((h=c.screen)==null?void 0:h.videoTrack),n=!0),e=yield sn(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(Ht,"logName","LocalStreamManager"),Ht);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(B)],ut.prototype,"stopLocalStream",1),ft([C()],ut.prototype,"createHTTPPublishStream",1),ft([C()],ut.prototype,"stop",1),ft([C(B)],ut.prototype,"setVideoProfile",1),ft([C(B)],ut.prototype,"setVideoContentHint",1),ft([C(B)],ut.prototype,"setAudioProfile",1),ft([C(B)],ut.prototype,"setScreenProfile",1),ft([C(B)],ut.prototype,"setScreenContentHint",1),ft([C(B)],ut.prototype,"setCameraVideoConstraints",1),ft([C(B)],ut.prototype,"setMicAudioConstraints",1);let nc=ut;const oc=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 nn=(s=>(s[s.PRE_PROCESSOR=0]="PRE_PROCESSOR",s[s.POST_PROCESSOR=1]="POST_PROCESSOR",s))(nn||{}),oi=(s=>(s[s.AUDIO=0]="AUDIO",s[s.VIDEO=1]="VIDEO",s[s.BOTH=2]="BOTH",s))(oi||{});class Dt extends se{constructor(e,t=Oe.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 cc extends Dt{constructor(){super("AliRtcScreenStandardize",Oe.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===Si.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 d;if(!this.shouldProcess(e))return this.clear(e),void(this.isProcessingScreenTrack=!1);if(e.originVideoTrack){const h=e.originVideoTrack.getSettings();if(h){const{width:p,height:u}=h;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(h,p){return I(this,null,function*(){const u=yield n.handleFrame(h);yield p.enqueue(u),u==null||u.close()})}});t.readable.pipeThrough(c).pipeTo(i.writable);const o=(d=r.getVideoTracks())==null?void 0:d[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 lc extends Dt{constructor(){super("blankAudio",Oe.AliRtcSdkStreamTypeCapture,oi.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 on{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(on,"LEVEL",0);class dc{constructor(){g(this,"logger",new on("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 hc extends Dt{constructor(){super("audioMixer",Oe.AliRtcSdkStreamTypeCapture,oi.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!==Oe.AliRtcSdkStreamTypeCapture)return!1;const i=t.find(o=>o.type===Oe.AliRtcSdkStreamTypeCapture),r=t.find(o=>o.type===Oe.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(l=>l.type===Oe.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 dc),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 uc extends Dt{constructor(){super(...arguments);g(this,"isProcessing",!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 hr.isSupport()}shouldUpdate(e){const t=!!e.currentVideoTrack;return this.isProcessing!==t}process(e){return I(this,null,function*(){if(e.currentVideoTrack){if(this.isProcessing=!0,!this.videoScaler){const i=this.options||this.initOptions;this.videoScaler=hr.getInstance(e.currentVideoTrack,i)}const t=this.videoScaler.getVideoTrack();t&&e.updateDualVideoTrack(t)}else this.isProcessing&&this.clear()})}clear(e){var t;super.clear(e),this.isProcessing=!1,e==null||e.updateDualVideoTrack(),(t=this.videoScaler)==null||t.dispose()}}function ci(s,a,e,t){return new(e||(e=Promise))(function(i,r){function n(l){try{o(t.next(l))}catch(d){r(d)}}function c(l){try{o(t.throw(l))}catch(d){r(d)}}function o(l){var d;l.done?i(l.value):(d=l.value,d instanceof e?d:new e(function(h){h(d)})).then(n,c)}o((t=t.apply(s,a||[])).next())})}var Bt,Et;function cn(){return ci(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,(Et=Bt||(Bt={}))[Et.ERROR=0]="ERROR",Et[Et.WARN=1]="WARN",Et[Et.INFO=2]="INFO",Et[Et.LOG=3]="LOG",Et[Et.DEBUG=4]="DEBUG";class ve{static error(...a){var e;ve.logLevel>=Bt.ERROR&&((e=console.error)===null||e===void 0||e.call(console,`[${ve.logTag}] `,...a))}static warn(...a){var e;ve.logLevel>=Bt.WARN&&((e=console.warn)===null||e===void 0||e.call(console,`[${ve.logTag}] `,...a))}static info(...a){var e;ve.logLevel>=Bt.INFO&&((e=console.info)===null||e===void 0||e.call(console,`[${ve.logTag}] `,...a))}static log(...a){var e;ve.logLevel>=Bt.LOG&&((e=console.log)===null||e===void 0||e.call(console,`[${ve.logTag}] `,...a))}static debug(...a){var e;ve.logLevel>=Bt.DEBUG&&((e=console.debug)===null||e===void 0||e.call(console,`[${ve.logTag}] `,...a))}}ve.logLevel=Bt.WARN,ve.logTag="aliyun-audio-3a";class pc{}class ln extends pc{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 ci(this,void 0,void 0,function*(){return yield cn()})}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 ci(this,void 0,void 0,function*(){ve.log("initWASM",a,e,t);const i=n=>ci(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=>ci(this,void 0,void 0,function*(){return fetch(n).then(c=>c.text())});try{const n=yield cn(),c=this.options.wasmCdnPath+"audio_module_v2.wasm",o=this.options.wasmCdnPath+"audio_module_v2_simd.wasm",d=yield i(n?o:c),h=this.options.wasmCdnPath+"audio_module_v2.js",p=this.options.wasmCdnPath+"audio_module_v2_simd.js",u=n?p:h,f=yield r(u);a.port.postMessage(Object.assign({type:"init",channelCount:e,sampleRate:t,wasmBuffer:d,isSupportSIMD:n,audioModuleScript:f,logLevel:ve.logLevel},this.options),[d])}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 ci(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 $c=Object.defineProperty,Kc=Object.defineProperties;var Jc=Object.getOwnPropertyDescriptors;var Xi=Object.getOwnPropertySymbols,Gc=Object.getPrototypeOf,xn=Object.prototype.hasOwnProperty,On=Object.prototype.propertyIsEnumerable,qc=Reflect.get;var Qr=(W,X,se)=>X in W?$c(W,X,{enumerable:!0,configurable:!0,writable:!0,value:se}):W[X]=se,G=(W,X)=>{for(var se in X||(X={}))xn.call(X,se)&&Qr(W,se,X[se]);if(Xi)for(var se of Xi(X))On.call(X,se)&&Qr(W,se,X[se]);return W},yt=(W,X)=>Kc(W,Jc(X));var Mt=(W,X)=>{var se={};for(var et in W)xn.call(W,et)&&X.indexOf(et)<0&&(se[et]=W[et]);if(W!=null&&Xi)for(var et of Xi(W))X.indexOf(et)<0&&On.call(W,et)&&(se[et]=W[et]);return se};var g=(W,X,se)=>(Qr(W,typeof X!="symbol"?X+"":X,se),se);var Zr=(W,X,se)=>qc(Gc(W),se,X);var I=(W,X,se)=>new Promise((et,ui)=>{var Mi=Ct=>{try{pi(se.next(Ct))}catch(ii){ui(ii)}},ti=Ct=>{try{pi(se.throw(Ct))}catch(ii){ui(ii)}},pi=Ct=>Ct.done?et(Ct.value):Promise.resolve(Ct.value).then(Mi,ti);pi((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"}),l=URL.createObjectURL(o);yield this.audioContext.audioWorklet.addModule(l)}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)}}class gc extends Dt{constructor(e){super("AliRtcAudioProcessPlugin",Oe.AliRtcSdkStreamTypeCapture,oi.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(){var e;(e=this.audioContext)==null||e.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 ln.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){this.audioProcessor=new ln({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),l=document.createElement("a");l.href=o,l.download=n,document.body.appendChild(l),l.click(),document.body.removeChild(l)},c)}),this.audioProcessor.on("loadsuccess",()=>{var r,n;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=>{this.emit("error",r)}),this.audioProcessor.on("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),l=JSON.parse(r);o!==null&&(l.diff=o);const d=this.extractLeakValue(this.lastDiffOutputLog);d!==null&&(l.leak=d),c=JSON.stringify(l)}(n=this.slsReporter)==null||n.reportPublishAudio3A("","","",c)}catch(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 Ai=(s=>(s[s.Default=0]="Default",s[s.Human=1]="Human",s[s.Robot=2]="Robot",s))(Ai||{}),mc=Object.defineProperty,fc=Object.getOwnPropertyDescriptor,dn=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?fc(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&&mc(a,e,r),r};const Nr=(Ft=class extends se{constructor(e,t){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,"robotUserId");g(this,"onSubscribeDataChannel",e=>{!this.remoteUser&&e&&(this.robotUserId&&this.robotUserId!==e.userId||(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&&(N.event(`[${Ft.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===te.AliRtcStatePublished&&(this.hasPubDataChannel=!0,this.trySendReadyMsg())});this.self=e,this.self.on("dataPublishStateChanged",this.onDataPublishStateChange),this.robotUserId=t}destroy(){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(){N.event(`[${Ft.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?N.event(`[${Ft.logName}]`,"sendReadyMsgLoop fail after 30 times"):this.sendReadyMsgTimer=window.setTimeout(()=>{this.sendReadyMsgLoop(e+1)},i)})}},g(Ft,"logName","DataChannelReadyHelper"),Ft);dn([C()],Nr.prototype,"destroy",1),dn([C()],Nr.prototype,"sendReadyMsgLoop",1);let Sc=Nr;class bc{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,l,d;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=(l=a.enableSoft3ACheck)!=null?l:this.enableSoft3ACheck,this.useHardOnly=(d=a.useHardOnly)!=null?d:this.useHardOnly}loadFromServerConfig(a){if(a&&typeof a=="object"){const e=Kt(a,"enableSoft3A"),t=si(a,"enableSoft3A");if(e===!0&&t===!0&&(this.enableSoft3A=!0),this.enableSoft3A){if(a.archCfgs){const i=Kt(a,"enableSoft3ACheck");i!==void 0&&(this.enableSoft3ACheck=i);const r=Kt(a,"useAIAEC");r!==void 0&&(this.useAIAEC=r);const n=Kt(a,"useSysNoiseSuppression");n!==void 0&&(this.useSysNoiseSuppression=n);const c=Kt(a,"useSysEchoCancellation");c!==void 0&&(this.useSysEchoCancellation=c);const o=Kt(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)}N.info("setAudio3AConfig:","enableSoft3A",this.enableSoft3A,", enableSoft3ACheck",this.enableSoft3ACheck,", useAIAEC",this.useAIAEC,", useSysNoiseSuppression",this.useSysNoiseSuppression,", useSysEchoCancellation",this.useSysEchoCancellation,", useSysAutoGainControl",this.useSysAutoGainControl)}}}}var vc=Object.defineProperty,yc=Object.getOwnPropertyDescriptor,it=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?yc(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&&vc(a,e,r),r};class Xe 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",Ke.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 bc);g(this,"dcReadyHelper");const{signalingManager:t,slsReporter:i,parameter:r}=e;this.signalingManager=t,this.addSignalingManagerListener(),this.slsReporter=i,r&&(this.parameter=r),this.pluginManager=new ec,this.localStreamManager=new nc(this.pluginManager,this.slsReporter),this.rtsManager=new rc(this.localStreamManager,this.slsReporter,this.parameter),this.addRTSListener(),this.self=new Go({rtsManager:this.rtsManager,localStreamManager:this.localStreamManager,slsReporter:this.slsReporter,signalingManager:this.signalingManager,pluginManager:this.pluginManager,audioVolumeIndicationInterval:this.audioVolumeIndicationInterval,parameter:this.parameter}),this.audioMixerPlugin=new hc,this.pluginManager.add(this.audioMixerPlugin),this.dualVideoPlugin=new uc("dualVideoPlugin"),new X.AliRTS.SupportUtil().checkScreenCapture()&&this.pluginManager.add(new cc)}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,"","",""),N.event("[Signaling] Notify Publish ",e),e.forEach(t=>{this.onRemotePublishStateChange(t)})}),this.signalingManager.stsManager.on("onTokenUpdate",(e,t)=>{this.slsReporter.updateToken(t,e)})}addRTSListener(){this.rtsManager.on("traceIdUpdated",(e,t)=>{if(Ne.removeQueryString(this.self.url)===Ne.removeQueryString(e))return void(this.self.traceId=t);const i=this.remoteUsers.find(r=>Ne.removeQueryString(r.streamUrl)===Ne.removeQueryString(e));i&&(i.traceId=t)}),this.rtsManager.on("reconnect",(e,t,i)=>{if(!e||e==="pc"||e==="all")return this.self.markReconnect(),void this.remoteUsers.forEach(n=>{n.markReconnect()});if(e==="pub"||e==="pub-data")return void this.self.markReconnect(i);const r=this.remoteUsers.find(n=>Ne.removeQueryString(n.streamUrl)===Ne.removeQueryString(t||""));r==null||r.markReconnect(i)}),this.rtsManager.on("reconnectFinish",(e,t,i)=>{if(N.event("[RtsManager]","reconnectFinish",e,t,i),!e||e==="pc"||e==="all")return this.self.markReconnected(),void this.remoteUsers.forEach(n=>{n.markReconnected()});if(e==="pub"||e==="pub-data")return void this.self.markReconnected(i);const r=this.remoteUsers.find(n=>Ne.removeQueryString(n.streamUrl)===Ne.removeQueryString(t||""));r==null||r.markReconnected(i)})}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){if(!e)return this.publisher.setViewConfig(null,t);const i=cr(e);i.length!==0&&i.forEach(r=>{this.publisher.resetElement(r),Object.values(this.usersViewMap).forEach(({cameraViews:n=[],screenViews:c=[]})=>{n.includes(r)&&n.splice(n.indexOf(r),1),c.includes(r)&&c.splice(c.indexOf(r),1)}),this.publisher.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=cr(t);r.length!==0&&(r.forEach(o=>{this.publisher.resetElement(o),Object.values(this.usersViewMap).forEach(({cameraViews:l=[],screenViews:d=[]})=>{l.includes(o)&&l.splice(l.indexOf(o),1),d.includes(o)&&d.splice(d.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,l=(u=n==null?void 0:n.pullstreamurl)!=null?u:"";let d=this.getRemoteUser(i);if(!d)return;const h=d.streamInfo.audioTrackInfo,p=d.streamInfo.videoTrackInfo;d.updateRemoteTracks(r,l,c,o),h===d.streamInfo.audioTrackInfo&&p===d.streamInfo.videoTrackInfo||this.emit("remoteTrackAvailableChange",i,d.streamInfo.audioTrackInfo,d.streamInfo.videoTrackInfo),t&&d.updateSubscribe(be.Publish)}setTimeoutToUpdateAllStreamUrls(e){var r;if(!e)return;let t=354e4;const i=(r=function(n){var c,o;try{const l=new URL(n),[d,h]=l.pathname.slice(1).split("/"),p=/(\w+)(web\w{5}-\w{4}-\w{4}-\w{4}-\w{12})/.exec(h),u=p==null?void 0:p[1],f=p==null?void 0:p[2],m=new URLSearchParams(l.search);return{appId:d,channelId:u,sessionId:f,timeoutTs:1e3*parseInt((o=(c=m.get("auth_key"))==null?void 0:c.split("-")[0])!=null?o:"0")}}catch(l){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 d;const l=this.getRemoteUser(o.userid);l&&((d=o.subscribe)!=null&&d.pullstreamurl)&&(l.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===Ai.Human&&(this.dcReadyHelper=new Sc(this.self,i.robotUserId),this.dcReadyHelper.on("dcready",n=>{var c;this.emit("remoteUserSubscribedDataChannel",n),(c=this.dcReadyHelper)==null||c.destroy(),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.destroy(),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 Zo({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(Qe.Remote,this.onRemoteDeviceStatusChange.bind(this)),r.on(Ce.PullStreamStats,this.onRemoteStatReport.bind(this)),r.on(Ce.RtsSubscribeExceeds,this.onSubscribeExceeds.bind(this)),r.on("audioSubscribeStateChanged",(n,c,o,l)=>{this.emit("audioSubscribeStateChanged",n,c,o,l,this.channel||"")}),r.on("videoSubscribeStateChanged",(n,c,o,l)=>{this.emit("videoSubscribeStateChanged",n,c,o,l,this.channel||"")}),r.on("screenSubscribeStateChanged",(n,c,o,l)=>{this.emit("screenSubscribeStateChanged",n,c,o,l,this.channel||"")}),r.on("dataSubscribeStateChanged",(n,c,o,l)=>{var d;o===ae.AliRtcStateSubscribed&&((d=this.dcReadyHelper)==null||d.onSubscribeDataChannel(this.userMap[n])),this.emit("dataSubscribeStateChanged",n,c,o,l,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===Ce.MuteAudio?this.emit("userAudioMuted",t,!0):e===Ce.UnmuteAudio?this.emit("userAudioMuted",t,!1):e===Ce.MuteVideo?this.emit("userVideoMuted",t,!0):e===Ce.UnmuteVideo?this.emit("userVideoMuted",t,!1):e===Ce.MuteScreen?this.emit("userScreenMuted",t,!0):e===Ce.UnmuteScreen&&this.emit("userScreenMuted",t,!1)}onRemoteStatReport(e,t,i){this.emit(Ce.PullStreamStats,e,t,i)}onSubscribeExceeds(e,t){this.emit(Ce.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:or.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 V(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 V(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 V(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 l=this.parameter[o],d=t[o];this.parameter[o]=typeof l=="object"&&typeof d=="object"?G(G({},l),d):d}),t.enableBlankAudio===!0?(this.blankAudioPlugin||(this.blankAudioPlugin=new lc),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 gc({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;N.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(Xe,"logName","BizControl"),it([C()],Xe.prototype,"init",1),it([C()],Xe.prototype,"leave",1),it([C()],Xe.prototype,"clear",1),it([C(B)],Xe.prototype,"addUser",1),it([C()],Xe.prototype,"removeLeftUser",1),it([C()],Xe.prototype,"diffUsers",1),it([C(B)],Xe.prototype,"updateAudioWant",1),it([C(B)],Xe.prototype,"updateVideoWant",1),it([C(B)],Xe.prototype,"updateScreenWant",1),it([C()],Xe.prototype,"stopIndication",1),it([C()],Xe.prototype,"startIndication",1),it([C(B)],Xe.prototype,"setEnableDualVideoStream",1),it([C(B)],Xe.prototype,"setAudioVolume",1),it([C()],Xe.prototype,"enableAudioVolumeIndication",1);var _i=(s=>(s[s.LiveTranscodingSingle=0]="LiveTranscodingSingle",s[s.LiveTranscodingMix=1]="LiveTranscodingMix",s))(_i||{}),xr=(s=>(s[s.LiveTranscodingOrigin=0]="LiveTranscodingOrigin",s[s.LiveTranscodingAudio=1]="LiveTranscodingAudio",s[s.LiveTranscodingVideo=2]="LiveTranscodingVideo",s))(xr||{}),li=(s=>(s[s.LiveTranscodingCamera=0]="LiveTranscodingCamera",s[s.LiveTranscodingShareScreen=1]="LiveTranscodingShareScreen",s))(li||{});const wi={0:"camera",1:"shareScreen"};var Or=(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))(Or||{});const Rc={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 $i=(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))($i||{}),Ei=(s=>(s[s.LiveTranscodingNoBody=0]="LiveTranscodingNoBody",s[s.LiveTranscodingBody=1]="LiveTranscodingBody",s))(Ei||{}),Ii=(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))(Ii||{}),Vr=(s=>(s[s.LiveTranscodingOrigin=0]="LiveTranscodingOrigin",s[s.LiveTranscodingCrop=1]="LiveTranscodingCrop",s[s.LiveTranscodingFill=2]="LiveTranscodingFill",s))(Vr||{}),Ki=(s=>(s[s.LiveTranscodingNormal=0]="LiveTranscodingNormal",s[s.LiveTranscodingVirtualBackground=1]="LiveTranscodingVirtualBackground",s))(Ki||{}),Ur=(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))(Ur||{}),It=(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))(It||{}),Br=(s=>(s[s.TrascodingPublishTaskStatusStart=0]="TrascodingPublishTaskStatusStart",s[s.TrascodingPublishTaskStatusUpdate=1]="TrascodingPublishTaskStatusUpdate",s[s.TrascodingPublishTaskStatusStop=2]="TrascodingPublishTaskStatusStop",s))(Br||{}),rt=(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))(rt||{});const Ac={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 Hr{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",$i.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 Fr=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 Ji{constructor(a,e,t){g(this,"mixMode",_i.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===rt.MPU_TASK_TRANSACTION_POLLING||a===rt.MPU_TASK_TRANSACTION_LIST||a===rt.MPU_TASK_TRANSACTION_ACKNOWLEDGE)return a===rt.MPU_TASK_TRANSACTION_ACKNOWLEDGE&&(n.messageid=r),n;if(n.taskid=t,a!==rt.MPU_TASK_TRANSACTION_STOP){if(n.mixmode=this.mixMode,i&&(n.streamurl=i),this.mixMode===_i.LiveTranscodingSingle){const c=this.singleParam;if(c){n.streamtype=c.streamType,c.sourceType===li.LiveTranscodingShareScreen?n.sourcetype=wi[c.sourceType]:n.sourcetype=wi[li.LiveTranscodingCamera];const o=[];c.userId&&o.push(c.userId),n.subspecusers=o}}else if(a===rt.MPU_TASK_TRANSACTION_START||a===rt.MPU_TASK_TRANSACTION_UPDATE){const c=this.mixParam;if(c){c.taskProfile&&(n.taskprofile=Rc[c.taskProfile]);const o=c.encodeParam||new Hr(1280,720);let l=o.videoWidth,d=o.videoHeight;const h={};Object.keys(o).forEach(u=>{const f=o[u];f>0&&(h[u.toLowerCase()]=f)}),h.lowbitratehighquality=0,n.encodeparam=h,n.backgrounds=c.backgrounds.map(u=>u.toJson(l,d)),n.watermarks=c.watermarks.map(u=>u.toJson(l,d)),n.clockwidgets=c.clockWidgets.map(u=>u.toJson(l,d));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,l,d,c.mediaProcessMode))}],n.layoutids=["0"],n.cropmode=c.cropMode,n.backgroundcolor=Fr(c.backgroundColor),n.taskmode=c.mediaProcessMode}}}return n}}const jr=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 _c{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(It.LiveTranscodingErrorInvalidParam);const i=Ac[a],r={appid:t.appId,userid:t.userId,channelid:t.channelId,timestamp:t.timestamp,token:t.token,nonce:t.nonce?t.nonce:"",requestid:Ne.createCallid(),tokensid:!1,session:(c=t.sessionId)!=null?c:Ne.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 V(U.ERR_INNER,`transcoding request failed, status: ${o.status}`))):o).catch(o=>Promise.reject(new V(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(It.LiveTranscodingErrorInvalidParam);const t=yield jr(a.split("?")[0]),i=rt.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(It.LiveTranscodingErrorInvalidParam);const t=rt.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(It.LiveTranscodingErrorInvalidParam);const t=yield jr(a.split("?")[0]),i=rt.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(It.LiveTranscodingErrorInvalidParam);const t=rt.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(It.LiveTranscodingErrorInvalidParam);const e=yield jr(a.split("?")[0]),t=rt.MPU_TASK_TRANSACTION_STOP,i=new Ji().toJson(t,this.authInfo,e,a);return this.doRequest(t,i)})}stopPublishLiveStreamWithTaskId(a){if(!this.authInfo)return Promise.reject(It.LiveTranscodingErrorInvalidParam);const e=rt.MPU_TASK_TRANSACTION_STOP,t=new Ji().toJson(e,this.authInfo,a);return this.doRequest(e,t)}refreshAuthInfo(a){this.authInfo&&this.setAuthInfo(G(G({},this.authInfo),a))}}function hn(s,a){const e=new window.XMLHttpRequest;e.open("POST",`${s}?APIVersion=0.6.0`,!0),e.send(a)}function wc(s,a){try{if(a.length>=32768)return void hn(s,a);(function(e,t){return!(!navigator||!navigator.sendBeacon)&&navigator.sendBeacon(`${e}?APIVersion=0.6.0`,t)})(s,a)||hn(s,a)}catch(e){window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
|
|
132
|
+
`)});try{this.startConnect();const l=yield this.rts.subscribe(lr(r,this.preferredSubL1Ip),n);return this._pcTraceId=l.traceId,this.setConnected(!0),{traceId:l.traceId,stream:l}}catch(l){throw this.setConnected(!1),this.emit("disconnected"),V.fromRtsError(l)}})}subscribeAdd(e){return I(this,null,function*(){var n,c,o,l;const{remoteUser:t,options:i}=e,r=yt(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 ma(d=>I(this,null,function*(){return yield this.dcConnectingPromise,d>0&&N.event(`[${Te.logName}]`,`subscribeAdd retry times: ${d}`),this.isConnected?this.rts.subscribeAdd([r]):Promise.reject()}),10,100,d=>{var h,p,u,f;return(d==null?void 0:d.errorCode)===15006||(d==null?void 0:d.errorCode)===15004&&((f=(u=(p=(h=d.extraInfo)==null?void 0:h.parsedData)==null?void 0:p.streams)==null?void 0:u[0])==null?void 0:f.res_code)===404}))[0]}catch(d){if(((l=(o=(c=(n=d==null?void 0:d.extraInfo)==null?void 0:n.parsedData)==null?void 0:c.streams)==null?void 0:o[0])==null?void 0:l.res_code)===508)return this.emit("subscribeexceeds"),null;throw V.fromRtsError(d)}})}subscribeDelete(e){return I(this,null,function*(){var n,c,o,l;const{remoteUser:t,options:i}=e,r=yt(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 N.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(d){if(((l=(o=(c=(n=d==null?void 0:d.extraInfo)==null?void 0:n.parsedData)==null?void 0:c.streams)==null?void 0:o[0])==null?void 0:l.res_code)===404)return;throw V.fromRtsError(d)}})}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})}subscribeDeleteDatachannel(e,t){return I(this,null,function*(){let i;try{i=yield this.rts.subscribeDeleteDatachannel({url:e,msid:M.Data,datachannel:t})}catch(r){}return i})}publish(r){return I(this,arguments,function*(e,t=!1,i=_t.MANUAL){const n=e.url;let c,o="";if(this.connecting&&(yield this.connectingPromise),this.connected){yield this.dcConnectingPromise;let l,d=!1;const{audio:h,video:p,videoSmall:u,screen:f}=this.localStreamManager.publishStreams;h&&(o=yield this.publishAdd(e,h,{aMsid:M.Audio},t),d=!0,l=M.Audio,yield xt(100)),p&&(o=yield this.publishAdd(e,p,{vMsid:M.VideoLarge},t),d=!1,l=M.VideoLarge,yield xt(100)),u&&(o=yield this.publishAdd(e,u,{vMsid:M.VideoSmall},t),d=!1,l=M.VideoSmall,yield xt(100)),f&&(o=yield this.publishAdd(e,f,{isScreen:!0,vMsid:M.Screen},t),d=!1,l=M.Screen),l&&(yield this.waitPublishSender(n,d,l))}else{const l=yield this.httpPublish(e,t,i);o=l.traceId,c=l.l1ip}return{traceId:o,l1ip:c}})}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,dt.START,t,c,i,0,r),this.slsReporter.reportConnectionLatencyEvent(ot.HANDLE_SUB_TASK,dt.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:l}=e;if(o.video&&o.screen)throw new V(U.ERR_INNER,"subscribe error, video and screen cannot be subscribed at the same time");let d;this.connecting&&(yield this.connectingPromise);let h=Date.now();this.connected?d=yield this.subscribeAdd(e):(c=!0,d=yield this.httpSubscribe(e)),this.reportSubscribeLatency(o,i,h,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 R=((w,y)=>{let A=0;const _=()=>{let E;return m&&!b&&(E=this.rts.getSubscribeAudioStats(l.streamUrl).then(T=>{if(T.packetsReceived>0)b=Date.now(),N.debug(`[${Te.logName}]`,l.userId,"Stats 音频首包");else if(!f)return A<w&&(A++,new Promise(k=>setTimeout(()=>k(_()),y)));return!0})),f&&!v&&(E=this.rts.getSubscribeVideoStats(l.streamUrl,u).then(T=>(!S&&T.packetsReceived>0&&(S=Date.now(),N.debug(`[${Te.logName}]`,l.userId,"Stats 视频首包")),T.framesDecoded>0?(v=Date.now(),N.debug(`[${Te.logName}]`,l.userId,"Stats 视频首帧数据"),!0):A<w?(A++,new Promise(k=>setTimeout(()=>k(_()),y))):(N.event(`[${Te.logName}]`,l.userId,"尝试获取首帧数据失败"),!1)))),Promise.resolve(E)};return _()})(20,100);return R.then(()=>{S&&this.slsReporter.reportSubscribeFirstPacket(t===be.Resume,i,r,u,{fprt:S-h,ifsprtc:v?v-h:0,ajsub:t===be.Join?1:0,pctid:this.pcTraceId,subtid:(d==null?void 0:d.traceId)||"",sstc:p-h}),v&&this.slsReporter.reportSubscribeFirstFrame(t===be.Resume,i,r,u,{fvfrt:v-h,fp2fftc:v-S,ajsub:t===be.Join?1:0,tffrtc:t===be.Join?v-this.localJoinTime:v-n,pctid:this.pcTraceId,subtid:(d==null?void 0:d.traceId)||"",fvfdtc:v-h}),b&&(this.slsReporter.reportConnectionLatencyEvent(ot.FIRST_REMOTE,dt.DECODED,i,M.Audio,b),this.slsReporter.reportSubscribeFirstPacket(t===be.Resume,i,r,M.Audio,{fprt:b-h,ifsprtc:b-h,ajsub:t===be.Join?1:0,pctid:this.pcTraceId,subtid:(d==null?void 0:d.traceId)||"",sstc:p-h}))}),d&&(d.isHTTP=c,d.statsCheckPromise=R),d})}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){var t;return(t=this.rts.commonController.datachannelManager)==null?void 0:t.getByMsid(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);ze([C(B)],Fe.prototype,"startConnect",1),ze([C()],Fe.prototype,"updatePublishingTracks",1),ze([C(B,B)],Fe.prototype,"httpPublish",1),ze([C(B,B)],Fe.prototype,"waitPublishSender",1),ze([C(([s,a,e])=>[s,JSON.stringify(e)],B)],Fe.prototype,"publishAdd",1),ze([C(B,B)],Fe.prototype,"publishDelete",1),ze([C(([s,a,e])=>[s,JSON.stringify(e)])],Fe.prototype,"publishReplace",1),ze([C(B)],Fe.prototype,"publishStop",1),ze([C(B)],Fe.prototype,"publishAddDataChannel",1),ze([C(B)],Fe.prototype,"publishStopDataChannel",1),ze([C()],Fe.prototype,"unpublish",1),ze([C(Wi,({traceId:s})=>s)],Fe.prototype,"httpSubscribe",1),ze([C(Wi,({traceId:s})=>s)],Fe.prototype,"subscribeAdd",1),ze([C(Wi)],Fe.prototype,"subscribeDelete",1),ze([C(B)],Fe.prototype,"subscribeAddDataChannel",1),ze([C(B)],Fe.prototype,"subscribeDeleteDatachannel",1),ze([C(B)],Fe.prototype,"publish",1),ze([C(Wi)],Fe.prototype,"subscribe",1),ze([C()],Fe.prototype,"sendSEI",1);let rc=Fe;class Mr{constructor(a=Cr){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 Oe=(s=>(s[s.AliRtcSdkStreamTypeCapture=0]="AliRtcSdkStreamTypeCapture",s[s.AliRtcSdkStreamTypeScreen=1]="AliRtcSdkStreamTypeScreen",s))(Oe||{});class Lr 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,l,d,h,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===Oe.AliRtcSdkStreamTypeScreen?this.stop():(r&&((l=this.originVideoTrack)==null||l.stop()),n&&((d=this.originAudioTrack)==null||d.stop())),r&&(this.originVideoTrack=r,(h=this.originVideoTrack)==null||h.addEventListener("ended",this.onVideoTrackEnded),this.videoSource=t||Si.Camera,this.updateVideoTrack(r)),n&&(this.originAudioTrack=n,(p=this.originAudioTrack)==null||p.addEventListener("ended",this.onAudioTrackEnded),this.audioSource=i||Bi.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,l,d,h,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 Ri(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 Ri(this._targetVideoTrack)):(this._publishVideoStream=void 0,(o=this.previewStream)==null||o.deleteTracks({video:!0})),this._targetDualVideoTrack?((d=(l=this._publishDualVideoStream)==null?void 0:l.videoTrack)==null?void 0:d.id)!==this._targetDualVideoTrack.id&&(this._publishDualVideoStream=yield Ri(this._targetDualVideoTrack),this._videoMuted?this._publishDualVideoStream.disableVideo():this._publishDualVideoStream.enableVideo()):this._publishDualVideoStream=void 0,this._targetAudioTrack?((p=(h=this._publishAudioStream)==null?void 0:h.audioTrack)==null?void 0:p.id)!==this._targetAudioTrack.id&&(this._publishAudioStream=yield Ri(this._targetAudioTrack),this.setAudioMuted(this._audioMuted),this.previewStream?(u=this.previewStream)==null||u.mergeStream(this._publishAudioStream):this._previewStream=yield Ri(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 Mr(this.type===Oe.AliRtcSdkStreamTypeScreen?en:Cr)),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 Mr(this.type===Oe.AliRtcSdkStreamTypeScreen?en:Cr)),this._profileManager.setContentHint(this.currentVideoTrack,e)}updateAudioProfile(e){return I(this,null,function*(){this._profileManager||(this._profileManager=new Mr),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 sc=Object.defineProperty,ac=Object.getOwnPropertyDescriptor,ft=(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&&sc(a,e,r),r};const ut=(Ht=class extends se{constructor(e,t){super();g(this,"pluginManager");g(this,"slsReporter");g(this,"publishingCameraVideoStream");g(this,"publishingScreenVideoStream");g(this,"cameraStreamInfo",new Lr(Oe.AliRtcSdkStreamTypeCapture));g(this,"screenStreamInfo",new Lr(Oe.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",qt.VideoTrackEnded)})),this.cameraStreamInfo.on("audiotrackended",()=>I(this,null,function*(){yield this.stopLocalStream({audio:!0}),this.emit("trackended",qt.AudioTrackEnded)})),this.screenStreamInfo.on("videotrackended",()=>I(this,null,function*(){yield this.stopLocalStream({screen:!0}),this.emit("trackended",qt.ScreenTrackEnded)})),this.pluginManager.on("added",i=>I(this,null,function*(){if(N.info(`[${Ht.logName}]`,"plugin added",i.name),!i.isSupported("7.2.1"))return console.warn(`${i.name} is not supported!!!`),void i.emit("unsupported");try{yield i.init()}catch(r){i.emit("error",V.fromError(r,Ut.AliRtcPluginErrorInitError))}i.streamType===Oe.AliRtcSdkStreamTypeCapture&&(this.cameraStreamInfo.addPlugin(i),yield this.cameraStreamInfo.process(this.streamInfos)),i.streamType===Oe.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 h;const{screen:t,mediaStream:i,videoProfile:r,screenProfile:n}=e;let{video:c,audio:o}=e;const l=(p=>{const{audio:u,video:f,screen:m}=p;if(f&&m)throw new V(U.ERR_INNER,"create stream error, cannot create video && screen together");return!!(f||u||m)})(e);let d;if(l){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{d=yield X.AliRTS.createStream({audio:o,video:c,screen:t,custom:!!i,mediaStream:i,skipProfile:!0}),N.info(`[${Ht.logName}]`,"createLocalStream",{audio:o,video:c,screen:t,custom:!!i,time:Date.now()-p}),o&&!i&&this.slsReporter.reportAudio(null,Date.now()-p,((h=d==null?void 0:d.audioTrack)==null?void 0:h.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(d,Si.Screen,Bi.Screen),yield this.setScreenProfile(n||Za),this.setScreenContentHint(),this.publishingScreenVideoStream=void 0;else if(yield this.cameraStreamInfo.updateSource(d,Si.Camera,Bi.Microphone),d.hasVideo&&(yield this.setVideoProfile(r||Qa),this.setVideoContentHint(),this.publishingCameraVideoStream=void 0),d.hasAudio&&typeof o=="boolean"){const u=this.cameraStreamInfo.audioProfile;u&&(yield d.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(),d})}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,l,d,h;let e,t,i,r,n=!1;const c=this.publishStreams;try{if(!(c.audio||c.video||c.videoSmall||c.screen))throw N.error(`[${Ht.logName}]`,"no tracks founded"),new V(U.ERR_SDK_PUBLISH_INVAILD,"no tracks founded");const p=new MediaStream;(o=c.audio)!=null&&o.audioTrack&&p.addTrack(c.audio.audioTrack),(l=c.video)!=null&&l.videoTrack?(p.addTrack(c.video.videoTrack),i=c.videoSmall,r=c.screen):(d=c.screen)!=null&&d.videoTrack&&(t=M.Screen,p.addTrack((h=c.screen)==null?void 0:h.videoTrack),n=!0),e=yield sn(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(Ht,"logName","LocalStreamManager"),Ht);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(B)],ut.prototype,"stopLocalStream",1),ft([C()],ut.prototype,"createHTTPPublishStream",1),ft([C()],ut.prototype,"stop",1),ft([C(B)],ut.prototype,"setVideoProfile",1),ft([C(B)],ut.prototype,"setVideoContentHint",1),ft([C(B)],ut.prototype,"setAudioProfile",1),ft([C(B)],ut.prototype,"setScreenProfile",1),ft([C(B)],ut.prototype,"setScreenContentHint",1),ft([C(B)],ut.prototype,"setCameraVideoConstraints",1),ft([C(B)],ut.prototype,"setMicAudioConstraints",1);let nc=ut;const oc=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 nn=(s=>(s[s.PRE_PROCESSOR=0]="PRE_PROCESSOR",s[s.POST_PROCESSOR=1]="POST_PROCESSOR",s))(nn||{}),oi=(s=>(s[s.AUDIO=0]="AUDIO",s[s.VIDEO=1]="VIDEO",s[s.BOTH=2]="BOTH",s))(oi||{});class Dt extends se{constructor(e,t=Oe.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 cc extends Dt{constructor(){super("AliRtcScreenStandardize",Oe.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===Si.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 d;if(!this.shouldProcess(e))return this.clear(e),void(this.isProcessingScreenTrack=!1);if(e.originVideoTrack){const h=e.originVideoTrack.getSettings();if(h){const{width:p,height:u}=h;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(h,p){return I(this,null,function*(){const u=yield n.handleFrame(h);yield p.enqueue(u),u==null||u.close()})}});t.readable.pipeThrough(c).pipeTo(i.writable);const o=(d=r.getVideoTracks())==null?void 0:d[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 lc extends Dt{constructor(){super("blankAudio",Oe.AliRtcSdkStreamTypeCapture,oi.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 on{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(on,"LEVEL",0);class dc{constructor(){g(this,"logger",new on("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 hc extends Dt{constructor(){super("audioMixer",Oe.AliRtcSdkStreamTypeCapture,oi.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!==Oe.AliRtcSdkStreamTypeCapture)return!1;const i=t.find(o=>o.type===Oe.AliRtcSdkStreamTypeCapture),r=t.find(o=>o.type===Oe.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(l=>l.type===Oe.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 dc),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 uc extends Dt{constructor(){super(...arguments);g(this,"isProcessing",!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 hr.isSupport()}shouldUpdate(e){const t=!!e.currentVideoTrack;return this.isProcessing!==t}process(e){return I(this,null,function*(){if(e.currentVideoTrack){if(this.isProcessing=!0,!this.videoScaler){const i=this.options||this.initOptions;this.videoScaler=hr.getInstance(e.currentVideoTrack,i)}const t=this.videoScaler.getVideoTrack();t&&e.updateDualVideoTrack(t)}else this.isProcessing&&this.clear()})}clear(e){var t;super.clear(e),this.isProcessing=!1,e==null||e.updateDualVideoTrack(),(t=this.videoScaler)==null||t.dispose()}}function ci(s,a,e,t){return new(e||(e=Promise))(function(i,r){function n(l){try{o(t.next(l))}catch(d){r(d)}}function c(l){try{o(t.throw(l))}catch(d){r(d)}}function o(l){var d;l.done?i(l.value):(d=l.value,d instanceof e?d:new e(function(h){h(d)})).then(n,c)}o((t=t.apply(s,a||[])).next())})}var Bt,Et;function cn(){return ci(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,(Et=Bt||(Bt={}))[Et.ERROR=0]="ERROR",Et[Et.WARN=1]="WARN",Et[Et.INFO=2]="INFO",Et[Et.LOG=3]="LOG",Et[Et.DEBUG=4]="DEBUG";class ve{static error(...a){var e;ve.logLevel>=Bt.ERROR&&((e=console.error)===null||e===void 0||e.call(console,`[${ve.logTag}] `,...a))}static warn(...a){var e;ve.logLevel>=Bt.WARN&&((e=console.warn)===null||e===void 0||e.call(console,`[${ve.logTag}] `,...a))}static info(...a){var e;ve.logLevel>=Bt.INFO&&((e=console.info)===null||e===void 0||e.call(console,`[${ve.logTag}] `,...a))}static log(...a){var e;ve.logLevel>=Bt.LOG&&((e=console.log)===null||e===void 0||e.call(console,`[${ve.logTag}] `,...a))}static debug(...a){var e;ve.logLevel>=Bt.DEBUG&&((e=console.debug)===null||e===void 0||e.call(console,`[${ve.logTag}] `,...a))}}ve.logLevel=Bt.WARN,ve.logTag="aliyun-audio-3a";class pc{}class ln extends pc{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 ci(this,void 0,void 0,function*(){return yield cn()})}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 ci(this,void 0,void 0,function*(){ve.log("initWASM",a,e,t);const i=n=>ci(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=>ci(this,void 0,void 0,function*(){return fetch(n).then(c=>c.text())});try{const n=yield cn(),c=this.options.wasmCdnPath+"audio_module_v2.wasm",o=this.options.wasmCdnPath+"audio_module_v2_simd.wasm",d=yield i(n?o:c),h=this.options.wasmCdnPath+"audio_module_v2.js",p=this.options.wasmCdnPath+"audio_module_v2_simd.js",u=n?p:h,f=yield r(u);a.port.postMessage(Object.assign({type:"init",channelCount:e,sampleRate:t,wasmBuffer:d,isSupportSIMD:n,audioModuleScript:f,logLevel:ve.logLevel},this.options),[d])}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 ci(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 $c=Object.defineProperty,Kc=Object.defineProperties;var Jc=Object.getOwnPropertyDescriptors;var Xi=Object.getOwnPropertySymbols,Gc=Object.getPrototypeOf,xn=Object.prototype.hasOwnProperty,On=Object.prototype.propertyIsEnumerable,qc=Reflect.get;var Qr=(W,X,se)=>X in W?$c(W,X,{enumerable:!0,configurable:!0,writable:!0,value:se}):W[X]=se,G=(W,X)=>{for(var se in X||(X={}))xn.call(X,se)&&Qr(W,se,X[se]);if(Xi)for(var se of Xi(X))On.call(X,se)&&Qr(W,se,X[se]);return W},yt=(W,X)=>Kc(W,Jc(X));var Mt=(W,X)=>{var se={};for(var et in W)xn.call(W,et)&&X.indexOf(et)<0&&(se[et]=W[et]);if(W!=null&&Xi)for(var et of Xi(W))X.indexOf(et)<0&&On.call(W,et)&&(se[et]=W[et]);return se};var g=(W,X,se)=>(Qr(W,typeof X!="symbol"?X+"":X,se),se);var Zr=(W,X,se)=>qc(Gc(W),se,X);var I=(W,X,se)=>new Promise((et,ui)=>{var Mi=Ct=>{try{pi(se.next(Ct))}catch(ii){ui(ii)}},ti=Ct=>{try{pi(se.throw(Ct))}catch(ii){ui(ii)}},pi=Ct=>Ct.done?et(Ct.value):Promise.resolve(Ct.value).then(Mi,ti);pi((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"}),l=URL.createObjectURL(o);yield this.audioContext.audioWorklet.addModule(l)}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)}}class gc extends Dt{constructor(e){super("AliRtcAudioProcessPlugin",Oe.AliRtcSdkStreamTypeCapture,oi.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(){var e;(e=this.audioContext)==null||e.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 ln.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){this.audioProcessor=new ln({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),l=document.createElement("a");l.href=o,l.download=n,document.body.appendChild(l),l.click(),document.body.removeChild(l)},c)}),this.audioProcessor.on("loadsuccess",()=>{var r,n;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=>{this.emit("error",r)}),this.audioProcessor.on("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),l=JSON.parse(r);o!==null&&(l.diff=o);const d=this.extractLeakValue(this.lastDiffOutputLog);d!==null&&(l.leak=d),c=JSON.stringify(l)}(n=this.slsReporter)==null||n.reportPublishAudio3A("","","",c)}catch(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 Ai=(s=>(s[s.Default=0]="Default",s[s.Human=1]="Human",s[s.Robot=2]="Robot",s))(Ai||{}),mc=Object.defineProperty,fc=Object.getOwnPropertyDescriptor,dn=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?fc(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&&mc(a,e,r),r};const Nr=(Ft=class extends se{constructor(e,t){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,"robotUserId");g(this,"onSubscribeDataChannel",e=>{!this.remoteUser&&e&&(this.robotUserId&&this.robotUserId!==e.userId||(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&&(N.event(`[${Ft.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===te.AliRtcStatePublished&&(this.hasPubDataChannel=!0,this.trySendReadyMsg())});this.self=e,this.self.on("dataPublishStateChanged",this.onDataPublishStateChange),this.robotUserId=t}destroy(){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(){N.event(`[${Ft.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?N.event(`[${Ft.logName}]`,"sendReadyMsgLoop fail after 30 times"):this.sendReadyMsgTimer=window.setTimeout(()=>{this.sendReadyMsgLoop(e+1)},i)})}},g(Ft,"logName","DataChannelReadyHelper"),Ft);dn([C()],Nr.prototype,"destroy",1),dn([C()],Nr.prototype,"sendReadyMsgLoop",1);let Sc=Nr;class bc{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,l,d;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=(l=a.enableSoft3ACheck)!=null?l:this.enableSoft3ACheck,this.useHardOnly=(d=a.useHardOnly)!=null?d:this.useHardOnly}loadFromServerConfig(a){if(a&&typeof a=="object"){const e=Kt(a,"enableSoft3A"),t=si(a,"enableSoft3A");if(e===!0&&t===!0&&(this.enableSoft3A=!0),this.enableSoft3A){if(a.archCfgs){const i=Kt(a,"enableSoft3ACheck");i!==void 0&&(this.enableSoft3ACheck=i);const r=Kt(a,"useAIAEC");r!==void 0&&(this.useAIAEC=r);const n=Kt(a,"useSysNoiseSuppression");n!==void 0&&(this.useSysNoiseSuppression=n);const c=Kt(a,"useSysEchoCancellation");c!==void 0&&(this.useSysEchoCancellation=c);const o=Kt(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)}N.info("setAudio3AConfig:","enableSoft3A",this.enableSoft3A,", enableSoft3ACheck",this.enableSoft3ACheck,", useAIAEC",this.useAIAEC,", useSysNoiseSuppression",this.useSysNoiseSuppression,", useSysEchoCancellation",this.useSysEchoCancellation,", useSysAutoGainControl",this.useSysAutoGainControl)}}}}var vc=Object.defineProperty,yc=Object.getOwnPropertyDescriptor,it=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?yc(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&&vc(a,e,r),r};class Xe 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",Ke.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 bc);g(this,"dcReadyHelper");const{signalingManager:t,slsReporter:i,parameter:r}=e;this.signalingManager=t,this.addSignalingManagerListener(),this.slsReporter=i,r&&(this.parameter=r),this.pluginManager=new ec,this.localStreamManager=new nc(this.pluginManager,this.slsReporter),this.rtsManager=new rc(this.localStreamManager,this.slsReporter,this.parameter),this.addRTSListener(),this.self=new Go({rtsManager:this.rtsManager,localStreamManager:this.localStreamManager,slsReporter:this.slsReporter,signalingManager:this.signalingManager,pluginManager:this.pluginManager,audioVolumeIndicationInterval:this.audioVolumeIndicationInterval,parameter:this.parameter}),this.audioMixerPlugin=new hc,this.pluginManager.add(this.audioMixerPlugin),this.dualVideoPlugin=new uc("dualVideoPlugin"),new X.AliRTS.SupportUtil().checkScreenCapture()&&this.pluginManager.add(new cc)}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,"","",""),N.event("[Signaling] Notify Publish ",e),e.forEach(t=>{this.onRemotePublishStateChange(t)})}),this.signalingManager.stsManager.on("onTokenUpdate",(e,t)=>{this.slsReporter.updateToken(t,e)})}addRTSListener(){this.rtsManager.on("traceIdUpdated",(e,t)=>{if(Ne.removeQueryString(this.self.url)===Ne.removeQueryString(e))return void(this.self.traceId=t);const i=this.remoteUsers.find(r=>Ne.removeQueryString(r.streamUrl)===Ne.removeQueryString(e));i&&(i.traceId=t)}),this.rtsManager.on("reconnect",(e,t,i)=>{if(!e||e==="pc"||e==="all")return this.self.markReconnect(),void this.remoteUsers.forEach(n=>{n.markReconnect()});if(e==="pub"||e==="pub-data")return void this.self.markReconnect(i);const r=this.remoteUsers.find(n=>Ne.removeQueryString(n.streamUrl)===Ne.removeQueryString(t||""));r==null||r.markReconnect(i)}),this.rtsManager.on("reconnectFinish",(e,t,i)=>{if(N.event("[RtsManager]","reconnectFinish",e,t,i),!e||e==="pc"||e==="all")return this.self.markReconnected(),void this.remoteUsers.forEach(n=>{n.markReconnected()});if(e==="pub"||e==="pub-data")return void this.self.markReconnected(i);const r=this.remoteUsers.find(n=>Ne.removeQueryString(n.streamUrl)===Ne.removeQueryString(t||""));r==null||r.markReconnected(i)})}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){if(!e)return this.publisher.setViewConfig(null,t);const i=cr(e);i.length!==0&&i.forEach(r=>{this.publisher.resetElement(r),Object.values(this.usersViewMap).forEach(({cameraViews:n=[],screenViews:c=[]})=>{n.includes(r)&&n.splice(n.indexOf(r),1),c.includes(r)&&c.splice(c.indexOf(r),1)}),this.publisher.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=cr(t);r.length!==0&&(r.forEach(o=>{this.publisher.resetElement(o),Object.values(this.usersViewMap).forEach(({cameraViews:l=[],screenViews:d=[]})=>{l.includes(o)&&l.splice(l.indexOf(o),1),d.includes(o)&&d.splice(d.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,l=(u=n==null?void 0:n.pullstreamurl)!=null?u:"";let d=this.getRemoteUser(i);if(!d)return;const h=d.streamInfo.audioTrackInfo,p=d.streamInfo.videoTrackInfo;d.updateRemoteTracks(r,l,c,o),h===d.streamInfo.audioTrackInfo&&p===d.streamInfo.videoTrackInfo||this.emit("remoteTrackAvailableChange",i,d.streamInfo.audioTrackInfo,d.streamInfo.videoTrackInfo),t&&d.updateSubscribe(be.Publish)}setTimeoutToUpdateAllStreamUrls(e){var r;if(!e)return;let t=354e4;const i=(r=function(n){var c,o;try{const l=new URL(n),[d,h]=l.pathname.slice(1).split("/"),p=/(\w+)(web\w{5}-\w{4}-\w{4}-\w{4}-\w{12})/.exec(h),u=p==null?void 0:p[1],f=p==null?void 0:p[2],m=new URLSearchParams(l.search);return{appId:d,channelId:u,sessionId:f,timeoutTs:1e3*parseInt((o=(c=m.get("auth_key"))==null?void 0:c.split("-")[0])!=null?o:"0")}}catch(l){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 d;const l=this.getRemoteUser(o.userid);l&&((d=o.subscribe)!=null&&d.pullstreamurl)&&(l.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===Ai.Human&&(this.dcReadyHelper=new Sc(this.self,i.robotUserId),this.dcReadyHelper.on("dcready",n=>{var c;this.emit("remoteUserSubscribedDataChannel",n),(c=this.dcReadyHelper)==null||c.destroy(),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.destroy(),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 Zo({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(Qe.Remote,this.onRemoteDeviceStatusChange.bind(this)),r.on(Ce.PullStreamStats,this.onRemoteStatReport.bind(this)),r.on(Ce.RtsSubscribeExceeds,this.onSubscribeExceeds.bind(this)),r.on("audioSubscribeStateChanged",(n,c,o,l)=>{this.emit("audioSubscribeStateChanged",n,c,o,l,this.channel||"")}),r.on("videoSubscribeStateChanged",(n,c,o,l)=>{this.emit("videoSubscribeStateChanged",n,c,o,l,this.channel||"")}),r.on("screenSubscribeStateChanged",(n,c,o,l)=>{this.emit("screenSubscribeStateChanged",n,c,o,l,this.channel||"")}),r.on("dataSubscribeStateChanged",(n,c,o,l)=>{var d;o===ae.AliRtcStateSubscribed&&((d=this.dcReadyHelper)==null||d.onSubscribeDataChannel(this.userMap[n])),this.emit("dataSubscribeStateChanged",n,c,o,l,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===Ce.MuteAudio?this.emit("userAudioMuted",t,!0):e===Ce.UnmuteAudio?this.emit("userAudioMuted",t,!1):e===Ce.MuteVideo?this.emit("userVideoMuted",t,!0):e===Ce.UnmuteVideo?this.emit("userVideoMuted",t,!1):e===Ce.MuteScreen?this.emit("userScreenMuted",t,!0):e===Ce.UnmuteScreen&&this.emit("userScreenMuted",t,!1)}onRemoteStatReport(e,t,i){this.emit(Ce.PullStreamStats,e,t,i)}onSubscribeExceeds(e,t){this.emit(Ce.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:or.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 V(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 V(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 V(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 l=this.parameter[o],d=t[o];this.parameter[o]=typeof l=="object"&&typeof d=="object"?G(G({},l),d):d}),t.enableBlankAudio===!0?(this.blankAudioPlugin||(this.blankAudioPlugin=new lc),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 gc({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;N.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(Xe,"logName","BizControl"),it([C()],Xe.prototype,"init",1),it([C()],Xe.prototype,"leave",1),it([C()],Xe.prototype,"clear",1),it([C(B)],Xe.prototype,"addUser",1),it([C()],Xe.prototype,"removeLeftUser",1),it([C()],Xe.prototype,"diffUsers",1),it([C(B)],Xe.prototype,"updateAudioWant",1),it([C(B)],Xe.prototype,"updateVideoWant",1),it([C(B)],Xe.prototype,"updateScreenWant",1),it([C()],Xe.prototype,"stopIndication",1),it([C()],Xe.prototype,"startIndication",1),it([C(B)],Xe.prototype,"setEnableDualVideoStream",1),it([C(B)],Xe.prototype,"setAudioVolume",1),it([C()],Xe.prototype,"enableAudioVolumeIndication",1);var _i=(s=>(s[s.LiveTranscodingSingle=0]="LiveTranscodingSingle",s[s.LiveTranscodingMix=1]="LiveTranscodingMix",s))(_i||{}),xr=(s=>(s[s.LiveTranscodingOrigin=0]="LiveTranscodingOrigin",s[s.LiveTranscodingAudio=1]="LiveTranscodingAudio",s[s.LiveTranscodingVideo=2]="LiveTranscodingVideo",s))(xr||{}),li=(s=>(s[s.LiveTranscodingCamera=0]="LiveTranscodingCamera",s[s.LiveTranscodingShareScreen=1]="LiveTranscodingShareScreen",s))(li||{});const wi={0:"camera",1:"shareScreen"};var Or=(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))(Or||{});const Rc={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 $i=(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))($i||{}),Ei=(s=>(s[s.LiveTranscodingNoBody=0]="LiveTranscodingNoBody",s[s.LiveTranscodingBody=1]="LiveTranscodingBody",s))(Ei||{}),Ii=(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))(Ii||{}),Vr=(s=>(s[s.LiveTranscodingOrigin=0]="LiveTranscodingOrigin",s[s.LiveTranscodingCrop=1]="LiveTranscodingCrop",s[s.LiveTranscodingFill=2]="LiveTranscodingFill",s))(Vr||{}),Ki=(s=>(s[s.LiveTranscodingNormal=0]="LiveTranscodingNormal",s[s.LiveTranscodingVirtualBackground=1]="LiveTranscodingVirtualBackground",s))(Ki||{}),Ur=(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))(Ur||{}),It=(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))(It||{}),Br=(s=>(s[s.TrascodingPublishTaskStatusStart=0]="TrascodingPublishTaskStatusStart",s[s.TrascodingPublishTaskStatusUpdate=1]="TrascodingPublishTaskStatusUpdate",s[s.TrascodingPublishTaskStatusStop=2]="TrascodingPublishTaskStatusStop",s))(Br||{}),rt=(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))(rt||{});const Ac={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 Hr{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",$i.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 Fr=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 Ji{constructor(a,e,t){g(this,"mixMode",_i.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===rt.MPU_TASK_TRANSACTION_POLLING||a===rt.MPU_TASK_TRANSACTION_LIST||a===rt.MPU_TASK_TRANSACTION_ACKNOWLEDGE)return a===rt.MPU_TASK_TRANSACTION_ACKNOWLEDGE&&(n.messageid=r),n;if(n.taskid=t,a!==rt.MPU_TASK_TRANSACTION_STOP){if(n.mixmode=this.mixMode,i&&(n.streamurl=i),this.mixMode===_i.LiveTranscodingSingle){const c=this.singleParam;if(c){n.streamtype=c.streamType,c.sourceType===li.LiveTranscodingShareScreen?n.sourcetype=wi[c.sourceType]:n.sourcetype=wi[li.LiveTranscodingCamera];const o=[];c.userId&&o.push(c.userId),n.subspecusers=o}}else if(a===rt.MPU_TASK_TRANSACTION_START||a===rt.MPU_TASK_TRANSACTION_UPDATE){const c=this.mixParam;if(c){c.taskProfile&&(n.taskprofile=Rc[c.taskProfile]);const o=c.encodeParam||new Hr(1280,720);let l=o.videoWidth,d=o.videoHeight;const h={};Object.keys(o).forEach(u=>{const f=o[u];f>0&&(h[u.toLowerCase()]=f)}),h.lowbitratehighquality=0,n.encodeparam=h,n.backgrounds=c.backgrounds.map(u=>u.toJson(l,d)),n.watermarks=c.watermarks.map(u=>u.toJson(l,d)),n.clockwidgets=c.clockWidgets.map(u=>u.toJson(l,d));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,l,d,c.mediaProcessMode))}],n.layoutids=["0"],n.cropmode=c.cropMode,n.backgroundcolor=Fr(c.backgroundColor),n.taskmode=c.mediaProcessMode}}}return n}}const jr=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 _c{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(It.LiveTranscodingErrorInvalidParam);const i=Ac[a],r={appid:t.appId,userid:t.userId,channelid:t.channelId,timestamp:t.timestamp,token:t.token,nonce:t.nonce?t.nonce:"",requestid:Ne.createCallid(),tokensid:!1,session:(c=t.sessionId)!=null?c:Ne.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 V(U.ERR_INNER,`transcoding request failed, status: ${o.status}`))):o).catch(o=>Promise.reject(new V(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(It.LiveTranscodingErrorInvalidParam);const t=yield jr(a.split("?")[0]),i=rt.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(It.LiveTranscodingErrorInvalidParam);const t=rt.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(It.LiveTranscodingErrorInvalidParam);const t=yield jr(a.split("?")[0]),i=rt.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(It.LiveTranscodingErrorInvalidParam);const t=rt.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(It.LiveTranscodingErrorInvalidParam);const e=yield jr(a.split("?")[0]),t=rt.MPU_TASK_TRANSACTION_STOP,i=new Ji().toJson(t,this.authInfo,e,a);return this.doRequest(t,i)})}stopPublishLiveStreamWithTaskId(a){if(!this.authInfo)return Promise.reject(It.LiveTranscodingErrorInvalidParam);const e=rt.MPU_TASK_TRANSACTION_STOP,t=new Ji().toJson(e,this.authInfo,a);return this.doRequest(e,t)}refreshAuthInfo(a){this.authInfo&&this.setAuthInfo(G(G({},this.authInfo),a))}}function hn(s,a){const e=new window.XMLHttpRequest;e.open("POST",`${s}?APIVersion=0.6.0`,!0),e.send(a)}function wc(s,a){try{if(a.length>=32768)return void hn(s,a);(function(e,t){return!(!navigator||!navigator.sendBeacon)&&navigator.sendBeacon(`${e}?APIVersion=0.6.0`,t)})(s,a)||hn(s,a)}catch(e){window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
|
|
133
133
|
`+e),console.error("Failed log data:",s))}}function Ec(s,a,e){return t=this,i=null,r=function*(){try{s=s.slice(0,-6);const{data:n,header:c}=yield e.process(s,a),o=new window.XMLHttpRequest;o.open("POST",s,!0);for(let l in c)o.setRequestHeader(l,c[l]);o.send(n)}catch(n){window&&window.console&&typeof window.console.error=="function"&&(console.error(`Failed to log to ali log service because of this exception:
|
|
134
|
-
`+n),console.error("Failed log data:",s))}},new Promise((n,c)=>{var o=h=>{try{d(r.next(h))}catch(p){c(p)}},l=h=>{try{d(r.throw(h))}catch(p){c(p)}},d=h=>h.done?n(h.value):Promise.resolve(h.value).then(o,l);d((r=r.apply(t,i)).next())});var t,i,r}class un extends ca{constructor(a){super(Object.assign({},a,{installUnloadHook:e=>{window.addEventListener("beforeunload",()=>{e()})},sendPayload:(e,t)=>{wc(e,t)}}))}useStsPlugin(a){this.getOpt().sendPayload=(e,t)=>{Ec(e,t,a)},this.overwriteTransString(a)}}Mi(window,"SLS_Tracker",un);const Zt=class Zt{constructor(){g(this,"ntpClock");this.ntpClock=new X.AliRTS.Clock}static getInstance(){return Zt.instance||(Zt.instance=new Zt),Zt.instance}now(){return this.ntpClock.now()}};g(Zt,"instance");let zr=Zt;const pn=()=>zr.getInstance(),{BrowserUtil:Wr,SystenUtil:gn}=X.AliRTS;class mn{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=pn()}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 un({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=Zi(t);e.useStsPlugin(i),this.tracker=e,this.msgCacheArr.forEach((r,n)=>{var c,o;(o=this.tracker)==null||o.send(G(yt(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(yt(G({bt:Wr.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=lt(),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:gn.systemName,osv:gn.systemVersion,deb:Co(),den:Eo(),udid:e,sdkvrs:Ni,acs:"Unknown",cput:oa(),dm:`${window.location.protocol}//${window.location.host}`,bt:Wr.browserName,bv:Wr.browserVersion,envir:"PRODUCT",args:"",instid:lt()})}}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)))},gt=(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))))},Xt=(s,a)=>{if(a===0||!a)return"0.00";let e=s;return(!e||e<0)&&(e=0),(e/a*100).toFixed(2)},fn=s=>s>=0&&s<=1?Ae(Math.floor(32767*s),1,32767):0,Ie=(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},Sn=(s,a)=>Ae(Ie(s,a),1e3,1e4),Yt=(s,a=2e7)=>Ae(s,1,a),Ci=class Ci{constructor(a){g(this,"engine");g(this,"logClient");g(this,"authInfo");g(this,"ntpClock");g(this,"customFields",{});this.logClient=new mn,this.engine=a,this.ntpClock=pn()}static getLogClient(){return this.staticClient||(this.staticClient=new mn),this.staticClient}static reportOSSUpload(a,e,t=0){Ci.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),Ci.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,rmtid:"",args:this.data2String(G({calid:a,tckid:e||"audio3a",rmtid:"",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=[],l=[],d=[],h=[],p=[],u=[],f=[],m=[],b=[],S=[],v=[],R=[],w=[],y=[],A=[],_=[],E=[],T=[],k=[];try{if(r.forEach(P=>{var O,de,Pe,K,me,Me;if(!P||!P.timestamp)return;const H=(O=P._last)!=null&&O.timestamp?P.timestamp-P._last.timestamp:1e3,q=Ie(P,"bytesSent"),Y=Ie(P,"headerBytesSent"),J=gt(Ae(q+Y,8,2e7),H);o.push(J);const z=gt(Ae(q,8,2e7),H);l.push(z);const Z=gt(Ae(Y,8,2e7),H);d.push(Z);const ee=Ie(P,"packetsSent"),ge=gt(ee,H);h.push(ge);const D=Ie(P,"packetsLost"),x=gt(D,H);p.push(x);const L=Xt(D,ee);if(u.push(L),n)(de=P._source)!=null&&de.audioLevel&&f.push(fn(P._source.audioLevel)),m.push(0);else{b.push(Sn(P,"totalEncodeTime")),S.push(Yt((Pe=P._source)==null?void 0:Pe.framesPerSecond,100)),v.push(Yt((K=P._source)==null?void 0:K.framesPerSecond,100)),R.push(Yt(P.framesPerSecond,100)),w.push(Yt((me=P._source)==null?void 0:me.height,4400)),y.push(Yt((Me=P._source)==null?void 0:Me.width,7700)),A.push(Yt(P.frameHeight,4400)),_.push(Yt(P.frameWidth,7700));const _e=Ie(P,"totalPacketSendDelay");E.push(Ae(_e,1/(D||1),2e3));const ke=Ie(P,"qpSum");T.push(Ae(ke,1/(P.framesPerSecond||1),51)),k.push(0)}}),c.sbr=o.join(","),c.mbrs=l.join(","),c.pbrs=d.join(","),c.ps=h.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=R.join(","),c.ih=w.join(","),c.iw=y.join(","),c.sh=A.join(","),c.sw=_.join(","),c.sd=E.join(","),c.aqp=T.join(","),c.caf=k.join(","),c.can=k.join(","),c.cav=l.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,rmtid:"",args:this.data2String(G({calid:a,tckid:t,rmtid:"",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=[],l=[],d=[],h=[],p=[],u=[],f=[],m=[],b=[],S=[],v=[],R=[],w=[],y=[],A=[],_=[],E=[],T=[],k=[],P=[],H=[],q=[],Y=[],J=[],z=[],Z=[],ee=[],ge=[],D=[],x=[],L=[],O=[],de=[],Pe=[];try{r.forEach(K=>{var ue,We;if(!K||!K.timestamp)return;const me=(ue=K._last)!=null&&ue.timestamp?K.timestamp-K._last.timestamp:1e3,Me=Ie(K,"bytesReceived"),_e=Ie(K,"headerBytesReceived"),ke=gt(Ae(Me+_e,8,2e7),me);o.push(ke);const fe=gt(Ae(Me,8,2e7),me);l.push(fe);const we=gt(Ae(_e,8,2e7),me);d.push(we);const he=Ie(K,"packetsReceived"),De=gt(he,me);h.push(De);const ye=Ie(K,"packetsLost"),qe=gt(ye,me);p.push(qe);const st=Xt(ye,he);u.push(st);const ne=Ie(K,"jitterBufferDelay"),re=Ie(K,"jitterBufferEmittedCount");if(K.jitterBufferDelay&&K.jitterBufferEmittedCount){const Q=Ae(ne,1e3/re,1e4);f.push(Q)}else f.push(0);const ie=Ie(K,"fecPacketsReceived");R.push(Xt(ie,he));const Se=Ie(K,"retransmittedPacketsReceived"),Ve=he+ye-Se;if(b.push(Xt(he-Se,Ve)),S.push(Xt(ye,Ve)),m.push(Xt(Se,Ve)),v.push(Ve),de.push(0),Pe.push(""),n){y.push(fn(K.audioLevel));const Q=((xe,bt)=>{var Tt,vt,jt;return(((Tt=xe==null?void 0:xe._source)==null?void 0:Tt[bt])||0)-(((jt=(vt=xe==null?void 0:xe._last)==null?void 0:vt._source)==null?void 0:jt[bt])||0)})(K,"synthesizedSamplesEvents");A.push(Q);const Le=Sn(K,"synthesizedSamplesDuration");_.push(Le);const at=Xt(Le,me);w.push(at),E.push(0)}else{const Q=(We=K._last)!=null&&We.totalInterFrameDelay?K.totalInterFrameDelay-K._last.totalInterFrameDelay:0;T.push(Ae(Q,1e3/(K.framesDecoded||30),500)),k.push(Ae(K.framesPerSecond,1,100)),P.push(Ie(K,"framesReceived")),O.push(Ie(K,"framesRendered")),H.push(Ae(K.frameHeight,1,4400)),q.push(Ae(K.frameWidth,1,7700));const Le=Ie(K,"totalProcessingDelay");Y.push(Ae(Le,1e3/(K.framesDecoded||30),12e4));const at=Ie(K,"nackCount");z.push(at);const xe=Ie(K,"pliCount");J.push(xe);const bt=Ie(K,"qpSum");Z.push(Ae(bt,1/(K.framesPerSecond||1),51)),ee.push(Ae(K.framesDropped));const Tt=Ie(K,"totalFreezesDuration");ge.push(Ae(Tt,1e3,3e4));const vt=Ie(K,"jitterBufferEmittedCount"),jt=Ie(K,"jitterBufferDelay");jt&&vt?D.push(Ae(jt,1e3/vt,3e4)):D.push(0);const Pi=Ie(K,"jitterBufferTargetDelay");Pi&&vt?x.push(Ae(Pi,1e3/vt,3e4)):x.push(0);const qi=Ie(K,"jitterBufferMinimumDelay");qi&&vt?L.push(Ae(qi,1e3/vt,3e4)):L.push(0)}}),c.rbr=o.join(","),c.mbrs=l.join(","),c.pbrs=d.join(","),c.pr=h.join(","),c.pl=p.join(","),c.plr=u.join(","),c.jd=f.join(","),c.fecr=R.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=_.join(",")):(c.dm=T.join(","),c.dfps=k.join(","),c.rfps=P.join(","),c.rh=H.join(","),c.rw=q.join(","),c.fpt=Pe.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=ge.join(","),c.cdm=D.join(","),c.tdm=x.join(","),c.pdm=L.join(","),c.ofps=O.join(","),c.dfbd=ee.join(","))}catch(K){}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=[],l=[],d=[],h=[];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(gt(Ae(u.bytesSent,8,2e7),m,25e6)),r.push(gt(Ae(u.bytesReceived,8,2e7),m,25e6)),n.push(0),c.push(0),f%5==0&&(o.push(""),l.push(""),d.push(""),h.push(""))});const p={ctm:Math.floor(a[0].timestamp||0),rtt:e.join(","),bsps:i.join(","),brps:r.join(","),cpu:o.join(","),mem:l.join(","),sysmem:d.join(","),systotalmem:h.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:l={}}=e||{};if(Object.keys(t).length===0)return;let d=0;d=Object.keys(l).length?(c.vTotalCost||0)+(c.upRTTHalf||0)+(l.totalCost||0)+(o.downRTTHalf||0)+(o.vTotalCost||0):(c.vEncPlugCost||0)+((c.timestampRecv||0)-(c.timestamp||0))+(o.vJitterBufferDelay||0)+(o.vDecPlugCost||0);const h={};let p=0;for(let m=0;m<10;m++){const b=`ngxRtcSeiCumulativeDelayKeyInternalRttHalf_${m}`,S=`ngxRtcSeiCumulativeDelayKeyGrtnNodeBefPacer_${m}`,v=`ngxRtcSeiCumulativeDelayKeyGrtnNodePacerCost_${m}`;if(!l.hasOwnProperty(b))break;p+=l[b]||0,p+=l[S]||0,p+=l[v]||0,h[`_gnd${m}`]=`gnd[${m}]: {${this.data2String({gnirh:l[b]||0,gnbp:l[S]||0,gnpc:l[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(yt(G({tdlms:d+(t.aiagenttotalcost||0),_:`aiqud:{${this.data2String(yt(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:l.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},h),{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 h,p;const{start:i,rs:r=0,re:n=0}=e,c=Date.now()-i,o=n-r;let l=0;r&&(l=r-i);let d=0;n&&(d=n-r),this.log({evetid:10010,args:this.data2String({sesid:((h=this.authInfo)==null?void 0:h.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:l,iptc:d,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,l,d,h,p){this.log({evetid:a?10032:10030,calid:t,tm:p,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()-h,pctid:l,pubtid:d,isvp:0,isarecording:0,isad:0,isdc:0,pubretry:0,pbrttimes:0})})}reportPublishFirstPacket(a,e,t,i,r,n,c,o,l){const d=Date.now();this.log({evetid:a?10033:10031,calid:e,args:this.data2String({calid:e,fpst:d-t,tckid:n,est:t,pctid:c,pubtid:o,totaltm:d-r,jorm:l===_t.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,l,d,h){this.log({evetid:10050,calid:a,rmtid:e,tm:h,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:l,isvp:0,isaplaying:0,isad:0,isdc:0,subretry:0,sbrttimes:0},d))})}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")},l=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(l)})}log(a){a&&(a.tm=a.tm||new Date().getTime(),N.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(Ci,"staticClient");let $r=Ci;const hi=class hi extends se{constructor(e){super();g(this,"ws");g(this,"socketStatus",0);g(this,"wsUrl","");g(this,"lastConnectStartTime",0);g(this,"connectRetryMinTimeGap",5e3);g(this,"shouldReconnect",!0);g(this,"connectRetryCount",0);g(this,"gotErr",!1);g(this,"closedByInvoke",!0);g(this,"isReconnecting",!1);g(this,"networkAvailableChecked",!0);g(this,"reconnectTimeoutId",0);e&&(this.connectRetryMinTimeGap=e),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()}markShouldReconnect(e){this.shouldReconnect=e}reconnect(){this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=0),this.emit("onWillReconnect"),this.shouldReconnect?(this.emit("onReconnectStart"),this.isReconnecting=!0,this.initWebSocket()):this.emit("onConnectFail")}onOpen(e){N.info(`[${hi.logName}]`,"onOpen"),this.socketStatus=2,this.connectRetryCount=0,this.shouldReconnect=!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&&Ne.isNetworkAvailable().then(t=>{t&&console.error(hi.logName,"onError, Network is available, token may be invalid")})}onClose(e){return I(this,null,function*(){if(this.closedByInvoke)this.socketStatus=0;else{if(N.info(`[${hi.logName}]`,`onClose, code: ${e.code}, reason: ${e.reason}, status: ${status}, retryCount: ${this.connectRetryCount}`),(yield Ne.isNetworkAvailable())&&!this.networkAvailableChecked)return this.reconnect(),void(this.networkAvailableChecked=!0);if(this.connectRetryCount||this.emit("onNetworkError"),!this.reconnectTimeoutId){this.connectRetryCount+=1;const t=Date.now()-this.lastConnectStartTime;t>=this.connectRetryMinTimeGap?this.reconnect():this.reconnectTimeoutId=window.setTimeout(()=>{this.reconnect()},this.connectRetryMinTimeGap-Math.max(0,t))}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(hi,"logName","Socket");let Kr=hi;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,"packageCreator");g(this,"keepAliveTimer",0);g(this,"lastKeepAliveResponseTime",0);g(this,"maxConnectRetryDuration",90);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.packageCreator=new Ui(e,t),this.channelProfile=i,this.clientRole=r,this.slsReporter=n,c&&(this.maxConnectRetryDuration=c),this.wsClient=new Kr,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("onWillReconnect",this.onWillReconnect.bind(this)),this.wsClient.on("onReconnectStart",this.onReconnectStart.bind(this)),this.wsClient.on("onReconnectFail",this.onReconnectFail.bind(this))}get retryCount(){return this.wsClient.connectRetryCount}destroy(){this.lastKeepAliveResponseTime=0,this.close()}start(e,t){this.joinChannelExtraData=t,this.wsClient.start(e)}startKeepAlive(){this.keepAliveTimer===0&&(this.keepAliveTimer=window.setInterval(()=>{let e=this.packageCreator.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.packageCreator.createLeavePackage();this.sendPackage(e)}reportStatus(e){let t=this.packageCreator.createStatusPackage(e);this.sendPackage(t)}publish(e){const l=e,{l1ip:t}=l,i=Mt(l,["l1ip"]);let r=this.packageCreator.createPublishPackage();r.data.users=[],r.data.l1ip=t,i.subscribe.signal=this.wsClient.connectUrl;const{tracks:n,resume:c}=i;let o="7.2.0";o&&(o=o.split("-")[0]),n.forEach(d=>{const{codec:h,ssrc:p}=d;d.userdata=JSON.stringify({sdk_version:o,codec:h}),d.ssrc=`${p}`,c&&(d.attr={reason:"reconnect"})}),r.data.users.push(i),this.sendPackage(r)}roleUpdate(e){let t=this.packageCreator.createRoleUpdatePackage();t.data.clientrole=e,this.sendPackage(t)}refreshUrl(e){const t=this.packageCreator.createRefreshUrlPackage();t.data=G(yt(G({},t.data),{sessionid:t.header.sessionid}),e),this.sendPackage(t)}refreshAuthInfo(e){this.authInfo=e,this.packageCreator.refreshAuthInfo(e)}close(){N.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){[Ue.KEEPALIVE,Ue.RECONNECT,Ue.JOINCHANNEL].includes(e.msgtype)||this.packageCache.set(e.tid,e),this.wsClient.send(e),e.msgtype!==Ue.KEEPALIVE&&this.slsReporter.reportRoomServerEvent(!0,e.msgtype,e.tid,e)}updateReconnectData(e){this.reconnectData=e}onOpen(){if(N.info(`[${ct.logName}] onOpen`),this.isFirstConnect){let e=this.packageCreator.createJoinPackage(this.joinChannelExtraData);e.data.configure={channelprofile:this.channelProfile},this.channelProfile!==kt.AliRtcSdkInteractiveLive&&this.channelProfile!==kt.AliRtcSdkInteractiveWithLowLatencyLive||(e.data.configure.clientrole=this.clientRole),this.sendPackage(e)}else{this.stopKeepAlive();const e=this.packageCreator.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)!==Ue.KEEPALIVE&&this.slsReporter.reportRoomServerEvent(!1,t.msgtype,t.tid,t)}catch(t){N.warn(`[${ct.logName}] onMessage err`,t,e)}}onError(e){N.warn(`[${ct.logName}] onError`,e),this.isFirstConnect&&this.onConnectFail()}onConnectFail(){N.warn(`[${ct.logName}] onConnectFail`);const e=new V(U.ERR_INNER,"Signaling connect failed.");this.isFirstConnect?this.emit("onJoinChannelResult",e):this.emit("onConnectFail",e)}onAuthInvalid(){N.warn(`[${ct.logName}] onAuthInvalid`),this.isFirstConnect&&this.emit("onAuthInvalid")}onNetworkError(){N.warn(`[${ct.logName}] onNetworkError`);const e=new V(U.ERR_INNER,"Network error, signaling connect failed.");this.emit("onNetworkError",e)}onClose(e){N.info(`[${ct.logName}] onClose`,e),this.stopKeepAlive()}onKeepAliveRsp(){this.emit("onKeepAliveRsp"),this.lastKeepAliveResponseTime=Date.now(),this.checkAlive()}onWillReconnect(){this.lastKeepAliveResponseTime||(this.lastKeepAliveResponseTime=Date.now()),Date.now()-this.lastKeepAliveResponseTime>1e3*this.maxConnectRetryDuration&&this.wsClient.markShouldReconnect(!1)}onReconnectStart(){this.emit("onReconnectStart")}onReconnectFail(){this.emit("onReconnectFail",new V(U.ERR_INNER,"signaling reconnect failed."))}checkAlive(){window.clearTimeout(this.aliveChecker),this.aliveChecker=window.setTimeout(()=>{N.info(`[${ct.logName}] not alive, reconnect`),this.stopKeepAlive(),this.emit("onReconnectStart"),this.wsClient.reconnect()},15e3)}onRecvMessage(e){switch(e.msgtype!==Ue.KEEPALIVE&&N.info(`[${ct.logName}] recv msg: ${e.msgtype}`),e.msgtype){case Ue.JOINCHANNEL:this.onJoinResult(e);break;case Ue.KEEPALIVE:this.onKeepAliveRsp();break;case Ue.PUBLISH:this.onPublishResult(e);break;case Ue.NOTIFYJOIN:this.onNotifyJoin(e);break;case Ue.NOTIFYSTATUS:this.onNotifyStatus(e);break;case Ue.LEAVECHANNEL:this.onLeaveResult(e);break;case Ue.NOTIFYLEAVE:this.onNotifyLeave(e);break;case Ue.NOTIFYPUBLISH:this.onNotifyPublish(e);break;case Ue.STATUSREPORT:this.onStatusReport(e);break;case Ue.BYE:this.onBye(e);break;case Ue.ROLEUPDATE:this.onRoleUpdateResult(e);break;case Ue.REFRESHURL:this.onRefreshUrlResult(e);break;case Ue.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 V(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.packageCreator.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.packageCreator.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.packageCreator.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.packageCreator.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 Jr=ct;var Ic=Object.defineProperty,Tc=Object.getOwnPropertyDescriptor,Gr=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?Tc(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&&Ic(a,e,r),r};const Gi=(Ze=class extends se{constructor(e,t,i,r=mt.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===mt.pre?ri.pre:ri.prod;this.roomServerUri=`wss://${n}/roomserver/v1/ws`}updateReconnectData(e){var t;this.reconnectData=e,(t=this.messageCenter)==null||t.updateReconnectData(this.reconnectData)}reset(){N.info("[roomsig] reset"),this.messageCenter&&(this.messageCenter.destroy(),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 Jr(e,t,this.channelProfile,this.clientRole,this.slsReporter,i),this.initMessageCenter(),this.messageCenter.once("onJoinChannelResult",d=>{var h,p,u;if(N.info(`[${Ze.logName}]`,"join result: ",d),o.taskretrynum=((h=this.messageCenter)==null?void 0:h.retryCount)||0,d.code==200){(p=this.messageCenter)==null||p.sendPkgCache(),(u=this.messageCenter)==null||u.startKeepAlive();let f=d.data;f.tid=d.tid,f.users=d.data.users,f.timestamp=d.timestamp,o.est&&(o.joinconnecttc=Date.now()-o.est),this.slsReporter.reportJoinConnection(o),n(f)}else this.reset(),c(this.handleSignalError(d.code,d.reason,U.ERR_JOIN_CHANNEL_FAILED))}),this.messageCenter.once("onAuthInvalid",()=>{this.reset(),c(new V(U.ERR_JOIN_BAD_TOKEN,"join failed because authentication failed"))}),N.info(`[${Ze.logName}]`,"start ws connecting roomserver and auto join when connected");const l={appid:this.authInfo.appId,channelid:this.authInfo.channelId,userid:this.authInfo.userId,nonce:this.authInfo.nonce||"",timestamp:this.authInfo.timestamp,token:this.authInfo.token,authtype:"app",tid:lt()};e.role&&(l.tokenrole=e.role),o.est=Date.now(),this.messageCenter.start(this.roomServerUri+"?"+Ne.queryingParam(l),r)})})}leave(){return N.info("[roomsig] leave .."),new Promise((e,t)=>{this.messageCenter?(this.messageCenter.on("onLeaveResult",(i,r)=>{N.info(`[${Ze.logName}]`,"recv leave response "+i),i===200?(this.updateReconnectData(),this.reset(),e({tid:r})):t(this.handleSignalError(i,"leave error"))}),N.info(`[${Ze.logName}]`,"send leave request"),this.messageCenter.leave()):(N.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)=>{N.info(`[${Ze.logName}]`,"recv pubish response "+n),n===200?(this.updateReconnectData(yt(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=lt()),N.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,l;N.info(`[${Ze.logName}]`,"recv role update response "+r),r===200?((l=(o=this.reconnectData)==null?void 0:o.role)!=null&&l.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 N.info(`[${Ze.logName}]`,"refreshUrl .."),new Promise((t,i)=>{this.messageCenter?(this.messageCenter.on("onRefreshUrlResult",r=>{const{code:n,description:c,data:o={}}=r||{};N.info("recv refresh url response "+n),n===200?t(o):i(this.handleSignalError(n,`refresh url error, ${c}`))}),N.info("send refresh url request"),this.messageCenter.refreshUrl(e)):i(this.handleSignalError(-1,"refresh url error, no message center"))})}reportStatus(e){return N.info(`[${Ze.logName}]`,"reportStatus "+e),new Promise((t,i)=>{this.messageCenter?(this.messageCenter.once("onStatusReport",(r,n)=>{r===200?t():i(new V(r,n))}),this.messageCenter.reportStatus(e)):i(new V(-1,"No messageCenter"))})}handleSignalError(e,t,i=U.ERR_INNER){return new V(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,l,d,h,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")}),(l=this.messageCenter)==null||l.on("onReconnectSuccess",m=>{this.emit("onReconnectSuccess",m)}),(d=this.messageCenter)==null||d.on("onReconnectFail",m=>{this.emit("onReconnectFail",m)}),(h=this.messageCenter)==null||h.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);Gr([C()],Gi.prototype,"join",1),Gr([C()],Gi.prototype,"publish",1),Gr([C()],Gi.prototype,"roleUpdate",1);let Cc=Gi;const kc=6e5,ki=class ki 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:l}=this.authInfo;let d="https://gw.rtn.aliyuncs.com";this.env===mt.pre&&(d="https://pgw.rtn.aliyuncs.com");const h=`${d}/gslb/v1/stsupdate?appid=${e}&channelid=${t}&userid=${i}&nonce=${r}&token=${n}×tamp=${c}&session=${o}${l?`&tokenrole=${l}`:""}&slstoken=true&osstoken=true&tokensid=false`,p=Date.now();fetch(h).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),N.event(`[${ki.logName}]`,"getToken",b,S)}this.slsReporter.reportSTSResult(200,p)}).catch(u=>{this.slsReporter.reportSTSResult(-1,p),N.error(`[${ki.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()},kc)}clear(){this.timer&&clearInterval(this.timer)}};g(ki,"logName","StsManager");let qr=ki;var Pc=Object.defineProperty,Dc=Object.getOwnPropertyDescriptor;class Xr extends se{constructor(e,t,i,r=mt.prod){super();g(this,"signaling");g(this,"authInfo");g(this,"userName");g(this,"channelProfile");g(this,"clientRole");g(this,"env",mt.prod);g(this,"maxSignalingReconnectDuration");g(this,"stsManager");g(this,"slsReporter");this.channelProfile=e,this.clientRole=t,this.env=r,this.slsReporter=i,this.stsManager=new qr(i,r)}reset(){var e;N.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.maxSignalingReconnectDuration=i,this.userName=t,new Promise((c,o)=>{this.signaling?o(new V(U.ERR_JOIN_ALREADY_JOINED,"already joined")):(N.info("[signalingmanager] create signaling"),this.signaling=new Cc(this.channelProfile,this.clientRole,this.slsReporter,this.env),this.initSignaling(),r&&(r.rs=Date.now()),this.signaling.join(e,t,i,n).then(l=>{this.authInfo=e,r&&(r.re=Date.now()),c(l)}).catch(l=>{this.reset(),o(l)}),this.stsManager.startSTSUpdate(e))})}retryJoin(){const e=this.authInfo;this.reset(),e&&this.join(e,this.userName,this.maxSignalingReconnectDuration)}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 V(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 V(-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 V(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,l,d,h,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)),(l=this.signaling)==null||l.on("onReconnectSuccess",this.onReconnectSuccess.bind(this)),(d=this.signaling)==null||d.on("onReconnectFail",this.onReconnectFail.bind(this)),(h=this.signaling)==null||h.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(Xr,"logName","SignalingManager"),((s,a,e,t)=>{for(var i,r=t>1?void 0:t?Dc(a,e):a,n=s.length-1;n>=0;n--)(i=s[n])&&(r=(t?i(a,e,r):i(r))||r);t&&r&&Pc(a,e,r)})([C(B)],Xr.prototype,"publish",1);class bn{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 vn{constructor(a,e,t){g(this,"userId");g(this,"streamType");g(this,"sourceType");this.userId=a,this.streamType=e,this.sourceType=t}}class yn{constructor(a,e,t,i=0,r=16777215,n=Ii.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:Fr(this.fontColor),zorder:this.zOrder}}}var Rn=(s=>(s[s.NOT_DISPLAY=0]="NOT_DISPLAY",s[s.ALWAYS=1]="ALWAYS",s[s.WHEN_NO_VIDEO=2]="WHEN_NO_VIDEO",s))(Rn||{});class Yr{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(Yr,"DisplayType",Rn);class An{constructor(a,e,t,i,r=0,n=16777215,c=Ii.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:Fr(this.fontColor),zorder:this.zOrder}}}class _n{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",Ei.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&&wi[this.sourceType]?r.sourcetype=wi[this.sourceType]:r.sourcetype=wi[li.LiveTranscodingCamera],this.segmentType&&i===Ki.LiveTranscodingVirtualBackground?r.segmenttype=this.segmentType:r.segmenttype=Ei.LiveTranscodingNoBody,r}}class Mc{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=`
|
|
134
|
+
`+n),console.error("Failed log data:",s))}},new Promise((n,c)=>{var o=h=>{try{d(r.next(h))}catch(p){c(p)}},l=h=>{try{d(r.throw(h))}catch(p){c(p)}},d=h=>h.done?n(h.value):Promise.resolve(h.value).then(o,l);d((r=r.apply(t,i)).next())});var t,i,r}class un extends ca{constructor(a){super(Object.assign({},a,{installUnloadHook:e=>{window.addEventListener("beforeunload",()=>{e()})},sendPayload:(e,t)=>{wc(e,t)}}))}useStsPlugin(a){this.getOpt().sendPayload=(e,t)=>{Ec(e,t,a)},this.overwriteTransString(a)}}Mi(window,"SLS_Tracker",un);const Zt=class Zt{constructor(){g(this,"ntpClock");this.ntpClock=new X.AliRTS.Clock}static getInstance(){return Zt.instance||(Zt.instance=new Zt),Zt.instance}now(){return this.ntpClock.now()}};g(Zt,"instance");let zr=Zt;const pn=()=>zr.getInstance(),{BrowserUtil:Wr,SystenUtil:gn}=X.AliRTS;class mn{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=pn()}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 un({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=Zi(t);e.useStsPlugin(i),this.tracker=e,this.msgCacheArr.forEach((r,n)=>{var c,o;(o=this.tracker)==null||o.send(G(yt(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(yt(G({bt:Wr.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=lt(),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:gn.systemName,osv:gn.systemVersion,deb:Co(),den:Eo(),udid:e,sdkvrs:Ni,acs:"Unknown",cput:oa(),dm:`${window.location.protocol}//${window.location.host}`,bt:Wr.browserName,bv:Wr.browserVersion,envir:"PRODUCT",args:"",instid:lt()})}}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)))},gt=(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))))},Xt=(s,a)=>{if(a===0||!a)return"0.00";let e=s;return(!e||e<0)&&(e=0),(e/a*100).toFixed(2)},fn=s=>s>=0&&s<=1?Ae(Math.floor(32767*s),1,32767):0,Ie=(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},Sn=(s,a)=>Ae(Ie(s,a),1e3,1e4),Yt=(s,a=2e7)=>Ae(s,1,a),Ci=class Ci{constructor(a){g(this,"engine");g(this,"logClient");g(this,"authInfo");g(this,"ntpClock");g(this,"customFields",{});this.logClient=new mn,this.engine=a,this.ntpClock=pn()}static getLogClient(){return this.staticClient||(this.staticClient=new mn),this.staticClient}static reportOSSUpload(a,e,t=0){Ci.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),Ci.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,rmtid:"",args:this.data2String(G({calid:a,tckid:e||"audio3a",rmtid:"",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=[],l=[],d=[],h=[],p=[],u=[],f=[],m=[],b=[],S=[],v=[],R=[],w=[],y=[],A=[],_=[],E=[],T=[],k=[];try{if(r.forEach(P=>{var O,de,Pe,K,me,Me;if(!P||!P.timestamp)return;const H=(O=P._last)!=null&&O.timestamp?P.timestamp-P._last.timestamp:1e3,q=Ie(P,"bytesSent"),Y=Ie(P,"headerBytesSent"),J=gt(Ae(q+Y,8,2e7),H);o.push(J);const z=gt(Ae(q,8,2e7),H);l.push(z);const Z=gt(Ae(Y,8,2e7),H);d.push(Z);const ee=Ie(P,"packetsSent"),ge=gt(ee,H);h.push(ge);const D=Ie(P,"packetsLost"),x=gt(D,H);p.push(x);const L=Xt(D,ee);if(u.push(L),n)(de=P._source)!=null&&de.audioLevel&&f.push(fn(P._source.audioLevel)),m.push(0);else{b.push(Sn(P,"totalEncodeTime")),S.push(Yt((Pe=P._source)==null?void 0:Pe.framesPerSecond,100)),v.push(Yt((K=P._source)==null?void 0:K.framesPerSecond,100)),R.push(Yt(P.framesPerSecond,100)),w.push(Yt((me=P._source)==null?void 0:me.height,4400)),y.push(Yt((Me=P._source)==null?void 0:Me.width,7700)),A.push(Yt(P.frameHeight,4400)),_.push(Yt(P.frameWidth,7700));const _e=Ie(P,"totalPacketSendDelay");E.push(Ae(_e,1/(D||1),2e3));const ke=Ie(P,"qpSum");T.push(Ae(ke,1/(P.framesPerSecond||1),51)),k.push(0)}}),c.sbr=o.join(","),c.mbrs=l.join(","),c.pbrs=d.join(","),c.ps=h.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=R.join(","),c.ih=w.join(","),c.iw=y.join(","),c.sh=A.join(","),c.sw=_.join(","),c.sd=E.join(","),c.aqp=T.join(","),c.caf=k.join(","),c.can=k.join(","),c.cav=l.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,rmtid:"",args:this.data2String(G({calid:a,tckid:t,rmtid:"",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=[],l=[],d=[],h=[],p=[],u=[],f=[],m=[],b=[],S=[],v=[],R=[],w=[],y=[],A=[],_=[],E=[],T=[],k=[],P=[],H=[],q=[],Y=[],J=[],z=[],Z=[],ee=[],ge=[],D=[],x=[],L=[],O=[],de=[],Pe=[];try{r.forEach(K=>{var ue,We;if(!K||!K.timestamp)return;const me=(ue=K._last)!=null&&ue.timestamp?K.timestamp-K._last.timestamp:1e3,Me=Ie(K,"bytesReceived"),_e=Ie(K,"headerBytesReceived"),ke=gt(Ae(Me+_e,8,2e7),me);o.push(ke);const fe=gt(Ae(Me,8,2e7),me);l.push(fe);const we=gt(Ae(_e,8,2e7),me);d.push(we);const he=Ie(K,"packetsReceived"),De=gt(he,me);h.push(De);const ye=Ie(K,"packetsLost"),qe=gt(ye,me);p.push(qe);const st=Xt(ye,he);u.push(st);const ne=Ie(K,"jitterBufferDelay"),re=Ie(K,"jitterBufferEmittedCount");if(K.jitterBufferDelay&&K.jitterBufferEmittedCount){const Q=Ae(ne,1e3/re,1e4);f.push(Q)}else f.push(0);const ie=Ie(K,"fecPacketsReceived");R.push(Xt(ie,he));const Se=Ie(K,"retransmittedPacketsReceived"),Ve=he+ye-Se;if(b.push(Xt(he-Se,Ve)),S.push(Xt(ye,Ve)),m.push(Xt(Se,Ve)),v.push(Ve),de.push(0),Pe.push(""),n){y.push(fn(K.audioLevel));const Q=((xe,bt)=>{var Tt,vt,jt;return(((Tt=xe==null?void 0:xe._source)==null?void 0:Tt[bt])||0)-(((jt=(vt=xe==null?void 0:xe._last)==null?void 0:vt._source)==null?void 0:jt[bt])||0)})(K,"synthesizedSamplesEvents");A.push(Q);const Le=Sn(K,"synthesizedSamplesDuration");_.push(Le);const at=Xt(Le,me);w.push(at),E.push(0)}else{const Q=(We=K._last)!=null&&We.totalInterFrameDelay?K.totalInterFrameDelay-K._last.totalInterFrameDelay:0;T.push(Ae(Q,1e3/(K.framesDecoded||30),500)),k.push(Ae(K.framesPerSecond,1,100)),P.push(Ie(K,"framesReceived")),O.push(Ie(K,"framesRendered")),H.push(Ae(K.frameHeight,1,4400)),q.push(Ae(K.frameWidth,1,7700));const Le=Ie(K,"totalProcessingDelay");Y.push(Ae(Le,1e3/(K.framesDecoded||30),12e4));const at=Ie(K,"nackCount");z.push(at);const xe=Ie(K,"pliCount");J.push(xe);const bt=Ie(K,"qpSum");Z.push(Ae(bt,1/(K.framesPerSecond||1),51)),ee.push(Ae(K.framesDropped));const Tt=Ie(K,"totalFreezesDuration");ge.push(Ae(Tt,1e3,3e4));const vt=Ie(K,"jitterBufferEmittedCount"),jt=Ie(K,"jitterBufferDelay");jt&&vt?D.push(Ae(jt,1e3/vt,3e4)):D.push(0);const Pi=Ie(K,"jitterBufferTargetDelay");Pi&&vt?x.push(Ae(Pi,1e3/vt,3e4)):x.push(0);const qi=Ie(K,"jitterBufferMinimumDelay");qi&&vt?L.push(Ae(qi,1e3/vt,3e4)):L.push(0)}}),c.rbr=o.join(","),c.mbrs=l.join(","),c.pbrs=d.join(","),c.pr=h.join(","),c.pl=p.join(","),c.plr=u.join(","),c.jd=f.join(","),c.fecr=R.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=_.join(",")):(c.dm=T.join(","),c.dfps=k.join(","),c.rfps=P.join(","),c.rh=H.join(","),c.rw=q.join(","),c.fpt=Pe.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=ge.join(","),c.cdm=D.join(","),c.tdm=x.join(","),c.pdm=L.join(","),c.ofps=O.join(","),c.dfbd=ee.join(","))}catch(K){}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=[],l=[],d=[],h=[];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(gt(Ae(u.bytesSent,8,2e7),m,25e6)),r.push(gt(Ae(u.bytesReceived,8,2e7),m,25e6)),n.push(0),c.push(0),f%5==0&&(o.push(""),l.push(""),d.push(""),h.push(""))});const p={ctm:Math.floor(a[0].timestamp||0),rtt:e.join(","),bsps:i.join(","),brps:r.join(","),cpu:o.join(","),mem:l.join(","),sysmem:d.join(","),systotalmem:h.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:l={}}=e||{};if(Object.keys(t).length===0)return;let d=0;d=Object.keys(l).length?(c.vTotalCost||0)+(c.upRTTHalf||0)+(l.totalCost||0)+(o.downRTTHalf||0)+(o.vTotalCost||0):(c.vEncPlugCost||0)+((c.timestampRecv||0)-(c.timestamp||0))+(o.vJitterBufferDelay||0)+(o.vDecPlugCost||0);const h={};let p=0;for(let m=0;m<10;m++){const b=`ngxRtcSeiCumulativeDelayKeyInternalRttHalf_${m}`,S=`ngxRtcSeiCumulativeDelayKeyGrtnNodeBefPacer_${m}`,v=`ngxRtcSeiCumulativeDelayKeyGrtnNodePacerCost_${m}`;if(!l.hasOwnProperty(b))break;p+=l[b]||0,p+=l[S]||0,p+=l[v]||0,h[`_gnd${m}`]=`gnd[${m}]: {${this.data2String({gnirh:l[b]||0,gnbp:l[S]||0,gnpc:l[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(yt(G({tdlms:d+(t.aiagenttotalcost||0),_:`aiqud:{${this.data2String(yt(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:l.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},h),{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 h,p;const{start:i,rs:r=0,re:n=0}=e,c=Date.now()-i,o=n-r;let l=0;r&&(l=r-i);let d=0;n&&(d=n-r),this.log({evetid:10010,args:this.data2String({sesid:((h=this.authInfo)==null?void 0:h.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:l,iptc:d,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,l,d,h,p){this.log({evetid:a?10032:10030,calid:t,tm:p,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()-h,pctid:l,pubtid:d,isvp:0,isarecording:0,isad:0,isdc:0,pubretry:0,pbrttimes:0})})}reportPublishFirstPacket(a,e,t,i,r,n,c,o,l){const d=Date.now();this.log({evetid:a?10033:10031,calid:e,args:this.data2String({calid:e,fpst:d-t,tckid:n,est:t,pctid:c,pubtid:o,totaltm:d-r,jorm:l===_t.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,l,d,h){this.log({evetid:10050,calid:a,rmtid:e,tm:h,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:l,isvp:0,isaplaying:0,isad:0,isdc:0,subretry:0,sbrttimes:0},d))})}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")},l=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(l)})}log(a){a&&(a.tm=a.tm||new Date().getTime(),N.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(Ci,"staticClient");let $r=Ci;const hi=class hi extends se{constructor(e){super();g(this,"ws");g(this,"socketStatus",0);g(this,"wsUrl","");g(this,"lastConnectStartTime",0);g(this,"connectRetryMinTimeGap",5e3);g(this,"shouldReconnect",!0);g(this,"connectRetryCount",0);g(this,"gotErr",!1);g(this,"closedByInvoke",!0);g(this,"isReconnecting",!1);g(this,"networkAvailableChecked",!0);g(this,"reconnectTimeoutId",0);e&&(this.connectRetryMinTimeGap=e),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()}markShouldReconnect(e){this.shouldReconnect=e}reconnect(){this.reconnectTimeoutId&&(clearTimeout(this.reconnectTimeoutId),this.reconnectTimeoutId=0),this.emit("onWillReconnect"),this.shouldReconnect?(this.emit("onReconnectStart"),this.isReconnecting=!0,this.initWebSocket()):this.emit("onConnectFail")}onOpen(e){N.info(`[${hi.logName}]`,"onOpen"),this.socketStatus=2,this.connectRetryCount=0,this.shouldReconnect=!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&&Ne.isNetworkAvailable().then(t=>{t&&console.error(hi.logName,"onError, Network is available, token may be invalid")})}onClose(e){return I(this,null,function*(){if(this.closedByInvoke)this.socketStatus=0;else{if(N.info(`[${hi.logName}]`,`onClose, code: ${e.code}, reason: ${e.reason}, status: ${status}, retryCount: ${this.connectRetryCount}`),(yield Ne.isNetworkAvailable())&&!this.networkAvailableChecked)return this.reconnect(),void(this.networkAvailableChecked=!0);if(this.connectRetryCount||this.emit("onNetworkError"),!this.reconnectTimeoutId){this.connectRetryCount+=1;const t=Date.now()-this.lastConnectStartTime;t>=this.connectRetryMinTimeGap?this.reconnect():this.reconnectTimeoutId=window.setTimeout(()=>{this.reconnect()},this.connectRetryMinTimeGap-Math.max(0,t))}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(hi,"logName","Socket");let Kr=hi;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,"packageCreator");g(this,"keepAliveTimer",0);g(this,"lastKeepAliveResponseTime",0);g(this,"maxConnectRetryDuration",90);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.packageCreator=new Ui(e,t),this.channelProfile=i,this.clientRole=r,this.slsReporter=n,c&&(this.maxConnectRetryDuration=c),this.wsClient=new Kr,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("onWillReconnect",this.onWillReconnect.bind(this)),this.wsClient.on("onReconnectStart",this.onReconnectStart.bind(this)),this.wsClient.on("onReconnectFail",this.onReconnectFail.bind(this))}get retryCount(){return this.wsClient.connectRetryCount}destroy(){this.lastKeepAliveResponseTime=0,this.close()}start(e,t){this.joinChannelExtraData=t,this.wsClient.start(e)}startKeepAlive(){this.keepAliveTimer===0&&(this.keepAliveTimer=window.setInterval(()=>{let e=this.packageCreator.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.packageCreator.createLeavePackage();this.sendPackage(e)}reportStatus(e){let t=this.packageCreator.createStatusPackage(e);this.sendPackage(t)}publish(e){const l=e,{l1ip:t}=l,i=Mt(l,["l1ip"]);let r=this.packageCreator.createPublishPackage();r.data.users=[],r.data.l1ip=t,i.subscribe.signal=this.wsClient.connectUrl;const{tracks:n,resume:c}=i;let o="7.2.1";o&&(o=o.split("-")[0]),n.forEach(d=>{const{codec:h,ssrc:p}=d;d.userdata=JSON.stringify({sdk_version:o,codec:h}),d.ssrc=`${p}`,c&&(d.attr={reason:"reconnect"})}),r.data.users.push(i),this.sendPackage(r)}roleUpdate(e){let t=this.packageCreator.createRoleUpdatePackage();t.data.clientrole=e,this.sendPackage(t)}refreshUrl(e){const t=this.packageCreator.createRefreshUrlPackage();t.data=G(yt(G({},t.data),{sessionid:t.header.sessionid}),e),this.sendPackage(t)}refreshAuthInfo(e){this.authInfo=e,this.packageCreator.refreshAuthInfo(e)}close(){N.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){[Ue.KEEPALIVE,Ue.RECONNECT,Ue.JOINCHANNEL].includes(e.msgtype)||this.packageCache.set(e.tid,e),this.wsClient.send(e),e.msgtype!==Ue.KEEPALIVE&&this.slsReporter.reportRoomServerEvent(!0,e.msgtype,e.tid,e)}updateReconnectData(e){this.reconnectData=e}onOpen(){if(N.info(`[${ct.logName}] onOpen`),this.isFirstConnect){let e=this.packageCreator.createJoinPackage(this.joinChannelExtraData);e.data.configure={channelprofile:this.channelProfile},this.channelProfile!==kt.AliRtcSdkInteractiveLive&&this.channelProfile!==kt.AliRtcSdkInteractiveWithLowLatencyLive||(e.data.configure.clientrole=this.clientRole),this.sendPackage(e)}else{this.stopKeepAlive();const e=this.packageCreator.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)!==Ue.KEEPALIVE&&this.slsReporter.reportRoomServerEvent(!1,t.msgtype,t.tid,t)}catch(t){N.warn(`[${ct.logName}] onMessage err`,t,e)}}onError(e){N.warn(`[${ct.logName}] onError`,e),this.isFirstConnect&&this.onConnectFail()}onConnectFail(){N.warn(`[${ct.logName}] onConnectFail`);const e=new V(U.ERR_INNER,"Signaling connect failed.");this.isFirstConnect?this.emit("onJoinChannelResult",e):this.emit("onConnectFail",e)}onAuthInvalid(){N.warn(`[${ct.logName}] onAuthInvalid`),this.isFirstConnect&&this.emit("onAuthInvalid")}onNetworkError(){N.warn(`[${ct.logName}] onNetworkError`);const e=new V(U.ERR_INNER,"Network error, signaling connect failed.");this.emit("onNetworkError",e)}onClose(e){N.info(`[${ct.logName}] onClose`,e),this.stopKeepAlive()}onKeepAliveRsp(){this.emit("onKeepAliveRsp"),this.lastKeepAliveResponseTime=Date.now(),this.checkAlive()}onWillReconnect(){this.lastKeepAliveResponseTime||(this.lastKeepAliveResponseTime=Date.now()),Date.now()-this.lastKeepAliveResponseTime>1e3*this.maxConnectRetryDuration&&this.wsClient.markShouldReconnect(!1)}onReconnectStart(){this.emit("onReconnectStart")}onReconnectFail(){this.emit("onReconnectFail",new V(U.ERR_INNER,"signaling reconnect failed."))}checkAlive(){window.clearTimeout(this.aliveChecker),this.aliveChecker=window.setTimeout(()=>{N.info(`[${ct.logName}] not alive, reconnect`),this.stopKeepAlive(),this.emit("onReconnectStart"),this.wsClient.reconnect()},15e3)}onRecvMessage(e){switch(e.msgtype!==Ue.KEEPALIVE&&N.info(`[${ct.logName}] recv msg: ${e.msgtype}`),e.msgtype){case Ue.JOINCHANNEL:this.onJoinResult(e);break;case Ue.KEEPALIVE:this.onKeepAliveRsp();break;case Ue.PUBLISH:this.onPublishResult(e);break;case Ue.NOTIFYJOIN:this.onNotifyJoin(e);break;case Ue.NOTIFYSTATUS:this.onNotifyStatus(e);break;case Ue.LEAVECHANNEL:this.onLeaveResult(e);break;case Ue.NOTIFYLEAVE:this.onNotifyLeave(e);break;case Ue.NOTIFYPUBLISH:this.onNotifyPublish(e);break;case Ue.STATUSREPORT:this.onStatusReport(e);break;case Ue.BYE:this.onBye(e);break;case Ue.ROLEUPDATE:this.onRoleUpdateResult(e);break;case Ue.REFRESHURL:this.onRefreshUrlResult(e);break;case Ue.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 V(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.packageCreator.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.packageCreator.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.packageCreator.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.packageCreator.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 Jr=ct;var Ic=Object.defineProperty,Tc=Object.getOwnPropertyDescriptor,Gr=(s,a,e,t)=>{for(var i,r=t>1?void 0:t?Tc(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&&Ic(a,e,r),r};const Gi=(Ze=class extends se{constructor(e,t,i,r=mt.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===mt.pre?ri.pre:ri.prod;this.roomServerUri=`wss://${n}/roomserver/v1/ws`}updateReconnectData(e){var t;this.reconnectData=e,(t=this.messageCenter)==null||t.updateReconnectData(this.reconnectData)}reset(){N.info("[roomsig] reset"),this.messageCenter&&(this.messageCenter.destroy(),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 Jr(e,t,this.channelProfile,this.clientRole,this.slsReporter,i),this.initMessageCenter(),this.messageCenter.once("onJoinChannelResult",d=>{var h,p,u;if(N.info(`[${Ze.logName}]`,"join result: ",d),o.taskretrynum=((h=this.messageCenter)==null?void 0:h.retryCount)||0,d.code==200){(p=this.messageCenter)==null||p.sendPkgCache(),(u=this.messageCenter)==null||u.startKeepAlive();let f=d.data;f.tid=d.tid,f.users=d.data.users,f.timestamp=d.timestamp,o.est&&(o.joinconnecttc=Date.now()-o.est),this.slsReporter.reportJoinConnection(o),n(f)}else this.reset(),c(this.handleSignalError(d.code,d.reason,U.ERR_JOIN_CHANNEL_FAILED))}),this.messageCenter.once("onAuthInvalid",()=>{this.reset(),c(new V(U.ERR_JOIN_BAD_TOKEN,"join failed because authentication failed"))}),N.info(`[${Ze.logName}]`,"start ws connecting roomserver and auto join when connected");const l={appid:this.authInfo.appId,channelid:this.authInfo.channelId,userid:this.authInfo.userId,nonce:this.authInfo.nonce||"",timestamp:this.authInfo.timestamp,token:this.authInfo.token,authtype:"app",tid:lt()};e.role&&(l.tokenrole=e.role),o.est=Date.now(),this.messageCenter.start(this.roomServerUri+"?"+Ne.queryingParam(l),r)})})}leave(){return N.info("[roomsig] leave .."),new Promise((e,t)=>{this.messageCenter?(this.messageCenter.on("onLeaveResult",(i,r)=>{N.info(`[${Ze.logName}]`,"recv leave response "+i),i===200?(this.updateReconnectData(),this.reset(),e({tid:r})):t(this.handleSignalError(i,"leave error"))}),N.info(`[${Ze.logName}]`,"send leave request"),this.messageCenter.leave()):(N.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)=>{N.info(`[${Ze.logName}]`,"recv pubish response "+n),n===200?(this.updateReconnectData(yt(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=lt()),N.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,l;N.info(`[${Ze.logName}]`,"recv role update response "+r),r===200?((l=(o=this.reconnectData)==null?void 0:o.role)!=null&&l.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 N.info(`[${Ze.logName}]`,"refreshUrl .."),new Promise((t,i)=>{this.messageCenter?(this.messageCenter.on("onRefreshUrlResult",r=>{const{code:n,description:c,data:o={}}=r||{};N.info("recv refresh url response "+n),n===200?t(o):i(this.handleSignalError(n,`refresh url error, ${c}`))}),N.info("send refresh url request"),this.messageCenter.refreshUrl(e)):i(this.handleSignalError(-1,"refresh url error, no message center"))})}reportStatus(e){return N.info(`[${Ze.logName}]`,"reportStatus "+e),new Promise((t,i)=>{this.messageCenter?(this.messageCenter.once("onStatusReport",(r,n)=>{r===200?t():i(new V(r,n))}),this.messageCenter.reportStatus(e)):i(new V(-1,"No messageCenter"))})}handleSignalError(e,t,i=U.ERR_INNER){return new V(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,l,d,h,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")}),(l=this.messageCenter)==null||l.on("onReconnectSuccess",m=>{this.emit("onReconnectSuccess",m)}),(d=this.messageCenter)==null||d.on("onReconnectFail",m=>{this.emit("onReconnectFail",m)}),(h=this.messageCenter)==null||h.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);Gr([C()],Gi.prototype,"join",1),Gr([C()],Gi.prototype,"publish",1),Gr([C()],Gi.prototype,"roleUpdate",1);let Cc=Gi;const kc=6e5,ki=class ki 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:l}=this.authInfo;let d="https://gw.rtn.aliyuncs.com";this.env===mt.pre&&(d="https://pgw.rtn.aliyuncs.com");const h=`${d}/gslb/v1/stsupdate?appid=${e}&channelid=${t}&userid=${i}&nonce=${r}&token=${n}×tamp=${c}&session=${o}${l?`&tokenrole=${l}`:""}&slstoken=true&osstoken=true&tokensid=false`,p=Date.now();fetch(h).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),N.event(`[${ki.logName}]`,"getToken",b,S)}this.slsReporter.reportSTSResult(200,p)}).catch(u=>{this.slsReporter.reportSTSResult(-1,p),N.error(`[${ki.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()},kc)}clear(){this.timer&&clearInterval(this.timer)}};g(ki,"logName","StsManager");let qr=ki;var Pc=Object.defineProperty,Dc=Object.getOwnPropertyDescriptor;class Xr extends se{constructor(e,t,i,r=mt.prod){super();g(this,"signaling");g(this,"authInfo");g(this,"userName");g(this,"channelProfile");g(this,"clientRole");g(this,"env",mt.prod);g(this,"maxSignalingReconnectDuration");g(this,"stsManager");g(this,"slsReporter");this.channelProfile=e,this.clientRole=t,this.env=r,this.slsReporter=i,this.stsManager=new qr(i,r)}reset(){var e;N.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.maxSignalingReconnectDuration=i,this.userName=t,new Promise((c,o)=>{this.signaling?o(new V(U.ERR_JOIN_ALREADY_JOINED,"already joined")):(N.info("[signalingmanager] create signaling"),this.signaling=new Cc(this.channelProfile,this.clientRole,this.slsReporter,this.env),this.initSignaling(),r&&(r.rs=Date.now()),this.signaling.join(e,t,i,n).then(l=>{this.authInfo=e,r&&(r.re=Date.now()),c(l)}).catch(l=>{this.reset(),o(l)}),this.stsManager.startSTSUpdate(e))})}retryJoin(){const e=this.authInfo;this.reset(),e&&this.join(e,this.userName,this.maxSignalingReconnectDuration)}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 V(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 V(-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 V(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,l,d,h,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)),(l=this.signaling)==null||l.on("onReconnectSuccess",this.onReconnectSuccess.bind(this)),(d=this.signaling)==null||d.on("onReconnectFail",this.onReconnectFail.bind(this)),(h=this.signaling)==null||h.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(Xr,"logName","SignalingManager"),((s,a,e,t)=>{for(var i,r=t>1?void 0:t?Dc(a,e):a,n=s.length-1;n>=0;n--)(i=s[n])&&(r=(t?i(a,e,r):i(r))||r);t&&r&&Pc(a,e,r)})([C(B)],Xr.prototype,"publish",1);class bn{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 vn{constructor(a,e,t){g(this,"userId");g(this,"streamType");g(this,"sourceType");this.userId=a,this.streamType=e,this.sourceType=t}}class yn{constructor(a,e,t,i=0,r=16777215,n=Ii.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:Fr(this.fontColor),zorder:this.zOrder}}}var Rn=(s=>(s[s.NOT_DISPLAY=0]="NOT_DISPLAY",s[s.ALWAYS=1]="ALWAYS",s[s.WHEN_NO_VIDEO=2]="WHEN_NO_VIDEO",s))(Rn||{});class Yr{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(Yr,"DisplayType",Rn);class An{constructor(a,e,t,i,r=0,n=16777215,c=Ii.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:Fr(this.fontColor),zorder:this.zOrder}}}class _n{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",Ei.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&&wi[this.sourceType]?r.sourcetype=wi[this.sourceType]:r.sourcetype=wi[li.LiveTranscodingCamera],this.segmentType&&i===Ki.LiveTranscodingVirtualBackground?r.segmenttype=this.segmentType:r.segmenttype=Ei.LiveTranscodingNoBody,r}}class Mc{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=`
|
|
135
135
|
var running = false;
|
|
136
136
|
function tick(){
|
|
137
137
|
postMessage(Date.now());
|