trtc-sdk-v5 5.15.0-beta.4 → 5.15.0-beta.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/debug-dialog.js +1 -1
- package/package.json +1 -1
- package/plugins/cdn-streaming/package.json +1 -1
- package/plugins/chorus/package.json +1 -1
- package/plugins/cross-room/package.json +1 -1
- package/plugins/custom-encryption/package.json +1 -1
- package/plugins/device-detector/package.json +1 -1
- package/plugins/lebplayer/package.json +1 -1
- package/plugins/small-stream-auto-switcher/package.json +1 -1
- package/plugins/video-decoder/package.json +1 -1
- package/plugins/video-effect/basic-beauty/package.json +1 -1
- package/plugins/video-effect/beauty/package.json +1 -1
- package/plugins/video-effect/video-mixer/package.json +1 -1
- package/plugins/video-effect/video-mixer/video-mixer.esm.d.ts +1 -1
- package/plugins/video-effect/video-mixer/video-mixer.esm.js +1 -1
- package/plugins/video-effect/video-mixer/video-mixer.umd.js +1 -1
- package/plugins/video-effect/virtual-background/package.json +1 -1
- package/plugins/video-effect/watermark/package.json +1 -1
- package/plugins/voice-changer/package.json +1 -1
- package/trtc.esm.js +8 -8
- package/trtc.js +1 -1
package/trtc.esm.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
var Z_=Object.create;var ks=Object.defineProperty,K_=Object.defineProperties,mm=Object.getOwnPropertyDescriptor,eg=Object.getOwnPropertyDescriptors,tg=Object.getOwnPropertyNames,na=Object.getOwnPropertySymbols,pm=Object.getPrototypeOf,$d=Object.prototype.hasOwnProperty,fm=Object.prototype.propertyIsEnumerable,ig=Reflect.get;var hr=Math.pow,Hd=(o,i,e)=>i in o?ks(o,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):o[i]=e,O=(o,i)=>{for(var e in i||(i={}))$d.call(i,e)&&Hd(o,e,i[e]);if(na)for(var e of na(i))fm.call(i,e)&&Hd(o,e,i[e]);return o},L=(o,i)=>K_(o,eg(i));var aa=(o,i)=>{var e={};for(var t in o)$d.call(o,t)&&i.indexOf(t)<0&&(e[t]=o[t]);if(o!=null&&na)for(var t of na(o))i.indexOf(t)<0&&fm.call(o,t)&&(e[t]=o[t]);return e};var Ui=(o,i)=>()=>(i||o((i={exports:{}}).exports,i),i.exports),Vi=(o,i)=>{for(var e in i)ks(o,e,{get:i[e],enumerable:!0})},rg=(o,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of tg(i))!$d.call(o,r)&&r!==e&&ks(o,r,{get:()=>i[r],enumerable:!(t=mm(i,r))||t.enumerable});return o};var Ge=(o,i,e)=>(e=o!=null?Z_(pm(o)):{},rg(i||!o||!o.__esModule?ks(e,"default",{value:o,enumerable:!0}):e,o));var M=(o,i,e,t)=>{for(var r=t>1?void 0:t?mm(i,e):i,s=o.length-1,n;s>=0;s--)(n=o[s])&&(r=(t?n(i,e,r):n(r))||r);return t&&r&&ks(i,e,r),r};var d=(o,i,e)=>Hd(o,typeof i!="symbol"?i+"":i,e);var Pe=(o,i,e)=>ig(pm(o),e,i);var p=(o,i,e)=>new Promise((t,r)=>{var s=c=>{try{a(e.next(c))}catch(l){r(l)}},n=c=>{try{a(e.throw(c))}catch(l){r(l)}},a=c=>c.done?t(c.value):Promise.resolve(c.value).then(s,n);a((e=e.apply(o,i)).next())});var at=Ui((PI,Wd)=>{"use strict";var og=Object.prototype.hasOwnProperty,ht="~";function Ps(){}Object.create&&(Ps.prototype=Object.create(null),new Ps().__proto__||(ht=!1));function sg(o,i,e){this.fn=o,this.context=i,this.once=e||!1}function _m(o,i,e,t,r){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new sg(e,t||o,r),n=ht?ht+i:i;return o._events[n]?o._events[n].fn?o._events[n]=[o._events[n],s]:o._events[n].push(s):(o._events[n]=s,o._eventsCount++),o}function ca(o,i){--o._eventsCount===0?o._events=new Ps:delete o._events[i]}function nt(){this._events=new Ps,this._eventsCount=0}nt.prototype.eventNames=function(){var i=[],e,t;if(this._eventsCount===0)return i;for(t in e=this._events)og.call(e,t)&&i.push(ht?t.slice(1):t);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i};nt.prototype.listeners=function(i){var e=ht?ht+i:i,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,s=t.length,n=new Array(s);r<s;r++)n[r]=t[r].fn;return n};nt.prototype.listenerCount=function(i){var e=ht?ht+i:i,t=this._events[e];return t?t.fn?1:t.length:0};nt.prototype.emit=function(i,e,t,r,s,n){var a=ht?ht+i:i;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,m;if(c.fn){switch(c.once&&this.removeListener(i,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,t),!0;case 4:return c.fn.call(c.context,e,t,r),!0;case 5:return c.fn.call(c.context,e,t,r,s),!0;case 6:return c.fn.call(c.context,e,t,r,s,n),!0}for(m=1,u=new Array(l-1);m<l;m++)u[m-1]=arguments[m];c.fn.apply(c.context,u)}else{var h=c.length,_;for(m=0;m<h;m++)switch(c[m].once&&this.removeListener(i,c[m].fn,void 0,!0),l){case 1:c[m].fn.call(c[m].context);break;case 2:c[m].fn.call(c[m].context,e);break;case 3:c[m].fn.call(c[m].context,e,t);break;case 4:c[m].fn.call(c[m].context,e,t,r);break;default:if(!u)for(_=1,u=new Array(l-1);_<l;_++)u[_-1]=arguments[_];c[m].fn.apply(c[m].context,u)}}return!0};nt.prototype.on=function(i,e,t){return _m(this,i,e,t,!1)};nt.prototype.once=function(i,e,t){return _m(this,i,e,t,!0)};nt.prototype.removeListener=function(i,e,t,r){var s=ht?ht+i:i;if(!this._events[s])return this;if(!e)return ca(this,s),this;var n=this._events[s];if(n.fn)n.fn===e&&(!r||n.once)&&(!t||n.context===t)&&ca(this,s);else{for(var a=0,c=[],l=n.length;a<l;a++)(n[a].fn!==e||r&&!n[a].once||t&&n[a].context!==t)&&c.push(n[a]);c.length?this._events[s]=c.length===1?c[0]:c:ca(this,s)}return this};nt.prototype.removeAllListeners=function(i){var e;return i?(e=ht?ht+i:i,this._events[e]&&ca(this,e)):(this._events=new Ps,this._eventsCount=0),this};nt.prototype.off=nt.prototype.removeListener;nt.prototype.addListener=nt.prototype.on;nt.prefixed=ht;nt.EventEmitter=nt;typeof Wd!="undefined"&&(Wd.exports=nt)});var dc=Ui((sC,lp)=>{"use strict";var dp=lp.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(o){return o.encoding?"rtpmap:%d %s/%s/%s":o.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(o){return o.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(o){return o.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(o){return"extmap:%d"+(o.direction?"/%s":"%v")+(o["encrypt-uri"]?" %s":"%v")+" %s"+(o.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(o){return o.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(o){var i="candidate:%s %d %s %d %s %d typ %s";return i+=o.raddr!=null?" raddr %s rport %d":"%v%v",i+=o.tcptype!=null?" tcptype %s":"%v",o.generation!=null&&(i+=" generation %d"),i+=o["network-id"]!=null?" network-id %d":"%v",i+=o["network-cost"]!=null?" network-cost %d":"%v",i}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(o){var i="ssrc:%d";return o.attribute!=null&&(i+=" %s",o.value!=null&&(i+=":%s")),i}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(o){return o.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(o){return o.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(o){return"imageattr:%s %s %s"+(o.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(o){return"simulcast:%s %s"+(o.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(o){return"ts-refclk:%s"+(o.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(o){var i="mediaclk:";return i+=o.id!=null?"id=%s %s":"%v%s",i+=o.mediaClockValue!=null?"=%s":"",i+=o.rateNumerator!=null?" rate=%s":"",i+=o.rateDenominator!=null?"/%s":"",i}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(dp).forEach(function(o){var i=dp[o];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var mp=Ui(Yi=>{"use strict";var is=function(o){return String(Number(o))===o?Number(o):o},mT=function(o,i,e,t){if(t&&!e)i[t]=is(o[1]);else for(var r=0;r<e.length;r+=1)o[r+1]!=null&&(i[e[r]]=is(o[r+1]))},pT=function(o,i,e){var t=o.name&&o.names;o.push&&!i[o.push]?i[o.push]=[]:t&&!i[o.name]&&(i[o.name]={});var r=o.push?{}:t?i[o.name]:i;mT(e.match(o.reg),r,o.names,o.name),o.push&&i[o.push].push(r)},up=dc(),fT=RegExp.prototype.test.bind(/^([a-z])=(.*)/);Yi.parse=function(o){var i={},e=[],t=i;return o.split(/(\r\n|\r|\n)/).filter(fT).forEach(function(r){var s=r[0],n=r.slice(2);s==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(up[s]||[]).length;a+=1){var c=up[s][a];if(c.reg.test(n))return pT(c,t,n)}}),i.media=e,i};var hp=function(o,i){var e=i.split(/=(.+)/,2);return e.length===2?o[e[0]]=is(e[1]):e.length===1&&i.length>1&&(o[e[0]]=void 0),o};Yi.parseParams=function(o){return o.split(/;\s?/).reduce(hp,{})};Yi.parseFmtpConfig=Yi.parseParams;Yi.parsePayloads=function(o){return o.toString().split(" ").map(Number)};Yi.parseRemoteCandidates=function(o){for(var i=[],e=o.split(" ").map(is),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};Yi.parseImageAttributes=function(o){return o.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(hp,{})})};Yi.parseSimulcastStreamList=function(o){return o.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=is(e):(t=is(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var fp=Ui((aC,pp)=>{"use strict";var Zl=dc(),_T=/%[sdv%]/g,gT=function(o){var i=1,e=arguments,t=e.length;return o.replace(_T,function(r){if(i>=t)return r;var s=e[i];switch(i+=1,r){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},mn=function(o,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,r=[o+"="+t];if(i.names)for(var s=0;s<i.names.length;s+=1){var n=i.names[s];i.name?r.push(e[i.name][n]):r.push(e[i.names[s]])}else r.push(e[i.name]);return gT.apply(null,r)},TT=["v","o","s","i","u","e","p","c","b","t","r","z","a"],ET=["i","c","b","a"];pp.exports=function(o,i){i=i||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var e=i.outerOrder||TT,t=i.innerOrder||ET,r=[];return e.forEach(function(s){Zl[s].forEach(function(n){n.name in o&&o[n.name]!=null?r.push(mn(s,n,o)):n.push in o&&o[n.push]!=null&&o[n.push].forEach(function(a){r.push(mn(s,n,a))})})}),o.media.forEach(function(s){r.push(mn("m",Zl.m[0],s)),t.forEach(function(n){Zl[n].forEach(function(a){a.name in s&&s[a.name]!=null?r.push(mn(n,a,s)):a.push in s&&s[a.push]!=null&&s[a.push].forEach(function(c){r.push(mn(n,a,c))})})})}),r.join(`\r
|
|
2
2
|
`)+`\r
|
|
3
|
-
`}});var _p=Ui(Ri=>{"use strict";var io=mp(),ST=fp(),IT=dc();Ri.grammar=IT;Ri.write=ST;Ri.parse=io.parse;Ri.parseParams=io.parseParams;Ri.parseFmtpConfig=io.parseFmtpConfig;Ri.parsePayloads=io.parsePayloads;Ri.parseRemoteCandidates=io.parseRemoteCandidates;Ri.parseImageAttributes=io.parseImageAttributes;Ri.parseSimulcastStreamList=io.parseSimulcastStreamList});var Qh=Ui((MF,c_)=>{"use strict";var a_=c_.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(o){return o.encoding?"rtpmap:%d %s/%s/%s":o.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(o){return o.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(o){return o.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(o){return"extmap:%d"+(o.direction?"/%s":"%v")+(o["encrypt-uri"]?" %s":"%v")+" %s"+(o.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(o){return o.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(o){var i="candidate:%s %d %s %d %s %d typ %s";return i+=o.raddr!=null?" raddr %s rport %d":"%v%v",i+=o.tcptype!=null?" tcptype %s":"%v",o.generation!=null&&(i+=" generation %d"),i+=o["network-id"]!=null?" network-id %d":"%v",i+=o["network-cost"]!=null?" network-cost %d":"%v",i}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(o){var i="ssrc:%d";return o.attribute!=null&&(i+=" %s",o.value!=null&&(i+=":%s")),i}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(o){return o.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(o){return o.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(o){return"imageattr:%s %s %s"+(o.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(o){return"simulcast:%s %s"+(o.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(o){return"ts-refclk:%s"+(o.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(o){var i="mediaclk:";return i+=o.id!=null?"id=%s %s":"%v%s",i+=o.mediaClockValue!=null?"=%s":"",i+=o.rateNumerator!=null?" rate=%s":"",i+=o.rateDenominator!=null?"/%s":"",i}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(a_).forEach(function(o){var i=a_[o];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var u_=Ui(dr=>{"use strict";var vs=function(o){return String(Number(o))===o?Number(o):o},rI=function(o,i,e,t){if(t&&!e)i[t]=vs(o[1]);else for(var r=0;r<e.length;r+=1)o[r+1]!=null&&(i[e[r]]=vs(o[r+1]))},oI=function(o,i,e){var t=o.name&&o.names;o.push&&!i[o.push]?i[o.push]=[]:t&&!i[o.name]&&(i[o.name]={});var r=o.push?{}:t?i[o.name]:i;rI(e.match(o.reg),r,o.names,o.name),o.push&&i[o.push].push(r)},d_=Qh(),sI=RegExp.prototype.test.bind(/^([a-z])=(.*)/);dr.parse=function(o){var i={},e=[],t=i;return o.split(/(\r\n|\r|\n)/).filter(sI).forEach(function(r){var s=r[0],n=r.slice(2);s==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(d_[s]||[]).length;a+=1){var c=d_[s][a];if(c.reg.test(n))return oI(c,t,n)}}),i.media=e,i};var l_=function(o,i){var e=i.split(/=(.+)/,2);return e.length===2?o[e[0]]=vs(e[1]):e.length===1&&i.length>1&&(o[e[0]]=void 0),o};dr.parseParams=function(o){return o.split(/;\s?/).reduce(l_,{})};dr.parseFmtpConfig=dr.parseParams;dr.parsePayloads=function(o){return o.toString().split(" ").map(Number)};dr.parseRemoteCandidates=function(o){for(var i=[],e=o.split(" ").map(vs),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};dr.parseImageAttributes=function(o){return o.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(l_,{})})};dr.parseSimulcastStreamList=function(o){return o.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=vs(e):(t=vs(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var m_=Ui((kF,h_)=>{"use strict";var Yh=Qh(),nI=/%[sdv%]/g,aI=function(o){var i=1,e=arguments,t=e.length;return o.replace(nI,function(r){if(i>=t)return r;var s=e[i];switch(i+=1,r){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},ta=function(o,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,r=[o+"="+t];if(i.names)for(var s=0;s<i.names.length;s+=1){var n=i.names[s];i.name?r.push(e[i.name][n]):r.push(e[i.names[s]])}else r.push(e[i.name]);return aI.apply(null,r)},cI=["v","o","s","i","u","e","p","c","b","t","r","z","a"],dI=["i","c","b","a"];h_.exports=function(o,i){i=i||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var e=i.outerOrder||cI,t=i.innerOrder||dI,r=[];return e.forEach(function(s){Yh[s].forEach(function(n){n.name in o&&o[n.name]!=null?r.push(ta(s,n,o)):n.push in o&&o[n.push]!=null&&o[n.push].forEach(function(a){r.push(ta(s,n,a))})})}),o.media.forEach(function(s){r.push(ta("m",Yh.m[0],s)),t.forEach(function(n){Yh[n].forEach(function(a){a.name in s&&s[a.name]!=null?r.push(ta(n,a,s)):a.push in s&&s[a.push]!=null&&s[a.push].forEach(function(c){r.push(ta(n,a,c))})})})}),r.join(`\r
|
|
3
|
+
`}});var _p=Ui(Ri=>{"use strict";var io=mp(),ST=fp(),IT=dc();Ri.grammar=IT;Ri.write=ST;Ri.parse=io.parse;Ri.parseParams=io.parseParams;Ri.parseFmtpConfig=io.parseFmtpConfig;Ri.parsePayloads=io.parsePayloads;Ri.parseRemoteCandidates=io.parseRemoteCandidates;Ri.parseImageAttributes=io.parseImageAttributes;Ri.parseSimulcastStreamList=io.parseSimulcastStreamList});var Qh=Ui((kF,c_)=>{"use strict";var a_=c_.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(o){return o.encoding?"rtpmap:%d %s/%s/%s":o.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(o){return o.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(o){return o.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(o){return"extmap:%d"+(o.direction?"/%s":"%v")+(o["encrypt-uri"]?" %s":"%v")+" %s"+(o.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(o){return o.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(o){var i="candidate:%s %d %s %d %s %d typ %s";return i+=o.raddr!=null?" raddr %s rport %d":"%v%v",i+=o.tcptype!=null?" tcptype %s":"%v",o.generation!=null&&(i+=" generation %d"),i+=o["network-id"]!=null?" network-id %d":"%v",i+=o["network-cost"]!=null?" network-cost %d":"%v",i}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(o){var i="ssrc:%d";return o.attribute!=null&&(i+=" %s",o.value!=null&&(i+=":%s")),i}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(o){return o.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(o){return o.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(o){return"imageattr:%s %s %s"+(o.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(o){return"simulcast:%s %s"+(o.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(o){return"ts-refclk:%s"+(o.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(o){var i="mediaclk:";return i+=o.id!=null?"id=%s %s":"%v%s",i+=o.mediaClockValue!=null?"=%s":"",i+=o.rateNumerator!=null?" rate=%s":"",i+=o.rateDenominator!=null?"/%s":"",i}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(a_).forEach(function(o){var i=a_[o];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var u_=Ui(dr=>{"use strict";var vs=function(o){return String(Number(o))===o?Number(o):o},rI=function(o,i,e,t){if(t&&!e)i[t]=vs(o[1]);else for(var r=0;r<e.length;r+=1)o[r+1]!=null&&(i[e[r]]=vs(o[r+1]))},oI=function(o,i,e){var t=o.name&&o.names;o.push&&!i[o.push]?i[o.push]=[]:t&&!i[o.name]&&(i[o.name]={});var r=o.push?{}:t?i[o.name]:i;rI(e.match(o.reg),r,o.names,o.name),o.push&&i[o.push].push(r)},d_=Qh(),sI=RegExp.prototype.test.bind(/^([a-z])=(.*)/);dr.parse=function(o){var i={},e=[],t=i;return o.split(/(\r\n|\r|\n)/).filter(sI).forEach(function(r){var s=r[0],n=r.slice(2);s==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(d_[s]||[]).length;a+=1){var c=d_[s][a];if(c.reg.test(n))return oI(c,t,n)}}),i.media=e,i};var l_=function(o,i){var e=i.split(/=(.+)/,2);return e.length===2?o[e[0]]=vs(e[1]):e.length===1&&i.length>1&&(o[e[0]]=void 0),o};dr.parseParams=function(o){return o.split(/;\s?/).reduce(l_,{})};dr.parseFmtpConfig=dr.parseParams;dr.parsePayloads=function(o){return o.toString().split(" ").map(Number)};dr.parseRemoteCandidates=function(o){for(var i=[],e=o.split(" ").map(vs),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};dr.parseImageAttributes=function(o){return o.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(l_,{})})};dr.parseSimulcastStreamList=function(o){return o.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=vs(e):(t=vs(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var m_=Ui((wF,h_)=>{"use strict";var Yh=Qh(),nI=/%[sdv%]/g,aI=function(o){var i=1,e=arguments,t=e.length;return o.replace(nI,function(r){if(i>=t)return r;var s=e[i];switch(i+=1,r){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},ta=function(o,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,r=[o+"="+t];if(i.names)for(var s=0;s<i.names.length;s+=1){var n=i.names[s];i.name?r.push(e[i.name][n]):r.push(e[i.names[s]])}else r.push(e[i.name]);return aI.apply(null,r)},cI=["v","o","s","i","u","e","p","c","b","t","r","z","a"],dI=["i","c","b","a"];h_.exports=function(o,i){i=i||{},o.version==null&&(o.version=0),o.name==null&&(o.name=" "),o.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var e=i.outerOrder||cI,t=i.innerOrder||dI,r=[];return e.forEach(function(s){Yh[s].forEach(function(n){n.name in o&&o[n.name]!=null?r.push(ta(s,n,o)):n.push in o&&o[n.push]!=null&&o[n.push].forEach(function(a){r.push(ta(s,n,a))})})}),o.media.forEach(function(s){r.push(ta("m",Yh.m[0],s)),t.forEach(function(n){Yh[n].forEach(function(a){a.name in s&&s[a.name]!=null?r.push(ta(n,a,s)):a.push in s&&s[a.push]!=null&&s[a.push].forEach(function(c){r.push(ta(n,a,c))})})})}),r.join(`\r
|
|
4
4
|
`)+`\r
|
|
5
|
-
`}});var Zh=Ui(lr=>{"use strict";var Co=u_(),lI=m_();lr.write=lI;lr.parse=Co.parse;lr.parseParams=Co.parseParams;lr.parseFmtpConfig=Co.parseFmtpConfig;lr.parsePayloads=Co.parsePayloads;lr.parseRemoteCandidates=Co.parseRemoteCandidates;lr.parseImageAttributes=Co.parseImageAttributes;lr.parseSimulcastStreamList=Co.parseSimulcastStreamList});import x4 from"webrtc-adapter";var Kf=Ge(at());var gm=(B=>(B[B.INVALID_PARAMETER=4096]="INVALID_PARAMETER",B[B.INVALID_OPERATION=4097]="INVALID_OPERATION",B[B.NOT_SUPPORTED=4098]="NOT_SUPPORTED",B[B.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",B[B.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",B[B.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",B[B.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",B[B.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",B[B.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",B[B.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",B[B.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",B[B.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",B[B.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",B[B.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",B[B.CLIENT_BANNED=16448]="CLIENT_BANNED",B[B.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",B[B.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",B[B.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",B[B.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",B[B.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",B[B.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",B[B.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",B[B.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",B[B.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",B[B.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",B[B.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",B[B.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",B[B.API_CALL_ABORTED=16461]="API_CALL_ABORTED",B[B.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",B[B.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",B[B.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",B[B.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",B[B.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",B[B.UNKNOWN=65535]="UNKNOWN",B))(gm||{}),I=gm;var ng=function(o){for(let i in I)if(I[i]===o)return i;return"UNKNOWN"},ws=class extends Error{constructor({name:e="RtcError",message:t,code:r=I.UNKNOWN,extraCode:s=0,constraint:n}){let a=`<${ng(r)} 0x${r.toString(16)}>`,c=`${t}${n?` constraint: ${n}`:""}${t!=null&&t.includes(a)?"":` ${a}`}`;super(c);d(this,"code");d(this,"extraCode");d(this,"message");d(this,"originMessage");d(this,"name");d(this,"constraint");this.code=r,this.extraCode=s,this.name=e,this.message=c,this.constraint=n,this.originMessage=t}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},D=ws;var Gd=0,Tm=!0,da=function(o){Gd=o;let i=new Date;i.setTime(i.getTime()+o),R[Tm?"info":"debug"](`baseTime from server: ${i} offset: ${o}`),Tm=!1},Em=function(){return Gd},Fi=function(){return Date.now()+Gd},la=function(){let o=new Date;return o.setTime(Fi()),o.toLocaleString()},No=function(o){let i=String(o.getMilliseconds());return"padStart"in String.prototype&&(i=i.toString().padStart(3,"0")),`${o.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${i}`};var vt={};Vi(vt,{REPORT_TYPE:()=>$o,buildSSOPackage:()=>Gi,bytes2ms:()=>Mm,calculateScaleResolutionDownNumber:()=>Ho,concatArrayBuffers:()=>ka,convertObjectNumberToInt:()=>Js,copyProperties:()=>Dm,deepClone:()=>Gr,deepCloneBasic:()=>ya,deepMerge:()=>ei,delay:()=>Ke,fibonacci:()=>Jr,formatedTime:()=>Fm,getConstructorName:()=>xo,getContainerFromElement:()=>Vm,getEnv:()=>bm,getFirst16Bits:()=>Hm,getInternalVersion:()=>xm,getLast16Bits:()=>Pa,getLoggerUrl:()=>Wi,getMediaStreamTrackInfo:()=>Oa,getMuteStateFromFlag:()=>Kt,getNetworkType:()=>ba,getNumNetworkType:()=>qr,getReconnectionTimeout:()=>Zt,getStringByteLength:()=>qs,getTurnServer:()=>Um,getUint32Version:()=>Na,getValueType:()=>Me,getViewListFromView:()=>Fo,glog:()=>_l,ipv4ToUint32:()=>Vo,isArray:()=>Ie,isAudioWorkletSupported:()=>wm,isBoolean:()=>he,isConstructor:()=>jr,isEmpty:()=>Uo,isFunction:()=>le,isLangChinese:()=>Yt,isMediaStreamTrack:()=>km,isNumber:()=>z,isObject:()=>yt,isOverseaSdkAppId:()=>Ut,isPlainObject:()=>dt,isPortrait:()=>gl,isPromise:()=>Tr,isRemoteTrack:()=>Pm,isRotate90Or270:()=>bt,isSetSinkIdSupported:()=>Lm,isString:()=>ie,isUndefined:()=>T,loadImage:()=>Bo,loadVideo:()=>Bm,ms2bytes:()=>Om,ms2samples:()=>fl,normalizeUrl:()=>Ma,performanceNow:()=>U,promiseAny:()=>Xr,samples2ms:()=>pl,setNetworkTypeFromWebRTC:()=>va,stringify:()=>_t,stringifyIncludeValue:()=>Gs,throttlePromise:()=>Da});var ol={};Vi(ol,{AUDIO_MUTE_BIT:()=>Ta,AUDIO_STAT_BIT:()=>_r,AUX_STAT_BIT:()=>Br,AUX_STREAM_MSID:()=>Yd,BACKEND_ENV:()=>ga,BASE_DOC_URL:()=>ft,BASE_HOST:()=>Sm,CAPABILITIES_KEYS:()=>Ia,CLASS_NAME:()=>Ng,CLOUD_CONSOLE_URL:()=>lg,CROSS_ROOM_BIT:()=>Qd,DATA_FREEZE_TIMING:()=>Sa,DOC_BILLING_CN:()=>ua,DOC_BILLING_OVERSEA:()=>ha,DOC_URL:()=>ug,DTLS_STATE_UNKNOWN:()=>Qt,ENV_NAME:()=>Bi,EXCHANGE_SDP_TIMEOUT:()=>il,IS_WORKER:()=>Do,IS_WORKLET:()=>xs,KIBANA_EVENT:()=>Ze,LOCAL_STREAM_PUBLISH_STATE:()=>Am,LOGGER_CMD_TYPE:()=>mr,LOGGER_DOMAIN:()=>Jd,LOGGER_DOMAIN_OVERSEA:()=>jd,LOG_LEVEL:()=>Xt,LOG_LEVEL_NAME:()=>Mg,MAIN_STREAM_MSID:()=>Fs,MAX_RTT:()=>$s,MICROPHONE_COMMUNICATIONS:()=>Dg,MICROPHONE_DEFAULT:()=>Wr,MUTE_ALL_BIT:()=>pg,NAME:()=>f,NETWORK_TYPE:()=>ma,NOT_SUPPORTED_H264:()=>Hr,PAUSED_RETRY_COUNT:()=>$r,PEERCONNECTION_CONNECTING_TIMEOUT:()=>Bs,PEER_CONNECTION_STATE:()=>Ce,PEER_LEAVE_REASON:()=>rl,RECOVER_CAPTURE_INTERVAL:()=>ko,REMOTE_STREAM_TYPE_AUX:()=>Kd,REMOTE_STREAM_TYPE_MAIN:()=>Zd,RENDER_FREEZE_TIMING:()=>Rg,SCHEDULE_DOMAIN:()=>$i,SCHEDULE_TIMEOUT:()=>vg,SDP_SEMANTICS_PLAN_B:()=>Mo,SDP_SEMANTICS_UNIFIED_PLAN:()=>gr,SECOND_HOST:()=>cg,SIGNAL_PING_PONG_INTERVAL:()=>mg,SIGNAL_PING_TIMEOUT:()=>hg,SIGNAL_RECONNECTION_COUNT:()=>Ag,SMALL_STAT_BIT:()=>Vs,SPEAKER_DEFAULT:()=>Hs,STORAGE_EXPIRES_TIME:()=>pa,STREAM_TYPE_BIG:()=>yg,STREAM_TYPE_SMALL:()=>bg,SUBSCRIBE_SMALL_RETRY_COUNT:()=>Oo,SYNC_USER_LIST_INTERVAL:()=>Cg,Scene:()=>Ei,THIRD_HOST:()=>dg,TRANSPORT_DIRECTION:()=>ne,TRTC_ERROR_ASSISTANCE:()=>Xd,TRTC_QUALITY_BAD:()=>Eg,TRTC_QUALITY_DISCONNECTED:()=>Ig,TRTC_QUALITY_EXCELLENT:()=>_g,TRTC_QUALITY_GOOD:()=>gg,TRTC_QUALITY_POOR:()=>Tg,TRTC_QUALITY_UNKNOWN:()=>fg,TRTC_QUALITY_VERY_BAD:()=>Sg,UPDATE_OFFER_TIMEOUT:()=>tl,VIDEO_MUTE_BIT:()=>Ea,VIDEO_STAT_BIT:()=>fr,audioProfileMap:()=>fa,defaultBigVideoProfile:()=>pr,defaultSmallVideoProfile:()=>zd,getRetryCount:()=>Hi,getScriptDir:()=>ag,innerVersion:()=>Ls,loggerProxy:()=>Us,screenProfileMap:()=>_a,setLoggerProxy:()=>Fr,setRetryCount:()=>el,setVersion:()=>qd,version:()=>He,videoProfileMap:()=>zt});var Ls="4.15.00.1600",He="5.0.0";function qd(o){He=o;let[i,e,t]=o.split(".").map(r=>parseInt(r,10));Ls=`${i}.${Math.min(15,e)}.${Math.min(15,t)}.${e.toString().padStart(2,"0")}${t.toString().padStart(2,"0")}`}var Do=typeof importScripts!="undefined",xs=typeof registerProcessor!="undefined",ag=()=>{let o=Do?self.location.href:document.currentScript.src;return o.substring(0,o.lastIndexOf("/")+1)},Us="",Fr=o=>Us=o,Sm="web.sdk.qcloud.com",cg="web.sdk.tencent.cn",dg="web.sdk.cloud.tencent.cn",lg="https://console.cloud.tencent.com/trtc",ft=`https://${Sm}/trtc/webrtc/doc`,ug=`${ft}/zh-cn/`,ua="https://cloud.tencent.com/document/product/647/85386",ha="https://trtc.io/document/56025",Jd="https://yun.tim.qq.com",jd="https://apisgp.my-imcloud.com",Xd="trtc_error_assistance",mr={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},Bi={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},Xt=(n=>(n[n.TRACE=0]="TRACE",n[n.DEBUG=1]="DEBUG",n[n.INFO=2]="INFO",n[n.WARN=3]="WARN",n[n.ERROR=4]="ERROR",n[n.NONE=5]="NONE",n))(Xt||{}),hg=18e3,mg=2e3,ma={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5,"5g":6},pa=7*24*3600*1e3,fa={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:128},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},zt={"120p":{width:160,height:120,frameRate:15,bitrate:200},"120p_2":{width:160,height:120,frameRate:15,bitrate:100},"180p":{width:320,height:180,frameRate:15,bitrate:350},"180p_2":{width:320,height:180,frameRate:15,bitrate:150},"240p":{width:320,height:240,frameRate:15,bitrate:400},"240p_2":{width:320,height:240,frameRate:15,bitrate:200},"360p":{width:640,height:360,frameRate:15,bitrate:800},"360p_2":{width:640,height:360,frameRate:15,bitrate:400},"480p":{width:640,height:480,frameRate:15,bitrate:900},"480p_2":{width:640,height:480,frameRate:15,bitrate:500},"720p":{width:1280,height:720,frameRate:15,bitrate:1500},"1080p":{width:1920,height:1080,frameRate:15,bitrate:2e3},"1440p":{width:2560,height:1440,frameRate:30,bitrate:4860},"4K":{width:3840,height:2160,frameRate:30,bitrate:9e3}},pr=zt["480p_2"],zd=zt["120p_2"],_a={"480p":{width:640,height:480,frameRate:5,bitrate:900},"480p_2":{width:640,height:480,frameRate:30,bitrate:1e3},"720p":{width:1280,height:720,frameRate:5,bitrate:1200},"720p_2":{width:1280,height:720,frameRate:30,bitrate:3e3},"1080p":{width:1920,height:1080,frameRate:5,bitrate:1600},"1080p_2":{width:1920,height:1080,frameRate:30,bitrate:4e3}},f={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADSTART:"loadstart",LOADEDDATA:"loadeddata",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture",RESIZE:"resize",TIME_UPDATE:"timeupdate"},ne={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},ga={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Ei=(e=>(e.LIVE="live",e.RTC="rtc",e))(Ei||{}),fr=1,Vs=2,Br=4,_r=8,Ta=64,Ea=16,pg=112,Qd=128,Fs="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",Yd="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",Zd=f.MAIN,Kd=f.AUXILIARY,fg=0,_g=1,gg=2,Tg=3,Eg=4,Sg=5,Ig=6,Qt="unknown",Ce={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Im=1/0;function el(o){Im=o}function Hi(){return Im}var Ag=30,Ze={JOIN:"join",DELTA_JOIN:"delta-join",REJOIN:"rejoin",LEAVE:"leave",DELTA_LEAVE:"delta-leave",PUBLISH:"publish",DELTA_PUBLISH:"delta-publish",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",UPLINK_CONNECTION:"uplink-connection",UPLINK_RECONNECTION:"uplink-reconnection",DOWNLINK_CONNECTION:"downlink-connection",DOWNLINK_RECONNECTION:"downlink-reconnection",ON_TRACK:"ontrack",ICE_CONNECTION_STATE:"iceConnectionState",LOCAL_STREAM_INITIALIZE:"stream-initialize",SIGNAL_CONNECTION:"websocketConnectionState",SIGNAL_RECONNECTION:"websocketReconnectionState",UPDATE_STREAM:"update-stream",RECOVER_LOCAL_AUDIO_TRACK:"recover-local-audio-track",RECOVER_LOCAL_VIDEO_TRACK:"recover-local-video-track",RECOVER_SUBSCRIPTION:"recover-subscription",START_MIX_TRANSCODE:"start-mix-transcode",STOP_MIX_TRANSCODE:"stop-mix-transcode",PLAYER_ERROR:"player-error",SCHEDULE:"schedule",LOAD_WORKLET:"load-worklet",VIDEO_FROZEN_COUNT:"videoFrozenCount",GET_USER_MEDIA_RETRY:"getUserMedia-retry",VIDEO_ENCODE_FAILED_DURING_CALL:"video-encode-failed-during-call",AUDIO_ENCODE_FAILED_DURING_CALL:"audio-encode-failed-during-call"},Cg=1e4,tl=1e4,il=1e4,gr="unified-plan",Mo="plan-b",Hr=1028,Am=(t=>(t[t.UNPUBLISH=-1]="UNPUBLISH",t[t.PUBLISHING=0]="PUBLISHING",t[t.PUBLISHED=1]="PUBLISHED",t))(Am||{}),Sa=500,Rg=1e3,yg=f.BIG,bg=f.SMALL,Bs=10*1e3,$i={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_BACKUP:"intl-schedule.cloud-rtc.com"},vg=2e3,Ng={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},$r=5,Wr="default",Hs=Wr,Dg="communications",Mg=Object.keys(Xt),rl=["normal leave","timeout leave","kick","role change"],Oo=10,ko=2e3,Ia=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],$s=10*1e3;var Og=function(o,i,e,t){function r(s){return s instanceof e?s:new e(function(n){n(s)})}return new(e||(e=Promise))(function(s,n){function a(u){try{l(t.next(u))}catch(m){n(m)}}function c(u){try{l(t.throw(u))}catch(m){n(m)}}function l(u){u.done?s(u.value):r(u.value).then(a,c)}l((t=t.apply(o,i||[])).next())})},sl=Symbol(32),nl=Symbol(16),al=Symbol(8),Si=class{constructor(i){this.g=i,this.consumed=0,i&&(this.need=i.next().value)}setG(i){this.g=i,this.demand(i.next().value,!0)}consume(){this.buffer&&this.consumed&&(this.buffer.copyWithin(0,this.consumed),this.buffer=this.buffer.subarray(0,this.buffer.length-this.consumed),this.consumed=0)}demand(i,e){return e&&this.consume(),this.need=i,this.flush()}read(i){return Og(this,void 0,void 0,function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise((e,t)=>{var r;this.reject=t,this.resolve=n=>{delete this.lastReadPromise,delete this.resolve,delete this.need,e(n)},this.demand(i,!0)||(r=this.pull)===null||r===void 0||r.call(this,i)})})}readU32(){return this.read(sl)}readU16(){return this.read(nl)}readU8(){return this.read(al)}close(){var i;this.g&&this.g.return(),this.buffer&&this.buffer.subarray(0,0),(i=this.reject)===null||i===void 0||i.call(this,new Error("EOF")),delete this.lastReadPromise}flush(){if(!this.buffer||!this.need)return;let i=null,e=this.buffer.subarray(this.consumed),t=0,r=s=>e.length<(t=s);if(typeof this.need=="number"){if(r(this.need))return;i=e.subarray(0,t)}else if(this.need===sl){if(r(4))return;i=e[0]<<24|e[1]<<16|e[2]<<8|e[3]}else if(this.need===nl){if(r(2))return;i=e[0]<<8|e[1]}else if(this.need===al){if(r(1))return;i=e[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(r(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(e.subarray(0,t)),i=this.need}else if(this.g){this.g.throw(new Error("Unsupported type"));return}}else{if(r(this.need.byteLength))return;new Uint8Array(this.need).set(e.subarray(0,t)),i=this.need}return this.consumed+=t,this.g?this.demand(this.g.next(i).value,!0):this.resolve&&this.resolve(i),i}write(i){if(i instanceof Uint8Array?this.malloc(i.length).set(i):"buffer"in i?this.malloc(i.byteLength).set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)):this.malloc(i.byteLength).set(new Uint8Array(i)),this.g||this.resolve)this.flush();else return new Promise(e=>this.pull=e)}writeU32(i){this.malloc(4).set([i>>24&255,i>>16&255,i>>8&255,i&255]),this.flush()}writeU16(i){this.malloc(2).set([i>>8&255,i&255]),this.flush()}writeU8(i){this.malloc(1)[0]=i,this.flush()}malloc(i){if(this.buffer){let e=this.buffer.length,t=e+i;if(t<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,t);else{let r=new Uint8Array(t);r.set(this.buffer),this.buffer=r}return this.buffer.subarray(e,t)}else return this.buffer=new Uint8Array(i),this.buffer}};Si.U32=sl;Si.U16=nl;Si.U8=al;var kg=128,Pg=127,$I=~Pg,WI=Math.pow(2,31);function cl(o){let i=new Si;for(;o>=128;)i.malloc(1)[0]=o&255|kg,o>>>=7;return i.malloc(1)[0]=o&255,i.buffer||new Uint8Array(0)}function Aa(o,i=0){let e=new Si,t=i<<3;switch(typeof o){case"boolean":let r=e.malloc(2);r[0]=t,r[1]=o?1:0;break;case"number":e.malloc(1)[0]=t,e.write(cl(o));break;case"string":e.malloc(1)[0]=t|2;let s=new TextEncoder().encode(o);e.write(cl(s.length));let n=e.malloc(s.length);for(let c=0;c<s.length;c++)n[c]=s[c];break;case"object":let a=new Si;if(Array.isArray(o))for(let c=0;c<o.length;c++){let l=Aa(o[c],c+1);l&&a.write(l)}else{let c=1;for(let l in o){let u=Aa(o[l],c++);u&&a.write(u)}}i===0?a.buffer&&e.write(a.buffer):(e.malloc(1)[0]=t|2,a.buffer&&(e.write(cl(a.buffer.length)),e.write(a.buffer)))}return e.buffer||new Uint8Array(0)}var Ws=class{constructor(){d(this,"buffer");this.buffer=[]}get data(){return this.buffer}get length(){return this.buffer.length}writeInt32(i){this.buffer.push(i>>>24&255),this.buffer.push(i>>>16&255),this.buffer.push(i>>>8&255),this.buffer.push(i&255)}writeInt16(i){this.buffer.push(i>>>8&255),this.buffer.push(i&255)}writeByte(i){this.buffer.push(i&255)}writeBytes(i){for(let e=0;e<i.length;e++)this.buffer.push(i[e])}};function dl(o,i,e){o[e]=i>>>24&255,o[e+1]=i>>>16&255,o[e+2]=i>>>8&255,o[e+3]=i&255}function ct(o,i){return o[i]<<24|o[i+1]<<16|o[i+2]<<8|o[i+3]}function ll(o,i){return o[i]}function Po(o,i,e){return new TextDecoder().decode(wg(o,i,e))}function wg(o,i,e){return o.slice(i,i+e)}var ul=0,Ca=2654435769,Ra=16,ml=4,wo=2,Lo=7;function Lg(o,i,e,t="AVQualityReportSvc.C2S",r=2e3,s=2,n=30){return{version:r,encryption:s,d2:"",d2Len:0,uinType:n,uin:"",uinLen:0,reqHead:{seqNumber:e,appId:o,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:t,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:i}}function Cm(o,i){let e=new Ws,t=Lg(i,o,ul);ul=ul+1&2147483647,e.writeInt32(0),e.writeInt32(t.version),e.writeByte(t.encryption);let r=new TextEncoder().encode(t.d2);e.writeInt32(r.length+4),r&&e.writeBytes(r),e.writeByte(t.uinType);let s=new TextEncoder().encode(t.uin);e.writeInt32(s.length+4),s.length&&e.writeBytes(s);let n=new Ws;n.writeInt32(0),n.writeInt32(t.reqHead.seqNumber),n.writeInt32(t.reqHead.appId),n.writeByte(t.reqHead.appId>>>24&255),n.writeByte(t.reqHead.appId>>>16&255),n.writeByte(t.reqHead.appId>>>8&255),n.writeByte(t.reqHead.appId&255);for(let re=4;re<16;re++)n.writeByte(0);let a=new TextEncoder().encode(t.reqHead.a2);n.writeInt32(a.length+4),a.length&&n.writeBytes(a);let c=new TextEncoder().encode(t.reqHead.serviceCmd);n.writeInt32(c.length+4),c.length&&n.writeBytes(c);let l=new TextEncoder().encode(t.reqHead.cookie);n.writeInt32(l.length+4),l.length&&n.writeBytes(l);let u=new TextEncoder().encode(t.reqHead.imei);n.writeInt32(u.length+4),u.length&&n.writeBytes(u);let m=new TextEncoder().encode(t.reqHead.ksid);n.writeInt32(m.length+4),m.length&&n.writeBytes(m);let h=new TextEncoder().encode(t.reqHead.clientVersionInfo);n.writeInt16(h.length+2),h.length&&n.writeBytes(h);let _=n.length;n.data[0]=_>>>24&255,n.data[1]=_>>>16&255,n.data[2]=_>>>8&255,n.data[3]=_&255,ie(o)&&(o=new TextEncoder().encode(o)),n.writeInt32(o.length+4),o.length&&n.writeBytes(o);let g=new Uint8Array(n.data),E=null;t.encryption===1?E=new TextEncoder().encode(t.uin):t.encryption===2&&(E=new Uint8Array(16)),E&&(g=xg(g,E)),e.writeBytes(g);let A=new Uint8Array(e.data),k=A.length;return A[0]=k>>>24&255,A[1]=k>>>16&255,A[2]=k>>>8&255,A[3]=k&255,A}function xg(o,i){let e=o.length,r=(e+1+wo+Lo)%8;r&&(r=8-r);let s=e+1+wo+Lo+r,n=new Uint8Array(s),a=0,c=new Uint8Array(8),l=new Uint8Array(8),u=new Uint8Array(8),m=0;c[0]=Math.floor(Math.random()*256)&248|r,m=1;for(let _=0;_<r;_++)c[m]=Math.floor(Math.random()*256)&255,m+=1;for(let _=0;_<wo;)if(m<8&&(c[m]=Math.floor(Math.random()*256)&255,m+=1,_+=1),m===8){hl(c,i,l,u,n,a),a+=8,m=0;for(let g=0;g<8;g++)u[g]=n[a-8+g]}let h=0;for(;h<e;)if(m<8&&(c[m]=o[h],m+=1,h+=1),m===8){hl(c,i,l,u,n,a),a+=8,m=0;for(let _=0;_<8;_++)u[_]=n[a-8+_]}for(let _=0;_<Lo;)if(m<8&&(c[m]=0,m+=1,_+=1),m===8){hl(c,i,l,u,n,a),a+=8,m=0;for(let g=0;g<8;g++)u[g]=n[a-8+g]}return n}function hl(o,i,e,t,r,s){for(let n=0;n<8;n++)o[n]^=t[n];Ug(o,i,r,s);for(let n=0;n<8;n++)r[s+n]^=e[n];for(let n=0;n<8;n++)e[n]=o[n]}function Ug(o,i,e,t){let r=ct(o,0),s=ct(o,4),n=[];for(let c=0;c<4;c++)n[c]=ct(i,c*4);let a=0;for(let c=0;c<Ra;c++)a+=Ca,a=a>>>0,r+=(s<<4)+n[0]^s+a^(s>>>5)+n[1],r=r>>>0,s+=(r<<4)+n[2]^r+a^(r>>>5)+n[3],s=s>>>0;dl(e,r,t),dl(e,s,t+4)}var bm=function(){return new URLSearchParams(location.search).get("trtc_env")||""},Ut=o=>Number(o)<14e8,Wi=function(o,i){let e;Us?e=Us:e=Ut(o)?jd:Jd;let t=Math.floor(Math.random()*hr(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${t}&sdkappid=${o}&cmdtype=${i}`},vm="unknown";function ba(){Fg();let{userAgent:o,connection:i}=navigator,e=(o.match(/NetType\/\S+/)||[])[0]||"";e=e.toLowerCase().replace("nettype/",""),e==="3gnet"&&(e="3g");let t=i&&i.type&&i.type.toLowerCase(),r=i&&i.effectiveType&&i.effectiveType.toLowerCase();return r==="slow-2"&&(r="2g"),t?Nm(t,r):vm}function Vg(){R.warn("netType changed",ba())}var Rm=!1;function Fg(){var o;Rm||(Rm=!0,(o=navigator.connection)==null||o.addEventListener("typechange",Vg))}function Nm(o,i){if(ma[o])return o;switch(o){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function va(o){vm=Nm(o)}function qr(){return ma[ba()]}function Dm(o,i){for(let e of Reflect.ownKeys(i))if(e!=="constructor"&&e!=="prototype"&&e!=="name"){let t=Object.getOwnPropertyDescriptor(i,e)||"";Object.defineProperty(o,e,t)}return o}function Mm(o,i=48e3){return pl(o/4,i)}function pl(o,i=48e3){return o*1e3/i}function Om(o,i=48e3){return fl(o,i)*4}function fl(o,i=48e3){return o*i/1e3}var _l=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},Yt=()=>{let o=navigator.language;return o=o.substring(0,2),o==="zh"},dt=function(o){if(!o||typeof o!="object"||Object.prototype.toString.call(o)!="[object Object]")return!1;let i=Object.getPrototypeOf(o);if(i===null)return!0;let e=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function Jr(o,i=1,e=1){return o<=1?e:Jr(o-1,e,i+e)}function Zt(o){return o>8?30*1e3:Jr(o)*1e3}function Me(o){return Reflect.apply(Object.prototype.toString,o,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var le=o=>typeof o=="function",T=o=>typeof o=="undefined",ie=o=>typeof o=="string",z=o=>typeof o=="number",he=o=>typeof o=="boolean",yt=o=>Me(o)==="object",Ie=o=>Me(o)==="array",km=o=>Me(o)==="MediaStreamTrack".toLowerCase(),Pm=o=>o.isRemote,Tr=o=>Me(o)==="promise",jr=o=>le(o)&&o.prototype.constructor===o,xo=o=>jr(o)?o.prototype.constructor.name:"",wm=typeof AudioWorkletNode!="undefined",Lm=typeof HTMLMediaElement!="undefined"&&"setSinkId"in HTMLMediaElement.prototype;function Xr(o){return new Promise((i,e)=>{let t=[];o.forEach(r=>{r.then(i).catch(s=>{t.push(s),t.length===o.length&&e(t)})})})}function U(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var ym=o=>+o<10?`0${o}`:o,xm=o=>{let i=o.match(/^\d+\.\d+\.\d+/)[0];if(!i)return o;let e=i.split("."),t=ym(e[1])+ym(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${t}`},Bg=Object.prototype.hasOwnProperty,{toString:iA}=Object.prototype;function Uo(o){if(o==null)return!0;if(typeof o=="boolean")return!1;if(typeof o=="number")return o===0;if(typeof o=="string"||typeof o=="function"||Array.isArray(o))return o.length===0;if(o instanceof Error)return o.message==="";if(dt(o))switch(Object.prototype.toString.call(o)){case"[object File]":case"[object Map]":case"[object Set]":return o.size===0;case"[object Object]":{for(let i in o)if(Bg.call(o,i))return!1;return!0}}return!1}function Kt(o,i){return{userId:i,hasAudio:!!(o&_r),hasVideo:!!(o&fr),hasAuxiliary:!!(o&Br),hasSmall:!!(o&Vs),audioMuted:!!(o&Ta),videoMuted:!!(o&Ea),audioAvailable:!!(o&_r)&&!(o&Ta),videoAvailable:!!(o&fr)&&!(o&Ea)}}function Um(o){let i={urls:o.url.startsWith("turn:")||o.url.startsWith("turns:")?o.url:`turn:${o.url}`};return!T(o.username)&&!T(o.credential)&&(i.username=o.username,i.credential=o.credential,i.credentialType="password",T(o.credentialType)||(i.credentialType=o.credentialType)),i}function Vo(o,i=!0){if(!ie(o))return 0;let e=o.split(".");return i?(Number(e[0])<<24|Number(e[1])<<16|Number(e[2])<<8|Number(e[3]))>>>0:(Number(e[3])<<24|Number(e[2])<<16|Number(e[1])<<8|Number(e[0]))>>>0}var ei=function(o,i,e,t){if(!(yt(o)&&yt(i)))return 0;let r=0,s=Object.keys(i),n;for(let a=0,c=s.length;a<c;a++)if(n=s[a],!(T(i[n])||e&&e.includes(n)))if(yt(o[n])&&yt(i[n]))r+=ei(o[n],i[n],e,t);else{if(t&&t.includes(i[n]))continue;o[n]!==i[n]&&(o[n]=Gr(i[n]),r+=1)}return r};function Gr(o){if(Ie(o)){let i=[];return o.forEach((e,t)=>{i[t]=Gr(e)}),i}if(yt(o)){let i={};return Object.keys(o).forEach(e=>{i[e]=Gr(o[e])}),i}return o}var Fo=o=>{let i=[];if(Ie(o))i=[...o];else if(ie(o)){let e=document.getElementById(o);e&&i.push(e)}else o&&i.push(o);return i},Vm=o=>ie(o)?document.getElementById(o):o,Hg=o=>{let i=c=>c<10?`0${c}`:`${c}`,e=o.getFullYear(),t=o.getMonth()+1,r=o.getDate(),s=i(o.getHours()),n=i(o.getMinutes()),a=i(o.getSeconds());return`${e}/${t}/${r} ${s}:${n}:${a}`},Fm=()=>Hg(new Date);function _t(o,{keysToInclude:i,keysToExclude:e}){try{if(Ie(o))return`[${o.map(n=>_t(n,{keysToInclude:i,keysToExclude:e})).join(",")}]`;if(!dt(o)||!Ie(i)&&!Ie(e))return JSON.stringify(o);let t={},r=new Set(i),s=new Set(e);return Object.keys(o).forEach(n=>{(s.size===0&&r.has(n)||r.size===0&&!s.has(n))&&(t[n]=dt(o[n])||Ie(o[n])?JSON.parse(_t(o[n],{keysToExclude:e,keysToInclude:i})):o[n])}),JSON.stringify(t)}catch(t){return"{}"}}function Gs(o,i=!1){let e=[];return Object.keys(o).forEach(t=>{i===o[t]&&e.push(t)}),_t(o,{keysToInclude:e})}function qs(o){return o.replace(/[\u4e00-\u9fa5]/g,"aa").length}var gl=()=>{var o,i,e,t;return(o=window.screen)!=null&&o.orientation?!!((t=(e=(i=window.screen)==null?void 0:i.orientation)==null?void 0:e.type)!=null&&t.includes("portrait")):window.orientation===0||window.orientation===180},Bo=o=>p(void 0,null,function*(){return new Promise((i,e)=>{let t;if(ie(o))t=new Image,t.crossOrigin="anonymous",t.src=o;else if(t=o,t.complete){i(t);return}t.onload=()=>i(t),t.onerror=()=>{e(new D({code:I.INVALID_PARAMETER,message:`load image failed, url: ${o}`}))}})}),Na=o=>{let i=o.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]<<0},Js=o=>(Object.keys(o).forEach(i=>{z(o[i])&&(i.startsWith("uint")||i.startsWith("int"))?o[i]=Math.floor(o[i]):(dt(o[i])||Ie(o[i]))&&Js(o[i])}),o);function Ke(o,i){return new Promise(e=>{let t=setTimeout(e,o);i&&i(t)})}function Da(o,i){let e=null;return function(...t){return e||(e=o.apply(i||this,t),e.finally(()=>e=null),e)}}function Ma(o){return o.replace(/(^|[^:])\/{2,}/g,"$1/")}function Oa(o){var i;try{let{width:e,height:t,frameRate:r,sampleRate:s,sampleSize:n,channelCount:a}=(i=o.getSettings)==null?void 0:i.call(o),c=o.kind===f.AUDIO?`${s}x${n}@${a}`:`${e}x${t}@${r}`,l=o.stats?` stats: ${JSON.stringify(o.stats).replaceAll('"',"")}`:"";return`${o.id} ${o.readyState} muted:${o.muted} ${o.kind} ${o.label} ${c}${l}`}catch(e){return""}}function Ho(o,i){return o.width*o.height===i.width*i.height?1:gl()&&i.width>i.height&&o.height>i.width?Math.max(o.width/i.height,o.height/i.width,1):Math.max(o.width/i.width,o.height/i.height,1)}function bt(o){return o===90||o===270}function Bm(o){return p(this,null,function*(){return new Promise((i,e)=>{let t=document.createElement("video");t.crossOrigin="anonymous",t.src=o,t.muted=!0,t.loop=!0,t.playsInline=!0,t.play().then(()=>i(t)),t.onerror=()=>{e(t.error)}})})}function ya(o,i=new WeakMap){if(typeof o!="object"||o===null)return o;if(i.has(o))return i.get(o);if(Array.isArray(o)){let e=[];return i.set(o,e),o.forEach((t,r)=>{e[r]=ya(t,i)}),e}if(Object.prototype.toString.call(o)==="[object Object]"){let e={};return i.set(o,e),Reflect.ownKeys(o).forEach(t=>{e[t]=ya(o[t],i)}),e}return o}var $o=(t=>(t[t.END_REPORT=2001]="END_REPORT",t[t.LOG=2002]="LOG",t[t.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",t))($o||{});function $g(o,i,e,t){let r={data:o,random:Math.floor(Math.random()*2147483648),sdkAppId:e};return T(t)||(r=L(O({},r),{gzip:+t})),{uint32_sdkappid:0,uint64_from_uin:0,uint32_timestamp:0,uint32_seq:0,msg_common_info:{msg_device_info:{enum_device_type:0,str_device_brand:"",str_device_model:"",str_device_board:"",str_device_cpu_abi:""},msg_system_info:{enum_os_type:0,str_os_version:"",msg_network_info:0},msg_network_info:{enum_network_type:0}},msg_report_content:{uint32_type:i,bytes_report_data:JSON.stringify(r)}}}function Gi(o,i,e,t){try{let r=$g(o,i,e,t),s=Aa(r);return Cm(s,e)}catch(r){return JSON.stringify(o)}}function ka(o,i){let e=new Uint8Array(o.byteLength+i.byteLength);return e.set(new Uint8Array(o),0),e.set(new Uint8Array(i),o.byteLength),e.buffer}function Pa(o){return(o&65535)>>>0}function Hm(o){return(o&4294901760)>>>0}function $m(o){let i=Wg(o);return i==null?void 0:i.busiBuff}function Wg(o){try{let i={},e=0;i.totalLength=ct(o,e),e+=4,i.version=ct(o,e),e+=4,i.encryption=ll(o,e),e+=1,i.uinType=ll(o,e),e+=1,i.uinLength=ct(o,e),e+=4,i.uin=i.uinLength>4?Po(o,e,i.uinLength-4):"",e+=i.uinLength-4;let t=o.slice(e);if(i.encryption===2){let r=new Uint8Array(16).fill(0);o=Gg(t,r),i.decrypted=!0,e=0}else o=t,e=0;return i.rspHeadLength=ct(o,e),e+=4,i.seqNo=ct(o,e),e+=4,i.retCode=ct(o,e),e+=4,i.retStrLength=ct(o,e),e+=4,i.retStr=i.retStrLength?Po(o,e,i.retStrLength-4):"",e+=i.retStrLength-4,i.serviceCmdLength=ct(o,e),e+=4,i.serviceCmd=i.serviceCmdLength?Po(o,e,i.serviceCmdLength-4):"",e+=i.serviceCmdLength-4,i.cookieLength=ct(o,e),e+=4,i.cookie=i.cookieLength?Po(o,e,i.cookieLength-4):"",e+=i.cookieLength-4,i.flag=ct(o,e),e+=4,i.busiBuffLength=ct(o,e),e+=4,i.busiBuff=i.busiBuffLength?Po(o,e,i.busiBuffLength-4):"",e+=i.busiBuffLength-4,i}catch(i){}}function Wm(o,i){let e=o[0]<<24|o[1]<<16|o[2]<<8|o[3],t=o[4]<<24|o[5]<<16|o[6]<<8|o[7];e=e>>>0,t=t>>>0;let r=Ca*Ra>>>0;for(let s=0;s<Ra;s++)t-=(e<<ml)+i[2]^e+r^(e>>>5)+i[3],t=t>>>0,e-=(t<<ml)+i[0]^t+r^(t>>>5)+i[1],e=e>>>0,r-=Ca,r=r>>>0;return new Uint8Array([e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255])}function Gg(o,i){let e=0,t=new Uint8Array(8).fill(0),r=new Uint8Array(o.slice(0,8)),s=Wm(r,i),n=s[0]&7,a=o.length-1-n-wo-Lo,c=new Uint8Array(a),l=0,u=t,m=o.slice(0,8);e=8;let h=1;h+=n;for(let g=1;g<=wo;)if(h<8)h++,g++;else if(h===8){let E=Tl(o,e,u,m,s,i);u=E.ivPreCrypt,m=E.ivCurCrypt,s=E.debiBuf,e=E.bufPos,h=0}let _=a;for(;_>0;)if(h<8)c[l++]=s[h]^u[h],h++,_--;else if(h===8){let g=Tl(o,e,u,m,s,i);u=g.ivPreCrypt,m=g.ivCurCrypt,s=g.debiBuf,e=g.bufPos,h=0}for(let g=1;g<=Lo;)if(h<8)s[h]^u[h],h++,g++;else if(h===8){if(e>=o.length)break;let E=Tl(o,e,u,m,s,i);if(!E.success)break;u=E.ivPreCrypt,m=E.ivCurCrypt,s=E.debiBuf,e=E.bufPos,h=0}return c}function Tl(o,i,e,t,r,s){if(i+8>o.length)return{success:!1};let n=new Uint8Array(t),a=o.slice(i,i+8),c=new Uint8Array(8);for(let u=0;u<8;u++)c[u]=r[u]^a[u];let l=Wm(c,s);return{success:!0,ivPreCrypt:n,ivCurCrypt:a,debiBuf:l,bufPos:i+8}}var Gm=typeof TextDecoder!="undefined"?new TextDecoder:void 0;function qi({url:o,body:i,method:e="POST",timeout:t,priority:r}){return new Promise((s,n)=>{if("fetch"in window)return fetch(o,{method:e,body:i,priority:r}).then(c=>c.clone().json().then(l=>({data:l}),()=>c.arrayBuffer().then(l=>({data:$m(new Uint8Array(l))||(Gm?Gm.decode(l):l)})))).then(s,n);let a=new XMLHttpRequest;a.onreadystatechange=()=>{if(a.readyState===4)if(a.status>=200&&a.status<300)try{let c=JSON.parse(a.response);s({data:c})}catch(c){s({data:a.response})}else n({status:a.status,statusText:a.statusText||"request failed!"})},a.timeout=t||5e3,a.open(e,o,!0),a.send(i)})}function El(o){return p(this,null,function*(){let i=U(),e=JSON.stringify(o);try{if(!CompressionStream||e.length<=2800)return e;let r=new Blob([e],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),a=yield(yield(yield new Response(r)).blob()).arrayBuffer();return R.debug(`compressJSON ${e.length} -> ${a.byteLength} ${U()-i}ms`),a}catch(t){return e}})}var qg=Object.prototype.hasOwnProperty;var Ii=o=>typeof o=="function",gt=o=>typeof o=="undefined";var wa=o=>typeof o=="boolean";var Sl=o=>o.isRemote;var Il=function(o){if(!o||typeof o!="object"||Object.prototype.toString.call(o)!="[object Object]")return!1;let i=Object.getPrototypeOf(o);if(i===null)return!0;let e=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function qm(o){if(o==null)return!0;if(typeof o=="boolean")return!1;if(typeof o=="number")return o===0;if(typeof o=="string"||typeof o=="function"||Array.isArray(o))return o.length===0;if(o instanceof Error)return o.message==="";if(Il(o))switch(Object.prototype.toString.call(o)){case"[object File]":case"[object Map]":case"[object Set]":return o.size===0;case"[object Object]":{for(let i in o)if(qg.call(o,i))return!1;return!0}}return!1}var Jg=0,jg=1,Jm=2;function Xg({retryFunction:o,settings:i,onError:e,onRetrying:t,onRetryFailed:r,onRetrySuccess:s,context:n}){return function(...a){let{retries:c=5,timeout:l=1e3}=i,u=0,m=-1,h=Jg,_=(g,E)=>p(this,null,function*(){let A=n||this;try{let k=yield o.apply(A,a);u>0&&s&&s.call(this,u),u=0,g(k)}catch(k){let re=()=>{clearTimeout(m),u=0,h=Jm,E(k)},P=()=>{h!==Jm&&u<(Ii(c)?c():c)?(u++,h=jg,Ii(t)&&t.call(this,u,re),m=window.setTimeout(()=>{m=-1,_(g,E)},Ii(l)?l(u):l)):(re(),Ii(r)&&r.call(this,k))};Ii(e)?e.call(this,{error:k,retry:P,reject:E,retryFuncArgs:a,retriedCount:u}):P()}});return new Promise(_)}}var Ai=Xg;var Er=class o{constructor(i){d(this,"_parentPath");d(this,"userId");d(this,"remoteUserId");d(this,"id");d(this,"sdkAppId");d(this,"type");d(this,"isLocal");this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=wa(i.isLocal)?i.isLocal:!0,this.type=this.isLocal?"":i.type}getFullId(){return this._parentPath&&this.id?`${this._parentPath}-${this.id}`:this._parentPath?this._parentPath:this.id}createChild(i){let e=new o({id:i.id,userId:gt(i.userId)?this.userId:i.userId,sdkAppId:gt(i.sdkAppId)?this.sdkAppId:i.sdkAppId,type:gt(i.type)?this.type:i.type,isLocal:gt(i.isLocal)?this.isLocal:i.isLocal,remoteUserId:gt(i.remoteUserId)?this.remoteUserId:i.remoteUserId});return e.bindParent(this),e}bindParent(i){let e=i.getFullId();this._parentPath!==e&&(this.debug(`bind logger parent: ${i.id}`),this._parentPath=e,this.userId=i.userId||this.userId,this.sdkAppId=i.sdkAppId||this.sdkAppId)}setUserId(i){this.userId=i}setSdkAppId(i){this.sdkAppId=i}log(i,e){let t=this.isLocal?this.userId:this.remoteUserId,r=this.getFullId();e.unshift(`[${this.isLocal?"\u2191":"\u2193"}${this.type&&this.type!=="main"?"*":""}${r}${t?`|${t}`:""}]`),R.log(i,e,gt(this.userId)||qm(this.userId),this.userId,this.sdkAppId)}info(...i){this.log(2,i)}debug(...i){this.log(1,i)}warn(...i){this.log(3,i)}error(...i){this.log(4,i)}};var Ko={};Vi(Ko,{ANDROID_VERSION:()=>xa,CHROME_MAJOR_VERSION:()=>qe,CHROME_VERSION:()=>Ka,EDGE_VERSION:()=>Va,EDG_MAJOR_VERSION:()=>Cl,EDG_VERSION:()=>Fa,ELECTRON_MAJOR_VERSION:()=>Nl,FIREFOX_MAJOR_VERSION:()=>qo,FIREFOX_VERSION:()=>Ua,HUAWEI_VERSION:()=>za,IE_VERSION:()=>Kg,IOS_MAIN_VERSION:()=>et,IOS_VERSION:()=>Tt,IPADQQB_VERSION:()=>ja,IS_ANDROID:()=>_e,IS_ANDROID_WEBVIEW:()=>rT,IS_ANY_SAFARI:()=>Ft,IS_CHROME:()=>Zo,IS_CHROME_OS:()=>Rl,IS_CHROMIUM_BASE:()=>$e,IS_DESKTOP_IOS_CHROME:()=>kl,IS_EDG:()=>Jo,IS_EDGE:()=>zr,IS_ELECTRON:()=>tT,IS_FIREFOX:()=>K,IS_HEADLESS_CHROME:()=>vl,IS_HONOR:()=>bl,IS_HUAWEI:()=>rn,IS_HUAWEIBROWSER:()=>tn,IS_IE:()=>Qm,IS_IE8:()=>Zg,IS_IOS:()=>ge,IS_IOS_13_OR_14:()=>Ol,IS_IOS_15_1:()=>Ml,IS_IOS_CHROME:()=>js,IS_IPAD:()=>Go,IS_IPADQQB:()=>Zs,IS_IPAD_PRO:()=>Al,IS_IPHONE:()=>Sr,IS_IPOD:()=>zm,IS_LINUX:()=>Ks,IS_LOCAL:()=>oi,IS_MAC:()=>ri,IS_MACQQB:()=>Ys,IS_MIBROWSER:()=>en,IS_MQQB:()=>Xo,IS_NATIVE_ANDROID:()=>Yg,IS_OLD_ANDROID:()=>Qg,IS_OPENHARMONY:()=>Qo,IS_OPPOBROWSER:()=>zo,IS_SAFARI:()=>Re,IS_SAFARI_15_1:()=>oT,IS_SAMSUNGBROWSER:()=>on,IS_SOGOU:()=>zs,IS_SOGOUM:()=>Xs,IS_TBS:()=>ii,IS_UCBROWSER:()=>yl,IS_VIVOBROWSER:()=>sn,IS_WECHAT:()=>ji,IS_WIN:()=>Qr,IS_WQQB:()=>Qs,IS_WX:()=>eT,IS_X5MQQB:()=>jo,IS_XWEB:()=>Ji,MACQQB_VERSION:()=>Ja,MI_VERSION:()=>Xa,MQQB_VERSION:()=>Wo,OPENHARMONY_VERSION:()=>iT,OPPO_VERSION:()=>Ya,SAFARI_VERSION:()=>Xi,SAMSUNG_VERSION:()=>Qa,SOGOUM_VERSION:()=>Ba,SOGOU_VERSION:()=>Ha,TBS_VERSION:()=>$a,UA_DATA_STRING:()=>ti,USER_AGENT:()=>Vt,VIVO_VERSION:()=>Za,WECHAT_VERSION:()=>Ga,WQQB_VERSION:()=>qa,XWEB_VERSION:()=>Wa,browserInfo:()=>Ci,getBrowserCoreNumber:()=>wl,getBrowserInfo:()=>Ym,getChromeMajorVersion:()=>Yo,getDeviceModel:()=>si,getDeviceModelFromUA:()=>ec,getGPUInfo:()=>Pl,getOSName:()=>tc,getOSNumber:()=>Zr,getOSString:()=>ni,getOSType:()=>sT,getTerminalType:()=>Ll,getUserAgentData:()=>Yr,isLocalStorageEnabled:()=>zi,isMobile:()=>an,isVersionLargerThan:()=>Dl,isVersionSmallerThan:()=>nn});var Vt=typeof navigator=="undefined"?"":navigator.userAgent,Z=o=>new RegExp(o,"i").test(Vt),we=o=>{if(Z(o)){let i=new RegExp(`${o}\\/([\\d.]+)`),e=Vt.match(i);if(e&&e[1])return e[1]}return""},La=o=>{if(Z(o)){let i=new RegExp(`${o}\\/(\\d+)`),e=Vt.match(i);if(e&&e[1])return parseFloat(e[1])}return NaN},jm=/AppleWebKit\/([\d.]+)/i.exec(Vt),zg=jm?parseFloat(jm[1]):NaN,Go=Z("iPad"),Al=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Z("Macintosh"),Sr=Z("iPhone")&&!Go,zm=Z("iPod"),ge=Sr||Go||zm||Al,_e=Z("Android"),xa=function(){if(_e){let o=Vt.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(o){let i=o[1]&&parseFloat(o[1]),e=o[2]&&parseFloat(o[2]);if(i&&e)return parseFloat(`${o[1]}.${o[2]}`);if(i)return i}}return NaN}(),Qg=_e&&Z("webkit")&&xa<2.3,Yg=_e&&xa<5&&zg<537,K=Z("Firefox"),Ua=we("Firefox"),qo=La("Firefox"),zr=Z("Edge"),Va=we("Edge"),Jo=Z("Edg"),Fa=we("Edg"),Cl=La("Edg"),Xs=Z("SogouMobileBrowser"),Ba=we("SogouMobileBrowser"),zs=Z("MetaSr\\s"),Ha=we("MetaSr\\s"),ii=Z("TBS"),$a=we("TBS"),Ji=Z("XWEB"),Wa=we("XWEB"),Zg=Z("MSIE\\s8\\.0"),Qm=Z("MSIE\\/\\d+"),Kg=function(){if(Qm){let o=/MSIE\s(\d+)\.\d/.exec(Vt),i=o&&parseFloat(o[1]);return!i&&/Trident\/7.0/i.test(Vt)&&/rv:11.0/.test(Vt)&&(i=11),i}return NaN}(),ji=Z("(micromessenger|webbrowser)"),Ga=we("MicroMessenger"),jo=!ii&&Z("MQQBrowser")&&Z("COVC"),Xo=!ii&&Z("MQQBrowser")&&!Z("COVC"),Wo=Xo||jo?we("MQQBrowser"):"",Qs=!ii&&Z(" QQBrowser"),qa=we(" QQBrowser"),Ys=!ii&&Z("QQBrowserLite"),Ja=we("QQBrowserLite"),Zs=!ii&&Z("MQBHD"),ja=we("MQBHD"),Qr=Z("Windows"),ri=!ge&&Z("MAC OS X"),Ks=!_e&&Z("Linux"),Rl=Z("CrOS"),eT=Z("MicroMessenger"),yl=Z("UCBrowser"),tT=Z("Electron"),en=Z("MiuiBrowser"),Xa=we("MiuiBrowser"),tn=Z("HuaweiBrowser"),rn=Z("Huawei")||Z("HUAWEI"),bl=Z("Honor")||Z("HONOR"),za=we("HuaweiBrowser"),on=Z("SamsungBrowser"),Qa=we("SamsungBrowser"),zo=Z("HeyTapBrowser"),Ya=we("HeyTapBrowser"),sn=Z("VivoBrowser"),Za=we("VivoBrowser"),Qo=Z("OpenHarmony"),iT=we("OpenHarmony"),Yo=()=>La("Chrome"),js=Z("CriOS"),$e=Z("Chrome"),Zo=!zr&&!zs&&!Xs&&!ii&&!Ji&&!Jo&&!Qs&&!en&&!tn&&!on&&!zo&&!sn&&$e,vl=Z("HeadlessChrome"),qe=Yo(),Ka=we("Chrome"),Nl=La("Electron"),Re=!$e&&!Xo&&!jo&&!Ys&&!Zs&&Z("Safari"),Ft=Re||ge,Xi=we("Version"),rT=/Android.*(wv|.0.0.0)/.test(Vt),Tt=(()=>{if(Al)return Xi;if(ge){let o=Vt.match(/OS (\d+)_(\d+)/i);if(o&&o[1]){let i=o[1];return o[2]&&(i+=`.${o[2]}`),i}}return""})();function nn(o,i){let e=o.split(".").map(r=>Number(r)),t=i.split(".").map(r=>Number(r));for(let r=0;r<Math.max(e.length,t.length);r++){let s=e[r]||0,n=t[r]||0;if(s<n)return!0;if(s>n)return!1}return!1}function Dl(o,i,e=!1){let t=o.split(".").map(s=>Number(s)),r=i.split(".").map(s=>Number(s));for(let s=0;s<Math.max(t.length,r.length);s++){let n=t[s]||0,a=r[s]||0;if(n>a)return!0;if(n<a)return!1}return e}var et=Number(Tt.split(".")[0]),oT=Xi==="15.1",Ml=Tt==="15.1",Ol=(()=>{let o=Number(Tt.split(".")[0]);return o===14||o===13})(),kl=js&&Xi==="11.1.1",oi=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",zi=(()=>{let o;return()=>{if(typeof o=="undefined")try{o=!!window.localStorage}catch(i){o=!1}return o}})(),Ci=Ym();function Ym(){let o=new Map([[K,["Firefox",Ua]],[Jo,["Edg",Fa]],[Zo,["Chrome",Ka]],[js,["ChiOS",we("CriOS")]],[Re&&!js,["Safari",Xi]],[ii,["TBS",$a]],[Ji,["XWEB",Wa]],[ji&&Sr,["WeChat",Ga]],[Qs,["QQ(Win)",qa]],[Xo,["QQ(Mobile)",Wo]],[jo,["QQ(Mobile X5)",Wo]],[Ys,["QQ(Mac)",Ja]],[Zs,["QQ(iPad)",ja]],[en,["MI",Xa]],[tn,["HW",za]],[on,["Samsung",Qa]],[zo,["OPPO",Ya]],[sn,["VIVO",Za]],[zr,["EDGE",Va]],[Xs,["SogouMobile",Ba]],[zs,["Sogou",Ha]]]),i="unknown",e="unknown";return o.has(!0)&&([i,e]=o.get(!0)),{name:i,version:e}}var me=null;function an(){return me&&typeof me.mobile=="boolean"?me.mobile:_e||ge||Sr||Go||Qo}var ti="";function Yr(){return p(this,null,function*(){if(me)return me;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return me=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),me&&!ti&&(ti=`UAData: ${me.platform}/${me.platformVersion}`,me.architecture&&me.bitness&&(ti+=` ${me.architecture}/${me.bitness}`),me.mobile&&(ti+=" mobile"),me.model&&(ti+=` model: ${me.model.replace(/\s+/g,"/")}`),me.fullVersionList&&(ti+=` ${me.fullVersionList.filter(o=>o.brand!=="Not/A)Brand").map(o=>`${o.brand}/${o.version}`).join(",")}`)),me}catch(o){return null}})}function Pl(){try{let o=document.createElement("canvas"),i=o.getContext("webgl")||o.getContext("experimental-webgl");if(!i)return"";let e=i.getExtension("WEBGL_debug_renderer_info");if(e){let t=i.getParameter(e.UNMASKED_VENDOR_WEBGL),r=i.getParameter(e.UNMASKED_RENDERER_WEBGL);return`${t} ${r}`}return""}catch(o){return""}}function si(){return(me==null?void 0:me.model)||ec()||""}function ec(){let o=/;\s*([^;)]+)\s+Build\//,i=Vt.match(o);return i!=null&&i[1]?i[1].trim():null}var Xm=new Map([[_e,"Android"],[ge,"iOS"],[Qr,"Windows"],[ri,"MacOS"],[Ks,"Linux"],[Rl,"ChromeOS"]]),tc=function(){return Xm.get(!0)?Xm.get(!0):me?me.platform:"unknown"};function Zr(){return Qr?1:_e?2:ri?3:ge?4:Ks?5:Rl?6:Qo?7:0}function wl(){return ji||Ji?4:$e?1:Re?2:K?3:0}var ni=()=>{let o=tc();return me!=null&&me.platformVersion?o+=`/${me.platformVersion}`:ge?o+=`/${Tt}`:_e&&(o+=`/${xa}`),o+=`/${Ci.name}/${Re&&!js?Ci.version:Ci.version.split(".")[0]}`,me!=null&&me.architecture&&(o+=`/${me.architecture}`),o};function Ll(){return _e?4:Sr?2:Go?3:ri?12:Qr?5:Ks?13:Qo?22:1}function sT(){return _e?"Android":Sr?"iPhone":Go?"iPad":ri?"Mac":Qr?"Windows":Ks?"Linux":"unknown"}var Zm=Ge(at(),1),nT=new Zm.default,S=nT;var mt=(W=>(W.ROOM_DESTROY="1",W.JOIN_START="21",W.JOIN_SCHEDULE_SUCCESS="22",W.JOIN_SIGNAL_CONNECTION_START="23",W.JOIN_SIGNAL_CONNECTION_END="24",W.JOIN_SEND_CMD="25",W.JOIN_RECEIVED_CMD_RES="26",W.JOIN_SUCCESS="27",W.JOIN_FAILED="28",W.LEAVE_START="51",W.LEAVE_SEND_CMD="52",W.LEAVE_SUCCESS="53",W.PUBLISH_START="61",W.SEND_FIRST_VIDEO_FRAME="62",W.PUBLISH_FAILED="63",W.SUBSCRIBE_START="81",W.SUBSCRIBE_SUCCESS="82",W.SUBSCRIBE_FAILED="84",W.UNSUBSCRIBE_SUCCESS="83",W.LOCAL_TRACK_CAPTURE_START="101",W.LOCAL_TRACK_CAPTURE_SUCCESS="102",W.LOCAL_TRACK_CAPTURE_FAILED="103",W.LOCAL_TRACK_PUBLISHED="104",W.LOCAL_TRACK_UNPUBLISHED="105",W.LOCAL_TRACK_REPLACED="106",W.SWITCH_DEVICE_SUCCESS="107",W.TRACK_MUTED="108",W.TRACK_UNMUTED="109",W.REMOTE_TRACK_SUBSCRIBED="110",W.REMOTE_TRACK_UNSUBSCRIBED="111",W.LOCAL_TRACK_RECAPTURE="112",W.LOCAL_AUDIO_STARTED="113",W.LOCAL_AUDIO_STOPPED="114",W.REMOTE_AUDIO_STARTED="115",W.REMOTE_AUDIO_STOPPED="116",W.PLAY_TRACK_START="151",W.PLAYER_STATE_CHANGED="152",W.VIDEO_LOADED_DATA="153",W.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",W.AUDIO_CONTEXT_LONG_SUSPENDED="155",W.REMOTE_VIDEO_PLAY_START="156",W.REMOTE_VIDEO_PLAY_FINISH="157",W.SIGNAL_CONNECTION_STATE_CHANGED="201",W.PEER_CONNECTION_STATE_CHANGED="202",W.SINGLE_CONNECTION_STAT="203",W.SPC_RECONNECTED="204",W.HEARTBEAT_REPORT="251",W.RECEIVED_PUBLISHED_USER_LIST="252",W.REMOTE_PUBLISH_STATE_CHANGED="253",W.AUDIO_LEVEL_INTERVAL="260",W.NETWORK_QUALITY="261",W.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",W.QUALITY_LIMITATION_CHANGED="263",W.LOG="264",W.AUDIO_PROCESSOR_DEBUG="265",W.SSO_SWITCH="266",W.SEI_MESSAGE="267",W.SWITCH_ROOM_START="401",W.SWITCH_ROOM_SUCCESS="407",W.SWITCH_ROOM_FAILED="408",W))(mt||{});var C=mt;var xl=class{constructor(){d(this,"enable",!1);d(this,"ssoFailCount",0);S.on("22",({schedule:i})=>{var e;(e=i==null?void 0:i.config)!=null&&e.sso&&S.emit("266",{enable:!0})}),S.on("266",({enable:i})=>{this.enable=i})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&S.emit("266",{enable:!1})}},Ir=new xl;var aT="%cTRTC%c%s",cT="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",dT="display: inline",ic=class ic{constructor(){d(this,"_isEnableUploadLog",!0);d(this,"_localJoinedUser",new Map);d(this,"_queue",[]);d(this,"_timeoutId",-1);d(this,"_logLevel",1);d(this,"_logLevelToUpload",2);!Do&&!xs&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){S.on(C.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var e;(e=i==null?void 0:i.config)!=null&&e.logLevelToUpload&&Xt[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),S.on(C.JOIN_START,({params:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),S.on(C.LEAVE_SUCCESS,({room:i})=>{this.deleteJoinedUser(i.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(i){this._localJoinedUser.set(i.userId,i),this.startUpload()}deleteJoinedUser(i){this._localJoinedUser.delete(i)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),5e3)}getLogsToUpload(){let i={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return i;let e=0;for(;e<this._queue.length&&e!==50;e++){let t=this._queue[e];if(t.forAllJoinedClients)this._localJoinedUser.forEach(({userId:r,sdkAppId:s})=>{i.map.has(r)?i.map.get(r).logs.push(t):i.map.set(r,{userId:r,sdkAppId:s,logs:[t]})});else if(ie(t.userId)&&z(t.sdkAppId)){let{userId:r,sdkAppId:s}=t;i.map.has(r)?i.map.get(r).logs.push(t):i.map.set(r,{userId:r,sdkAppId:s,logs:[t]})}}return i.map.size>0&&(i.splicedQueue=this._queue.splice(0,e)),i}upload(){return p(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:i,splicedQueue:e}=this.getLogsToUpload();if(i.size===0)return;try{let r=[...i.values()];for(let s=0;s<r.length;s++){let{userId:n,sdkAppId:a,logs:c}=r[s],l={timestamp:la(),sdkAppId:String(a),userId:n,version:He,log:c.map(h=>h.log).join(`
|
|
5
|
+
`}});var Zh=Ui(lr=>{"use strict";var Co=u_(),lI=m_();lr.write=lI;lr.parse=Co.parse;lr.parseParams=Co.parseParams;lr.parseFmtpConfig=Co.parseFmtpConfig;lr.parsePayloads=Co.parsePayloads;lr.parseRemoteCandidates=Co.parseRemoteCandidates;lr.parseImageAttributes=Co.parseImageAttributes;lr.parseSimulcastStreamList=Co.parseSimulcastStreamList});import V4 from"webrtc-adapter";var Kf=Ge(at());var gm=(B=>(B[B.INVALID_PARAMETER=4096]="INVALID_PARAMETER",B[B.INVALID_OPERATION=4097]="INVALID_OPERATION",B[B.NOT_SUPPORTED=4098]="NOT_SUPPORTED",B[B.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",B[B.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",B[B.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",B[B.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",B[B.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",B[B.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",B[B.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",B[B.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",B[B.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",B[B.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",B[B.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",B[B.CLIENT_BANNED=16448]="CLIENT_BANNED",B[B.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",B[B.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",B[B.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",B[B.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",B[B.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",B[B.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",B[B.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",B[B.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",B[B.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",B[B.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",B[B.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",B[B.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",B[B.API_CALL_ABORTED=16461]="API_CALL_ABORTED",B[B.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",B[B.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",B[B.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",B[B.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",B[B.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",B[B.UNKNOWN=65535]="UNKNOWN",B))(gm||{}),I=gm;var ng=function(o){for(let i in I)if(I[i]===o)return i;return"UNKNOWN"},ws=class extends Error{constructor({name:e="RtcError",message:t,code:r=I.UNKNOWN,extraCode:s=0,constraint:n}){let a=`<${ng(r)} 0x${r.toString(16)}>`,c=`${t}${n?` constraint: ${n}`:""}${t!=null&&t.includes(a)?"":` ${a}`}`;super(c);d(this,"code");d(this,"extraCode");d(this,"message");d(this,"originMessage");d(this,"name");d(this,"constraint");this.code=r,this.extraCode=s,this.name=e,this.message=c,this.constraint=n,this.originMessage=t}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},D=ws;var Gd=0,Tm=!0,da=function(o){Gd=o;let i=new Date;i.setTime(i.getTime()+o),R[Tm?"info":"debug"](`baseTime from server: ${i} offset: ${o}`),Tm=!1},Em=function(){return Gd},Fi=function(){return Date.now()+Gd},la=function(){let o=new Date;return o.setTime(Fi()),o.toLocaleString()},No=function(o){let i=String(o.getMilliseconds());return"padStart"in String.prototype&&(i=i.toString().padStart(3,"0")),`${o.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${i}`};var vt={};Vi(vt,{REPORT_TYPE:()=>$o,buildSSOPackage:()=>Gi,bytes2ms:()=>Mm,calculateScaleResolutionDownNumber:()=>Ho,concatArrayBuffers:()=>ka,convertObjectNumberToInt:()=>Js,copyProperties:()=>Dm,deepClone:()=>Gr,deepCloneBasic:()=>ya,deepMerge:()=>ei,delay:()=>Ke,fibonacci:()=>Jr,formatedTime:()=>Fm,getConstructorName:()=>xo,getContainerFromElement:()=>Vm,getEnv:()=>bm,getFirst16Bits:()=>Hm,getInternalVersion:()=>xm,getLast16Bits:()=>Pa,getLoggerUrl:()=>Wi,getMediaStreamTrackInfo:()=>Oa,getMuteStateFromFlag:()=>Kt,getNetworkType:()=>ba,getNumNetworkType:()=>qr,getReconnectionTimeout:()=>Zt,getStringByteLength:()=>qs,getTurnServer:()=>Um,getUint32Version:()=>Na,getValueType:()=>Me,getViewListFromView:()=>Fo,glog:()=>_l,ipv4ToUint32:()=>Vo,isArray:()=>Ie,isAudioWorkletSupported:()=>wm,isBoolean:()=>he,isConstructor:()=>jr,isEmpty:()=>Uo,isFunction:()=>le,isLangChinese:()=>Yt,isMediaStreamTrack:()=>km,isNumber:()=>z,isObject:()=>yt,isOverseaSdkAppId:()=>Ut,isPlainObject:()=>dt,isPortrait:()=>gl,isPromise:()=>Tr,isRemoteTrack:()=>Pm,isRotate90Or270:()=>bt,isSetSinkIdSupported:()=>Lm,isString:()=>ie,isUndefined:()=>T,loadImage:()=>Bo,loadVideo:()=>Bm,ms2bytes:()=>Om,ms2samples:()=>fl,normalizeUrl:()=>Ma,performanceNow:()=>U,promiseAny:()=>Xr,samples2ms:()=>pl,setNetworkTypeFromWebRTC:()=>va,stringify:()=>_t,stringifyIncludeValue:()=>Gs,throttlePromise:()=>Da});var ol={};Vi(ol,{AUDIO_MUTE_BIT:()=>Ta,AUDIO_STAT_BIT:()=>_r,AUX_STAT_BIT:()=>Br,AUX_STREAM_MSID:()=>Yd,BACKEND_ENV:()=>ga,BASE_DOC_URL:()=>ft,BASE_HOST:()=>Sm,CAPABILITIES_KEYS:()=>Ia,CLASS_NAME:()=>Ng,CLOUD_CONSOLE_URL:()=>lg,CROSS_ROOM_BIT:()=>Qd,DATA_FREEZE_TIMING:()=>Sa,DOC_BILLING_CN:()=>ua,DOC_BILLING_OVERSEA:()=>ha,DOC_URL:()=>ug,DTLS_STATE_UNKNOWN:()=>Qt,ENV_NAME:()=>Bi,EXCHANGE_SDP_TIMEOUT:()=>il,IS_WORKER:()=>Do,IS_WORKLET:()=>xs,KIBANA_EVENT:()=>Ze,LOCAL_STREAM_PUBLISH_STATE:()=>Am,LOGGER_CMD_TYPE:()=>mr,LOGGER_DOMAIN:()=>Jd,LOGGER_DOMAIN_OVERSEA:()=>jd,LOG_LEVEL:()=>Xt,LOG_LEVEL_NAME:()=>Mg,MAIN_STREAM_MSID:()=>Fs,MAX_RTT:()=>$s,MICROPHONE_COMMUNICATIONS:()=>Dg,MICROPHONE_DEFAULT:()=>Wr,MUTE_ALL_BIT:()=>pg,NAME:()=>f,NETWORK_TYPE:()=>ma,NOT_SUPPORTED_H264:()=>Hr,PAUSED_RETRY_COUNT:()=>$r,PEERCONNECTION_CONNECTING_TIMEOUT:()=>Bs,PEER_CONNECTION_STATE:()=>Ce,PEER_LEAVE_REASON:()=>rl,RECOVER_CAPTURE_INTERVAL:()=>ko,REMOTE_STREAM_TYPE_AUX:()=>Kd,REMOTE_STREAM_TYPE_MAIN:()=>Zd,RENDER_FREEZE_TIMING:()=>Rg,SCHEDULE_DOMAIN:()=>$i,SCHEDULE_TIMEOUT:()=>vg,SDP_SEMANTICS_PLAN_B:()=>Mo,SDP_SEMANTICS_UNIFIED_PLAN:()=>gr,SECOND_HOST:()=>cg,SIGNAL_PING_PONG_INTERVAL:()=>mg,SIGNAL_PING_TIMEOUT:()=>hg,SIGNAL_RECONNECTION_COUNT:()=>Ag,SMALL_STAT_BIT:()=>Vs,SPEAKER_DEFAULT:()=>Hs,STORAGE_EXPIRES_TIME:()=>pa,STREAM_TYPE_BIG:()=>yg,STREAM_TYPE_SMALL:()=>bg,SUBSCRIBE_SMALL_RETRY_COUNT:()=>Oo,SYNC_USER_LIST_INTERVAL:()=>Cg,Scene:()=>Ei,THIRD_HOST:()=>dg,TRANSPORT_DIRECTION:()=>ne,TRTC_ERROR_ASSISTANCE:()=>Xd,TRTC_QUALITY_BAD:()=>Eg,TRTC_QUALITY_DISCONNECTED:()=>Ig,TRTC_QUALITY_EXCELLENT:()=>_g,TRTC_QUALITY_GOOD:()=>gg,TRTC_QUALITY_POOR:()=>Tg,TRTC_QUALITY_UNKNOWN:()=>fg,TRTC_QUALITY_VERY_BAD:()=>Sg,UPDATE_OFFER_TIMEOUT:()=>tl,VIDEO_MUTE_BIT:()=>Ea,VIDEO_STAT_BIT:()=>fr,audioProfileMap:()=>fa,defaultBigVideoProfile:()=>pr,defaultSmallVideoProfile:()=>zd,getRetryCount:()=>Hi,getScriptDir:()=>ag,innerVersion:()=>Ls,loggerProxy:()=>Us,screenProfileMap:()=>_a,setLoggerProxy:()=>Fr,setRetryCount:()=>el,setVersion:()=>qd,version:()=>He,videoProfileMap:()=>zt});var Ls="4.15.00.1600",He="5.0.0";function qd(o){He=o;let[i,e,t]=o.split(".").map(r=>parseInt(r,10));Ls=`${i}.${Math.min(15,e)}.${Math.min(15,t)}.${e.toString().padStart(2,"0")}${t.toString().padStart(2,"0")}`}var Do=typeof importScripts!="undefined",xs=typeof registerProcessor!="undefined",ag=()=>{let o=Do?self.location.href:document.currentScript.src;return o.substring(0,o.lastIndexOf("/")+1)},Us="",Fr=o=>Us=o,Sm="web.sdk.qcloud.com",cg="web.sdk.tencent.cn",dg="web.sdk.cloud.tencent.cn",lg="https://console.cloud.tencent.com/trtc",ft=`https://${Sm}/trtc/webrtc/doc`,ug=`${ft}/zh-cn/`,ua="https://cloud.tencent.com/document/product/647/85386",ha="https://trtc.io/document/56025",Jd="https://yun.tim.qq.com",jd="https://apisgp.my-imcloud.com",Xd="trtc_error_assistance",mr={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},Bi={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},Xt=(n=>(n[n.TRACE=0]="TRACE",n[n.DEBUG=1]="DEBUG",n[n.INFO=2]="INFO",n[n.WARN=3]="WARN",n[n.ERROR=4]="ERROR",n[n.NONE=5]="NONE",n))(Xt||{}),hg=18e3,mg=2e3,ma={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5,"5g":6},pa=7*24*3600*1e3,fa={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:128},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},zt={"120p":{width:160,height:120,frameRate:15,bitrate:200},"120p_2":{width:160,height:120,frameRate:15,bitrate:100},"180p":{width:320,height:180,frameRate:15,bitrate:350},"180p_2":{width:320,height:180,frameRate:15,bitrate:150},"240p":{width:320,height:240,frameRate:15,bitrate:400},"240p_2":{width:320,height:240,frameRate:15,bitrate:200},"360p":{width:640,height:360,frameRate:15,bitrate:800},"360p_2":{width:640,height:360,frameRate:15,bitrate:400},"480p":{width:640,height:480,frameRate:15,bitrate:900},"480p_2":{width:640,height:480,frameRate:15,bitrate:500},"720p":{width:1280,height:720,frameRate:15,bitrate:1500},"1080p":{width:1920,height:1080,frameRate:15,bitrate:2e3},"1440p":{width:2560,height:1440,frameRate:30,bitrate:4860},"4K":{width:3840,height:2160,frameRate:30,bitrate:9e3}},pr=zt["480p_2"],zd=zt["120p_2"],_a={"480p":{width:640,height:480,frameRate:5,bitrate:900},"480p_2":{width:640,height:480,frameRate:30,bitrate:1e3},"720p":{width:1280,height:720,frameRate:5,bitrate:1200},"720p_2":{width:1280,height:720,frameRate:30,bitrate:3e3},"1080p":{width:1920,height:1080,frameRate:5,bitrate:1600},"1080p_2":{width:1920,height:1080,frameRate:30,bitrate:4e3}},f={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADSTART:"loadstart",LOADEDDATA:"loadeddata",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture",RESIZE:"resize",TIME_UPDATE:"timeupdate"},ne={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},ga={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Ei=(e=>(e.LIVE="live",e.RTC="rtc",e))(Ei||{}),fr=1,Vs=2,Br=4,_r=8,Ta=64,Ea=16,pg=112,Qd=128,Fs="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",Yd="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",Zd=f.MAIN,Kd=f.AUXILIARY,fg=0,_g=1,gg=2,Tg=3,Eg=4,Sg=5,Ig=6,Qt="unknown",Ce={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Im=1/0;function el(o){Im=o}function Hi(){return Im}var Ag=30,Ze={JOIN:"join",DELTA_JOIN:"delta-join",REJOIN:"rejoin",LEAVE:"leave",DELTA_LEAVE:"delta-leave",PUBLISH:"publish",DELTA_PUBLISH:"delta-publish",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",UPLINK_CONNECTION:"uplink-connection",UPLINK_RECONNECTION:"uplink-reconnection",DOWNLINK_CONNECTION:"downlink-connection",DOWNLINK_RECONNECTION:"downlink-reconnection",ON_TRACK:"ontrack",ICE_CONNECTION_STATE:"iceConnectionState",LOCAL_STREAM_INITIALIZE:"stream-initialize",SIGNAL_CONNECTION:"websocketConnectionState",SIGNAL_RECONNECTION:"websocketReconnectionState",UPDATE_STREAM:"update-stream",RECOVER_LOCAL_AUDIO_TRACK:"recover-local-audio-track",RECOVER_LOCAL_VIDEO_TRACK:"recover-local-video-track",RECOVER_SUBSCRIPTION:"recover-subscription",START_MIX_TRANSCODE:"start-mix-transcode",STOP_MIX_TRANSCODE:"stop-mix-transcode",PLAYER_ERROR:"player-error",SCHEDULE:"schedule",LOAD_WORKLET:"load-worklet",VIDEO_FROZEN_COUNT:"videoFrozenCount",GET_USER_MEDIA_RETRY:"getUserMedia-retry",VIDEO_ENCODE_FAILED_DURING_CALL:"video-encode-failed-during-call",AUDIO_ENCODE_FAILED_DURING_CALL:"audio-encode-failed-during-call"},Cg=1e4,tl=1e4,il=1e4,gr="unified-plan",Mo="plan-b",Hr=1028,Am=(t=>(t[t.UNPUBLISH=-1]="UNPUBLISH",t[t.PUBLISHING=0]="PUBLISHING",t[t.PUBLISHED=1]="PUBLISHED",t))(Am||{}),Sa=500,Rg=1e3,yg=f.BIG,bg=f.SMALL,Bs=10*1e3,$i={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_BACKUP:"intl-schedule.cloud-rtc.com"},vg=2e3,Ng={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},$r=5,Wr="default",Hs=Wr,Dg="communications",Mg=Object.keys(Xt),rl=["normal leave","timeout leave","kick","role change"],Oo=10,ko=2e3,Ia=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],$s=10*1e3;var Og=function(o,i,e,t){function r(s){return s instanceof e?s:new e(function(n){n(s)})}return new(e||(e=Promise))(function(s,n){function a(u){try{l(t.next(u))}catch(m){n(m)}}function c(u){try{l(t.throw(u))}catch(m){n(m)}}function l(u){u.done?s(u.value):r(u.value).then(a,c)}l((t=t.apply(o,i||[])).next())})},sl=Symbol(32),nl=Symbol(16),al=Symbol(8),Si=class{constructor(i){this.g=i,this.consumed=0,i&&(this.need=i.next().value)}setG(i){this.g=i,this.demand(i.next().value,!0)}consume(){this.buffer&&this.consumed&&(this.buffer.copyWithin(0,this.consumed),this.buffer=this.buffer.subarray(0,this.buffer.length-this.consumed),this.consumed=0)}demand(i,e){return e&&this.consume(),this.need=i,this.flush()}read(i){return Og(this,void 0,void 0,function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise((e,t)=>{var r;this.reject=t,this.resolve=n=>{delete this.lastReadPromise,delete this.resolve,delete this.need,e(n)},this.demand(i,!0)||(r=this.pull)===null||r===void 0||r.call(this,i)})})}readU32(){return this.read(sl)}readU16(){return this.read(nl)}readU8(){return this.read(al)}close(){var i;this.g&&this.g.return(),this.buffer&&this.buffer.subarray(0,0),(i=this.reject)===null||i===void 0||i.call(this,new Error("EOF")),delete this.lastReadPromise}flush(){if(!this.buffer||!this.need)return;let i=null,e=this.buffer.subarray(this.consumed),t=0,r=s=>e.length<(t=s);if(typeof this.need=="number"){if(r(this.need))return;i=e.subarray(0,t)}else if(this.need===sl){if(r(4))return;i=e[0]<<24|e[1]<<16|e[2]<<8|e[3]}else if(this.need===nl){if(r(2))return;i=e[0]<<8|e[1]}else if(this.need===al){if(r(1))return;i=e[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(r(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(e.subarray(0,t)),i=this.need}else if(this.g){this.g.throw(new Error("Unsupported type"));return}}else{if(r(this.need.byteLength))return;new Uint8Array(this.need).set(e.subarray(0,t)),i=this.need}return this.consumed+=t,this.g?this.demand(this.g.next(i).value,!0):this.resolve&&this.resolve(i),i}write(i){if(i instanceof Uint8Array?this.malloc(i.length).set(i):"buffer"in i?this.malloc(i.byteLength).set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)):this.malloc(i.byteLength).set(new Uint8Array(i)),this.g||this.resolve)this.flush();else return new Promise(e=>this.pull=e)}writeU32(i){this.malloc(4).set([i>>24&255,i>>16&255,i>>8&255,i&255]),this.flush()}writeU16(i){this.malloc(2).set([i>>8&255,i&255]),this.flush()}writeU8(i){this.malloc(1)[0]=i,this.flush()}malloc(i){if(this.buffer){let e=this.buffer.length,t=e+i;if(t<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,t);else{let r=new Uint8Array(t);r.set(this.buffer),this.buffer=r}return this.buffer.subarray(e,t)}else return this.buffer=new Uint8Array(i),this.buffer}};Si.U32=sl;Si.U16=nl;Si.U8=al;var kg=128,Pg=127,$I=~Pg,WI=Math.pow(2,31);function cl(o){let i=new Si;for(;o>=128;)i.malloc(1)[0]=o&255|kg,o>>>=7;return i.malloc(1)[0]=o&255,i.buffer||new Uint8Array(0)}function Aa(o,i=0){let e=new Si,t=i<<3;switch(typeof o){case"boolean":let r=e.malloc(2);r[0]=t,r[1]=o?1:0;break;case"number":e.malloc(1)[0]=t,e.write(cl(o));break;case"string":e.malloc(1)[0]=t|2;let s=new TextEncoder().encode(o);e.write(cl(s.length));let n=e.malloc(s.length);for(let c=0;c<s.length;c++)n[c]=s[c];break;case"object":let a=new Si;if(Array.isArray(o))for(let c=0;c<o.length;c++){let l=Aa(o[c],c+1);l&&a.write(l)}else{let c=1;for(let l in o){let u=Aa(o[l],c++);u&&a.write(u)}}i===0?a.buffer&&e.write(a.buffer):(e.malloc(1)[0]=t|2,a.buffer&&(e.write(cl(a.buffer.length)),e.write(a.buffer)))}return e.buffer||new Uint8Array(0)}var Ws=class{constructor(){d(this,"buffer");this.buffer=[]}get data(){return this.buffer}get length(){return this.buffer.length}writeInt32(i){this.buffer.push(i>>>24&255),this.buffer.push(i>>>16&255),this.buffer.push(i>>>8&255),this.buffer.push(i&255)}writeInt16(i){this.buffer.push(i>>>8&255),this.buffer.push(i&255)}writeByte(i){this.buffer.push(i&255)}writeBytes(i){for(let e=0;e<i.length;e++)this.buffer.push(i[e])}};function dl(o,i,e){o[e]=i>>>24&255,o[e+1]=i>>>16&255,o[e+2]=i>>>8&255,o[e+3]=i&255}function ct(o,i){return o[i]<<24|o[i+1]<<16|o[i+2]<<8|o[i+3]}function ll(o,i){return o[i]}function Po(o,i,e){return new TextDecoder().decode(wg(o,i,e))}function wg(o,i,e){return o.slice(i,i+e)}var ul=0,Ca=2654435769,Ra=16,ml=4,wo=2,Lo=7;function Lg(o,i,e,t="AVQualityReportSvc.C2S",r=2e3,s=2,n=30){return{version:r,encryption:s,d2:"",d2Len:0,uinType:n,uin:"",uinLen:0,reqHead:{seqNumber:e,appId:o,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:t,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:i}}function Cm(o,i){let e=new Ws,t=Lg(i,o,ul);ul=ul+1&2147483647,e.writeInt32(0),e.writeInt32(t.version),e.writeByte(t.encryption);let r=new TextEncoder().encode(t.d2);e.writeInt32(r.length+4),r&&e.writeBytes(r),e.writeByte(t.uinType);let s=new TextEncoder().encode(t.uin);e.writeInt32(s.length+4),s.length&&e.writeBytes(s);let n=new Ws;n.writeInt32(0),n.writeInt32(t.reqHead.seqNumber),n.writeInt32(t.reqHead.appId),n.writeByte(t.reqHead.appId>>>24&255),n.writeByte(t.reqHead.appId>>>16&255),n.writeByte(t.reqHead.appId>>>8&255),n.writeByte(t.reqHead.appId&255);for(let re=4;re<16;re++)n.writeByte(0);let a=new TextEncoder().encode(t.reqHead.a2);n.writeInt32(a.length+4),a.length&&n.writeBytes(a);let c=new TextEncoder().encode(t.reqHead.serviceCmd);n.writeInt32(c.length+4),c.length&&n.writeBytes(c);let l=new TextEncoder().encode(t.reqHead.cookie);n.writeInt32(l.length+4),l.length&&n.writeBytes(l);let u=new TextEncoder().encode(t.reqHead.imei);n.writeInt32(u.length+4),u.length&&n.writeBytes(u);let m=new TextEncoder().encode(t.reqHead.ksid);n.writeInt32(m.length+4),m.length&&n.writeBytes(m);let h=new TextEncoder().encode(t.reqHead.clientVersionInfo);n.writeInt16(h.length+2),h.length&&n.writeBytes(h);let _=n.length;n.data[0]=_>>>24&255,n.data[1]=_>>>16&255,n.data[2]=_>>>8&255,n.data[3]=_&255,ie(o)&&(o=new TextEncoder().encode(o)),n.writeInt32(o.length+4),o.length&&n.writeBytes(o);let g=new Uint8Array(n.data),E=null;t.encryption===1?E=new TextEncoder().encode(t.uin):t.encryption===2&&(E=new Uint8Array(16)),E&&(g=xg(g,E)),e.writeBytes(g);let A=new Uint8Array(e.data),k=A.length;return A[0]=k>>>24&255,A[1]=k>>>16&255,A[2]=k>>>8&255,A[3]=k&255,A}function xg(o,i){let e=o.length,r=(e+1+wo+Lo)%8;r&&(r=8-r);let s=e+1+wo+Lo+r,n=new Uint8Array(s),a=0,c=new Uint8Array(8),l=new Uint8Array(8),u=new Uint8Array(8),m=0;c[0]=Math.floor(Math.random()*256)&248|r,m=1;for(let _=0;_<r;_++)c[m]=Math.floor(Math.random()*256)&255,m+=1;for(let _=0;_<wo;)if(m<8&&(c[m]=Math.floor(Math.random()*256)&255,m+=1,_+=1),m===8){hl(c,i,l,u,n,a),a+=8,m=0;for(let g=0;g<8;g++)u[g]=n[a-8+g]}let h=0;for(;h<e;)if(m<8&&(c[m]=o[h],m+=1,h+=1),m===8){hl(c,i,l,u,n,a),a+=8,m=0;for(let _=0;_<8;_++)u[_]=n[a-8+_]}for(let _=0;_<Lo;)if(m<8&&(c[m]=0,m+=1,_+=1),m===8){hl(c,i,l,u,n,a),a+=8,m=0;for(let g=0;g<8;g++)u[g]=n[a-8+g]}return n}function hl(o,i,e,t,r,s){for(let n=0;n<8;n++)o[n]^=t[n];Ug(o,i,r,s);for(let n=0;n<8;n++)r[s+n]^=e[n];for(let n=0;n<8;n++)e[n]=o[n]}function Ug(o,i,e,t){let r=ct(o,0),s=ct(o,4),n=[];for(let c=0;c<4;c++)n[c]=ct(i,c*4);let a=0;for(let c=0;c<Ra;c++)a+=Ca,a=a>>>0,r+=(s<<4)+n[0]^s+a^(s>>>5)+n[1],r=r>>>0,s+=(r<<4)+n[2]^r+a^(r>>>5)+n[3],s=s>>>0;dl(e,r,t),dl(e,s,t+4)}var bm=function(){return new URLSearchParams(location.search).get("trtc_env")||""},Ut=o=>Number(o)<14e8,Wi=function(o,i){let e;Us?e=Us:e=Ut(o)?jd:Jd;let t=Math.floor(Math.random()*hr(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${t}&sdkappid=${o}&cmdtype=${i}`},vm="unknown";function ba(){Fg();let{userAgent:o,connection:i}=navigator,e=(o.match(/NetType\/\S+/)||[])[0]||"";e=e.toLowerCase().replace("nettype/",""),e==="3gnet"&&(e="3g");let t=i&&i.type&&i.type.toLowerCase(),r=i&&i.effectiveType&&i.effectiveType.toLowerCase();return r==="slow-2"&&(r="2g"),t?Nm(t,r):vm}function Vg(){R.warn("netType changed",ba())}var Rm=!1;function Fg(){var o;Rm||(Rm=!0,(o=navigator.connection)==null||o.addEventListener("typechange",Vg))}function Nm(o,i){if(ma[o])return o;switch(o){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function va(o){vm=Nm(o)}function qr(){return ma[ba()]}function Dm(o,i){for(let e of Reflect.ownKeys(i))if(e!=="constructor"&&e!=="prototype"&&e!=="name"){let t=Object.getOwnPropertyDescriptor(i,e)||"";Object.defineProperty(o,e,t)}return o}function Mm(o,i=48e3){return pl(o/4,i)}function pl(o,i=48e3){return o*1e3/i}function Om(o,i=48e3){return fl(o,i)*4}function fl(o,i=48e3){return o*i/1e3}var _l=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},Yt=()=>{let o=navigator.language;return o=o.substring(0,2),o==="zh"},dt=function(o){if(!o||typeof o!="object"||Object.prototype.toString.call(o)!="[object Object]")return!1;let i=Object.getPrototypeOf(o);if(i===null)return!0;let e=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function Jr(o,i=1,e=1){return o<=1?e:Jr(o-1,e,i+e)}function Zt(o){return o>8?30*1e3:Jr(o)*1e3}function Me(o){return Reflect.apply(Object.prototype.toString,o,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var le=o=>typeof o=="function",T=o=>typeof o=="undefined",ie=o=>typeof o=="string",z=o=>typeof o=="number",he=o=>typeof o=="boolean",yt=o=>Me(o)==="object",Ie=o=>Me(o)==="array",km=o=>Me(o)==="MediaStreamTrack".toLowerCase(),Pm=o=>o.isRemote,Tr=o=>Me(o)==="promise",jr=o=>le(o)&&o.prototype.constructor===o,xo=o=>jr(o)?o.prototype.constructor.name:"",wm=typeof AudioWorkletNode!="undefined",Lm=typeof HTMLMediaElement!="undefined"&&"setSinkId"in HTMLMediaElement.prototype;function Xr(o){return new Promise((i,e)=>{let t=[];o.forEach(r=>{r.then(i).catch(s=>{t.push(s),t.length===o.length&&e(t)})})})}function U(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var ym=o=>+o<10?`0${o}`:o,xm=o=>{let i=o.match(/^\d+\.\d+\.\d+/)[0];if(!i)return o;let e=i.split("."),t=ym(e[1])+ym(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${t}`},Bg=Object.prototype.hasOwnProperty,{toString:iA}=Object.prototype;function Uo(o){if(o==null)return!0;if(typeof o=="boolean")return!1;if(typeof o=="number")return o===0;if(typeof o=="string"||typeof o=="function"||Array.isArray(o))return o.length===0;if(o instanceof Error)return o.message==="";if(dt(o))switch(Object.prototype.toString.call(o)){case"[object File]":case"[object Map]":case"[object Set]":return o.size===0;case"[object Object]":{for(let i in o)if(Bg.call(o,i))return!1;return!0}}return!1}function Kt(o,i){return{userId:i,hasAudio:!!(o&_r),hasVideo:!!(o&fr),hasAuxiliary:!!(o&Br),hasSmall:!!(o&Vs),audioMuted:!!(o&Ta),videoMuted:!!(o&Ea),audioAvailable:!!(o&_r)&&!(o&Ta),videoAvailable:!!(o&fr)&&!(o&Ea)}}function Um(o){let i={urls:o.url.startsWith("turn:")||o.url.startsWith("turns:")?o.url:`turn:${o.url}`};return!T(o.username)&&!T(o.credential)&&(i.username=o.username,i.credential=o.credential,i.credentialType="password",T(o.credentialType)||(i.credentialType=o.credentialType)),i}function Vo(o,i=!0){if(!ie(o))return 0;let e=o.split(".");return i?(Number(e[0])<<24|Number(e[1])<<16|Number(e[2])<<8|Number(e[3]))>>>0:(Number(e[3])<<24|Number(e[2])<<16|Number(e[1])<<8|Number(e[0]))>>>0}var ei=function(o,i,e,t){if(!(yt(o)&&yt(i)))return 0;let r=0,s=Object.keys(i),n;for(let a=0,c=s.length;a<c;a++)if(n=s[a],!(T(i[n])||e&&e.includes(n)))if(yt(o[n])&&yt(i[n]))r+=ei(o[n],i[n],e,t);else{if(t&&t.includes(i[n]))continue;o[n]!==i[n]&&(o[n]=Gr(i[n]),r+=1)}return r};function Gr(o){if(Ie(o)){let i=[];return o.forEach((e,t)=>{i[t]=Gr(e)}),i}if(yt(o)){let i={};return Object.keys(o).forEach(e=>{i[e]=Gr(o[e])}),i}return o}var Fo=o=>{let i=[];if(Ie(o))i=[...o];else if(ie(o)){let e=document.getElementById(o);e&&i.push(e)}else o&&i.push(o);return i},Vm=o=>ie(o)?document.getElementById(o):o,Hg=o=>{let i=c=>c<10?`0${c}`:`${c}`,e=o.getFullYear(),t=o.getMonth()+1,r=o.getDate(),s=i(o.getHours()),n=i(o.getMinutes()),a=i(o.getSeconds());return`${e}/${t}/${r} ${s}:${n}:${a}`},Fm=()=>Hg(new Date);function _t(o,{keysToInclude:i,keysToExclude:e}){try{if(Ie(o))return`[${o.map(n=>_t(n,{keysToInclude:i,keysToExclude:e})).join(",")}]`;if(!dt(o)||!Ie(i)&&!Ie(e))return JSON.stringify(o);let t={},r=new Set(i),s=new Set(e);return Object.keys(o).forEach(n=>{(s.size===0&&r.has(n)||r.size===0&&!s.has(n))&&(t[n]=dt(o[n])||Ie(o[n])?JSON.parse(_t(o[n],{keysToExclude:e,keysToInclude:i})):o[n])}),JSON.stringify(t)}catch(t){return"{}"}}function Gs(o,i=!1){let e=[];return Object.keys(o).forEach(t=>{i===o[t]&&e.push(t)}),_t(o,{keysToInclude:e})}function qs(o){return o.replace(/[\u4e00-\u9fa5]/g,"aa").length}var gl=()=>{var o,i,e,t;return(o=window.screen)!=null&&o.orientation?!!((t=(e=(i=window.screen)==null?void 0:i.orientation)==null?void 0:e.type)!=null&&t.includes("portrait")):window.orientation===0||window.orientation===180},Bo=o=>p(void 0,null,function*(){return new Promise((i,e)=>{let t;if(ie(o))t=new Image,t.crossOrigin="anonymous",t.src=o;else if(t=o,t.complete){i(t);return}t.onload=()=>i(t),t.onerror=()=>{e(new D({code:I.INVALID_PARAMETER,message:`load image failed, url: ${o}`}))}})}),Na=o=>{let i=o.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]<<0},Js=o=>(Object.keys(o).forEach(i=>{z(o[i])&&(i.startsWith("uint")||i.startsWith("int"))?o[i]=Math.floor(o[i]):(dt(o[i])||Ie(o[i]))&&Js(o[i])}),o);function Ke(o,i){return new Promise(e=>{let t=setTimeout(e,o);i&&i(t)})}function Da(o,i){let e=null;return function(...t){return e||(e=o.apply(i||this,t),e.finally(()=>e=null),e)}}function Ma(o){return o.replace(/(^|[^:])\/{2,}/g,"$1/")}function Oa(o){var i;try{let{width:e,height:t,frameRate:r,sampleRate:s,sampleSize:n,channelCount:a}=(i=o.getSettings)==null?void 0:i.call(o),c=o.kind===f.AUDIO?`${s}x${n}@${a}`:`${e}x${t}@${r}`,l=o.stats?` stats: ${JSON.stringify(o.stats).replaceAll('"',"")}`:"";return`${o.id} ${o.readyState} muted:${o.muted} ${o.kind} ${o.label} ${c}${l}`}catch(e){return""}}function Ho(o,i){return o.width*o.height===i.width*i.height?1:gl()&&i.width>i.height&&o.height>i.width?Math.max(o.width/i.height,o.height/i.width,1):Math.max(o.width/i.width,o.height/i.height,1)}function bt(o){return o===90||o===270}function Bm(o){return p(this,null,function*(){return new Promise((i,e)=>{let t=document.createElement("video");t.crossOrigin="anonymous",t.src=o,t.muted=!0,t.loop=!0,t.playsInline=!0,t.play().then(()=>i(t)),t.onerror=()=>{e(t.error)}})})}function ya(o,i=new WeakMap){if(typeof o!="object"||o===null)return o;if(i.has(o))return i.get(o);if(Array.isArray(o)){let e=[];return i.set(o,e),o.forEach((t,r)=>{e[r]=ya(t,i)}),e}if(Object.prototype.toString.call(o)==="[object Object]"){let e={};return i.set(o,e),Reflect.ownKeys(o).forEach(t=>{e[t]=ya(o[t],i)}),e}return o}var $o=(t=>(t[t.END_REPORT=2001]="END_REPORT",t[t.LOG=2002]="LOG",t[t.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",t))($o||{});function $g(o,i,e,t){let r={data:o,random:Math.floor(Math.random()*2147483648),sdkAppId:e};return T(t)||(r=L(O({},r),{gzip:+t})),{uint32_sdkappid:0,uint64_from_uin:0,uint32_timestamp:0,uint32_seq:0,msg_common_info:{msg_device_info:{enum_device_type:0,str_device_brand:"",str_device_model:"",str_device_board:"",str_device_cpu_abi:""},msg_system_info:{enum_os_type:0,str_os_version:"",msg_network_info:0},msg_network_info:{enum_network_type:0}},msg_report_content:{uint32_type:i,bytes_report_data:JSON.stringify(r)}}}function Gi(o,i,e,t){try{let r=$g(o,i,e,t),s=Aa(r);return Cm(s,e)}catch(r){return JSON.stringify(o)}}function ka(o,i){let e=new Uint8Array(o.byteLength+i.byteLength);return e.set(new Uint8Array(o),0),e.set(new Uint8Array(i),o.byteLength),e.buffer}function Pa(o){return(o&65535)>>>0}function Hm(o){return(o&4294901760)>>>0}function $m(o){let i=Wg(o);return i==null?void 0:i.busiBuff}function Wg(o){try{let i={},e=0;i.totalLength=ct(o,e),e+=4,i.version=ct(o,e),e+=4,i.encryption=ll(o,e),e+=1,i.uinType=ll(o,e),e+=1,i.uinLength=ct(o,e),e+=4,i.uin=i.uinLength>4?Po(o,e,i.uinLength-4):"",e+=i.uinLength-4;let t=o.slice(e);if(i.encryption===2){let r=new Uint8Array(16).fill(0);o=Gg(t,r),i.decrypted=!0,e=0}else o=t,e=0;return i.rspHeadLength=ct(o,e),e+=4,i.seqNo=ct(o,e),e+=4,i.retCode=ct(o,e),e+=4,i.retStrLength=ct(o,e),e+=4,i.retStr=i.retStrLength?Po(o,e,i.retStrLength-4):"",e+=i.retStrLength-4,i.serviceCmdLength=ct(o,e),e+=4,i.serviceCmd=i.serviceCmdLength?Po(o,e,i.serviceCmdLength-4):"",e+=i.serviceCmdLength-4,i.cookieLength=ct(o,e),e+=4,i.cookie=i.cookieLength?Po(o,e,i.cookieLength-4):"",e+=i.cookieLength-4,i.flag=ct(o,e),e+=4,i.busiBuffLength=ct(o,e),e+=4,i.busiBuff=i.busiBuffLength?Po(o,e,i.busiBuffLength-4):"",e+=i.busiBuffLength-4,i}catch(i){}}function Wm(o,i){let e=o[0]<<24|o[1]<<16|o[2]<<8|o[3],t=o[4]<<24|o[5]<<16|o[6]<<8|o[7];e=e>>>0,t=t>>>0;let r=Ca*Ra>>>0;for(let s=0;s<Ra;s++)t-=(e<<ml)+i[2]^e+r^(e>>>5)+i[3],t=t>>>0,e-=(t<<ml)+i[0]^t+r^(t>>>5)+i[1],e=e>>>0,r-=Ca,r=r>>>0;return new Uint8Array([e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255])}function Gg(o,i){let e=0,t=new Uint8Array(8).fill(0),r=new Uint8Array(o.slice(0,8)),s=Wm(r,i),n=s[0]&7,a=o.length-1-n-wo-Lo,c=new Uint8Array(a),l=0,u=t,m=o.slice(0,8);e=8;let h=1;h+=n;for(let g=1;g<=wo;)if(h<8)h++,g++;else if(h===8){let E=Tl(o,e,u,m,s,i);u=E.ivPreCrypt,m=E.ivCurCrypt,s=E.debiBuf,e=E.bufPos,h=0}let _=a;for(;_>0;)if(h<8)c[l++]=s[h]^u[h],h++,_--;else if(h===8){let g=Tl(o,e,u,m,s,i);u=g.ivPreCrypt,m=g.ivCurCrypt,s=g.debiBuf,e=g.bufPos,h=0}for(let g=1;g<=Lo;)if(h<8)s[h]^u[h],h++,g++;else if(h===8){if(e>=o.length)break;let E=Tl(o,e,u,m,s,i);if(!E.success)break;u=E.ivPreCrypt,m=E.ivCurCrypt,s=E.debiBuf,e=E.bufPos,h=0}return c}function Tl(o,i,e,t,r,s){if(i+8>o.length)return{success:!1};let n=new Uint8Array(t),a=o.slice(i,i+8),c=new Uint8Array(8);for(let u=0;u<8;u++)c[u]=r[u]^a[u];let l=Wm(c,s);return{success:!0,ivPreCrypt:n,ivCurCrypt:a,debiBuf:l,bufPos:i+8}}var Gm=typeof TextDecoder!="undefined"?new TextDecoder:void 0;function qi({url:o,body:i,method:e="POST",timeout:t,priority:r}){return new Promise((s,n)=>{if("fetch"in window)return fetch(o,{method:e,body:i,priority:r}).then(c=>c.clone().json().then(l=>({data:l}),()=>c.arrayBuffer().then(l=>({data:$m(new Uint8Array(l))||(Gm?Gm.decode(l):l)})))).then(s,n);let a=new XMLHttpRequest;a.onreadystatechange=()=>{if(a.readyState===4)if(a.status>=200&&a.status<300)try{let c=JSON.parse(a.response);s({data:c})}catch(c){s({data:a.response})}else n({status:a.status,statusText:a.statusText||"request failed!"})},a.timeout=t||5e3,a.open(e,o,!0),a.send(i)})}function El(o){return p(this,null,function*(){let i=U(),e=JSON.stringify(o);try{if(!CompressionStream||e.length<=2800)return e;let r=new Blob([e],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),a=yield(yield(yield new Response(r)).blob()).arrayBuffer();return R.debug(`compressJSON ${e.length} -> ${a.byteLength} ${U()-i}ms`),a}catch(t){return e}})}var qg=Object.prototype.hasOwnProperty;var Ii=o=>typeof o=="function",gt=o=>typeof o=="undefined";var wa=o=>typeof o=="boolean";var Sl=o=>o.isRemote;var Il=function(o){if(!o||typeof o!="object"||Object.prototype.toString.call(o)!="[object Object]")return!1;let i=Object.getPrototypeOf(o);if(i===null)return!0;let e=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function qm(o){if(o==null)return!0;if(typeof o=="boolean")return!1;if(typeof o=="number")return o===0;if(typeof o=="string"||typeof o=="function"||Array.isArray(o))return o.length===0;if(o instanceof Error)return o.message==="";if(Il(o))switch(Object.prototype.toString.call(o)){case"[object File]":case"[object Map]":case"[object Set]":return o.size===0;case"[object Object]":{for(let i in o)if(qg.call(o,i))return!1;return!0}}return!1}var Jg=0,jg=1,Jm=2;function Xg({retryFunction:o,settings:i,onError:e,onRetrying:t,onRetryFailed:r,onRetrySuccess:s,context:n}){return function(...a){let{retries:c=5,timeout:l=1e3}=i,u=0,m=-1,h=Jg,_=(g,E)=>p(this,null,function*(){let A=n||this;try{let k=yield o.apply(A,a);u>0&&s&&s.call(this,u),u=0,g(k)}catch(k){let re=()=>{clearTimeout(m),u=0,h=Jm,E(k)},P=()=>{h!==Jm&&u<(Ii(c)?c():c)?(u++,h=jg,Ii(t)&&t.call(this,u,re),m=window.setTimeout(()=>{m=-1,_(g,E)},Ii(l)?l(u):l)):(re(),Ii(r)&&r.call(this,k))};Ii(e)?e.call(this,{error:k,retry:P,reject:E,retryFuncArgs:a,retriedCount:u}):P()}});return new Promise(_)}}var Ai=Xg;var Er=class o{constructor(i){d(this,"_parentPath");d(this,"userId");d(this,"remoteUserId");d(this,"id");d(this,"sdkAppId");d(this,"type");d(this,"isLocal");this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=wa(i.isLocal)?i.isLocal:!0,this.type=this.isLocal?"":i.type}getFullId(){return this._parentPath&&this.id?`${this._parentPath}-${this.id}`:this._parentPath?this._parentPath:this.id}createChild(i){let e=new o({id:i.id,userId:gt(i.userId)?this.userId:i.userId,sdkAppId:gt(i.sdkAppId)?this.sdkAppId:i.sdkAppId,type:gt(i.type)?this.type:i.type,isLocal:gt(i.isLocal)?this.isLocal:i.isLocal,remoteUserId:gt(i.remoteUserId)?this.remoteUserId:i.remoteUserId});return e.bindParent(this),e}bindParent(i){let e=i.getFullId();this._parentPath!==e&&(this.debug(`bind logger parent: ${i.id}`),this._parentPath=e,this.userId=i.userId||this.userId,this.sdkAppId=i.sdkAppId||this.sdkAppId)}setUserId(i){this.userId=i}setSdkAppId(i){this.sdkAppId=i}log(i,e){let t=this.isLocal?this.userId:this.remoteUserId,r=this.getFullId();e.unshift(`[${this.isLocal?"\u2191":"\u2193"}${this.type&&this.type!=="main"?"*":""}${r}${t?`|${t}`:""}]`),R.log(i,e,gt(this.userId)||qm(this.userId),this.userId,this.sdkAppId)}info(...i){this.log(2,i)}debug(...i){this.log(1,i)}warn(...i){this.log(3,i)}error(...i){this.log(4,i)}};var Ko={};Vi(Ko,{ANDROID_VERSION:()=>xa,CHROME_MAJOR_VERSION:()=>qe,CHROME_VERSION:()=>Ka,EDGE_VERSION:()=>Va,EDG_MAJOR_VERSION:()=>Cl,EDG_VERSION:()=>Fa,ELECTRON_MAJOR_VERSION:()=>Nl,FIREFOX_MAJOR_VERSION:()=>qo,FIREFOX_VERSION:()=>Ua,HUAWEI_VERSION:()=>za,IE_VERSION:()=>Kg,IOS_MAIN_VERSION:()=>et,IOS_VERSION:()=>Tt,IPADQQB_VERSION:()=>ja,IS_ANDROID:()=>_e,IS_ANDROID_WEBVIEW:()=>rT,IS_ANY_SAFARI:()=>Ft,IS_CHROME:()=>Zo,IS_CHROME_OS:()=>Rl,IS_CHROMIUM_BASE:()=>$e,IS_DESKTOP_IOS_CHROME:()=>kl,IS_EDG:()=>Jo,IS_EDGE:()=>zr,IS_ELECTRON:()=>tT,IS_FIREFOX:()=>K,IS_HEADLESS_CHROME:()=>vl,IS_HONOR:()=>bl,IS_HUAWEI:()=>rn,IS_HUAWEIBROWSER:()=>tn,IS_IE:()=>Qm,IS_IE8:()=>Zg,IS_IOS:()=>ge,IS_IOS_13_OR_14:()=>Ol,IS_IOS_15_1:()=>Ml,IS_IOS_CHROME:()=>js,IS_IPAD:()=>Go,IS_IPADQQB:()=>Zs,IS_IPAD_PRO:()=>Al,IS_IPHONE:()=>Sr,IS_IPOD:()=>zm,IS_LINUX:()=>Ks,IS_LOCAL:()=>oi,IS_MAC:()=>ri,IS_MACQQB:()=>Ys,IS_MIBROWSER:()=>en,IS_MQQB:()=>Xo,IS_NATIVE_ANDROID:()=>Yg,IS_OLD_ANDROID:()=>Qg,IS_OPENHARMONY:()=>Qo,IS_OPPOBROWSER:()=>zo,IS_SAFARI:()=>Re,IS_SAFARI_15_1:()=>oT,IS_SAMSUNGBROWSER:()=>on,IS_SOGOU:()=>zs,IS_SOGOUM:()=>Xs,IS_TBS:()=>ii,IS_UCBROWSER:()=>yl,IS_VIVOBROWSER:()=>sn,IS_WECHAT:()=>ji,IS_WIN:()=>Qr,IS_WQQB:()=>Qs,IS_WX:()=>eT,IS_X5MQQB:()=>jo,IS_XWEB:()=>Ji,MACQQB_VERSION:()=>Ja,MI_VERSION:()=>Xa,MQQB_VERSION:()=>Wo,OPENHARMONY_VERSION:()=>iT,OPPO_VERSION:()=>Ya,SAFARI_VERSION:()=>Xi,SAMSUNG_VERSION:()=>Qa,SOGOUM_VERSION:()=>Ba,SOGOU_VERSION:()=>Ha,TBS_VERSION:()=>$a,UA_DATA_STRING:()=>ti,USER_AGENT:()=>Vt,VIVO_VERSION:()=>Za,WECHAT_VERSION:()=>Ga,WQQB_VERSION:()=>qa,XWEB_VERSION:()=>Wa,browserInfo:()=>Ci,getBrowserCoreNumber:()=>wl,getBrowserInfo:()=>Ym,getChromeMajorVersion:()=>Yo,getDeviceModel:()=>si,getDeviceModelFromUA:()=>ec,getGPUInfo:()=>Pl,getOSName:()=>tc,getOSNumber:()=>Zr,getOSString:()=>ni,getOSType:()=>sT,getTerminalType:()=>Ll,getUserAgentData:()=>Yr,isLocalStorageEnabled:()=>zi,isMobile:()=>an,isVersionLargerThan:()=>Dl,isVersionSmallerThan:()=>nn});var Vt=typeof navigator=="undefined"?"":navigator.userAgent,Z=o=>new RegExp(o,"i").test(Vt),we=o=>{if(Z(o)){let i=new RegExp(`${o}\\/([\\d.]+)`),e=Vt.match(i);if(e&&e[1])return e[1]}return""},La=o=>{if(Z(o)){let i=new RegExp(`${o}\\/(\\d+)`),e=Vt.match(i);if(e&&e[1])return parseFloat(e[1])}return NaN},jm=/AppleWebKit\/([\d.]+)/i.exec(Vt),zg=jm?parseFloat(jm[1]):NaN,Go=Z("iPad"),Al=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Z("Macintosh"),Sr=Z("iPhone")&&!Go,zm=Z("iPod"),ge=Sr||Go||zm||Al,_e=Z("Android"),xa=function(){if(_e){let o=Vt.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(o){let i=o[1]&&parseFloat(o[1]),e=o[2]&&parseFloat(o[2]);if(i&&e)return parseFloat(`${o[1]}.${o[2]}`);if(i)return i}}return NaN}(),Qg=_e&&Z("webkit")&&xa<2.3,Yg=_e&&xa<5&&zg<537,K=Z("Firefox"),Ua=we("Firefox"),qo=La("Firefox"),zr=Z("Edge"),Va=we("Edge"),Jo=Z("Edg"),Fa=we("Edg"),Cl=La("Edg"),Xs=Z("SogouMobileBrowser"),Ba=we("SogouMobileBrowser"),zs=Z("MetaSr\\s"),Ha=we("MetaSr\\s"),ii=Z("TBS"),$a=we("TBS"),Ji=Z("XWEB"),Wa=we("XWEB"),Zg=Z("MSIE\\s8\\.0"),Qm=Z("MSIE\\/\\d+"),Kg=function(){if(Qm){let o=/MSIE\s(\d+)\.\d/.exec(Vt),i=o&&parseFloat(o[1]);return!i&&/Trident\/7.0/i.test(Vt)&&/rv:11.0/.test(Vt)&&(i=11),i}return NaN}(),ji=Z("(micromessenger|webbrowser)"),Ga=we("MicroMessenger"),jo=!ii&&Z("MQQBrowser")&&Z("COVC"),Xo=!ii&&Z("MQQBrowser")&&!Z("COVC"),Wo=Xo||jo?we("MQQBrowser"):"",Qs=!ii&&Z(" QQBrowser"),qa=we(" QQBrowser"),Ys=!ii&&Z("QQBrowserLite"),Ja=we("QQBrowserLite"),Zs=!ii&&Z("MQBHD"),ja=we("MQBHD"),Qr=Z("Windows"),ri=!ge&&Z("MAC OS X"),Ks=!_e&&Z("Linux"),Rl=Z("CrOS"),eT=Z("MicroMessenger"),yl=Z("UCBrowser"),tT=Z("Electron"),en=Z("MiuiBrowser"),Xa=we("MiuiBrowser"),tn=Z("HuaweiBrowser"),rn=Z("Huawei")||Z("HUAWEI"),bl=Z("Honor")||Z("HONOR"),za=we("HuaweiBrowser"),on=Z("SamsungBrowser"),Qa=we("SamsungBrowser"),zo=Z("HeyTapBrowser"),Ya=we("HeyTapBrowser"),sn=Z("VivoBrowser"),Za=we("VivoBrowser"),Qo=Z("OpenHarmony"),iT=we("OpenHarmony"),Yo=()=>La("Chrome"),js=Z("CriOS"),$e=Z("Chrome"),Zo=!zr&&!zs&&!Xs&&!ii&&!Ji&&!Jo&&!Qs&&!en&&!tn&&!on&&!zo&&!sn&&$e,vl=Z("HeadlessChrome"),qe=Yo(),Ka=we("Chrome"),Nl=La("Electron"),Re=!$e&&!Xo&&!jo&&!Ys&&!Zs&&Z("Safari"),Ft=Re||ge,Xi=we("Version"),rT=/Android.*(wv|.0.0.0)/.test(Vt),Tt=(()=>{if(Al)return Xi;if(ge){let o=Vt.match(/OS (\d+)_(\d+)/i);if(o&&o[1]){let i=o[1];return o[2]&&(i+=`.${o[2]}`),i}}return""})();function nn(o,i){let e=o.split(".").map(r=>Number(r)),t=i.split(".").map(r=>Number(r));for(let r=0;r<Math.max(e.length,t.length);r++){let s=e[r]||0,n=t[r]||0;if(s<n)return!0;if(s>n)return!1}return!1}function Dl(o,i,e=!1){let t=o.split(".").map(s=>Number(s)),r=i.split(".").map(s=>Number(s));for(let s=0;s<Math.max(t.length,r.length);s++){let n=t[s]||0,a=r[s]||0;if(n>a)return!0;if(n<a)return!1}return e}var et=Number(Tt.split(".")[0]),oT=Xi==="15.1",Ml=Tt==="15.1",Ol=(()=>{let o=Number(Tt.split(".")[0]);return o===14||o===13})(),kl=js&&Xi==="11.1.1",oi=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",zi=(()=>{let o;return()=>{if(typeof o=="undefined")try{o=!!window.localStorage}catch(i){o=!1}return o}})(),Ci=Ym();function Ym(){let o=new Map([[K,["Firefox",Ua]],[Jo,["Edg",Fa]],[Zo,["Chrome",Ka]],[js,["ChiOS",we("CriOS")]],[Re&&!js,["Safari",Xi]],[ii,["TBS",$a]],[Ji,["XWEB",Wa]],[ji&&Sr,["WeChat",Ga]],[Qs,["QQ(Win)",qa]],[Xo,["QQ(Mobile)",Wo]],[jo,["QQ(Mobile X5)",Wo]],[Ys,["QQ(Mac)",Ja]],[Zs,["QQ(iPad)",ja]],[en,["MI",Xa]],[tn,["HW",za]],[on,["Samsung",Qa]],[zo,["OPPO",Ya]],[sn,["VIVO",Za]],[zr,["EDGE",Va]],[Xs,["SogouMobile",Ba]],[zs,["Sogou",Ha]]]),i="unknown",e="unknown";return o.has(!0)&&([i,e]=o.get(!0)),{name:i,version:e}}var me=null;function an(){return me&&typeof me.mobile=="boolean"?me.mobile:_e||ge||Sr||Go||Qo}var ti="";function Yr(){return p(this,null,function*(){if(me)return me;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return me=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),me&&!ti&&(ti=`UAData: ${me.platform}/${me.platformVersion}`,me.architecture&&me.bitness&&(ti+=` ${me.architecture}/${me.bitness}`),me.mobile&&(ti+=" mobile"),me.model&&(ti+=` model: ${me.model.replace(/\s+/g,"/")}`),me.fullVersionList&&(ti+=` ${me.fullVersionList.filter(o=>o.brand!=="Not/A)Brand").map(o=>`${o.brand}/${o.version}`).join(",")}`)),me}catch(o){return null}})}function Pl(){try{let o=document.createElement("canvas"),i=o.getContext("webgl")||o.getContext("experimental-webgl");if(!i)return"";let e=i.getExtension("WEBGL_debug_renderer_info");if(e){let t=i.getParameter(e.UNMASKED_VENDOR_WEBGL),r=i.getParameter(e.UNMASKED_RENDERER_WEBGL);return`${t} ${r}`}return""}catch(o){return""}}function si(){return(me==null?void 0:me.model)||ec()||""}function ec(){let o=/;\s*([^;)]+)\s+Build\//,i=Vt.match(o);return i!=null&&i[1]?i[1].trim():null}var Xm=new Map([[_e,"Android"],[ge,"iOS"],[Qr,"Windows"],[ri,"MacOS"],[Ks,"Linux"],[Rl,"ChromeOS"]]),tc=function(){return Xm.get(!0)?Xm.get(!0):me?me.platform:"unknown"};function Zr(){return Qr?1:_e?2:ri?3:ge?4:Ks?5:Rl?6:Qo?7:0}function wl(){return ji||Ji?4:$e?1:Re?2:K?3:0}var ni=()=>{let o=tc();return me!=null&&me.platformVersion?o+=`/${me.platformVersion}`:ge?o+=`/${Tt}`:_e&&(o+=`/${xa}`),o+=`/${Ci.name}/${Re&&!js?Ci.version:Ci.version.split(".")[0]}`,me!=null&&me.architecture&&(o+=`/${me.architecture}`),o};function Ll(){return _e?4:Sr?2:Go?3:ri?12:Qr?5:Ks?13:Qo?22:1}function sT(){return _e?"Android":Sr?"iPhone":Go?"iPad":ri?"Mac":Qr?"Windows":Ks?"Linux":"unknown"}var Zm=Ge(at(),1),nT=new Zm.default,S=nT;var mt=(W=>(W.ROOM_DESTROY="1",W.JOIN_START="21",W.JOIN_SCHEDULE_SUCCESS="22",W.JOIN_SIGNAL_CONNECTION_START="23",W.JOIN_SIGNAL_CONNECTION_END="24",W.JOIN_SEND_CMD="25",W.JOIN_RECEIVED_CMD_RES="26",W.JOIN_SUCCESS="27",W.JOIN_FAILED="28",W.LEAVE_START="51",W.LEAVE_SEND_CMD="52",W.LEAVE_SUCCESS="53",W.PUBLISH_START="61",W.SEND_FIRST_VIDEO_FRAME="62",W.PUBLISH_FAILED="63",W.SUBSCRIBE_START="81",W.SUBSCRIBE_SUCCESS="82",W.SUBSCRIBE_FAILED="84",W.UNSUBSCRIBE_SUCCESS="83",W.LOCAL_TRACK_CAPTURE_START="101",W.LOCAL_TRACK_CAPTURE_SUCCESS="102",W.LOCAL_TRACK_CAPTURE_FAILED="103",W.LOCAL_TRACK_PUBLISHED="104",W.LOCAL_TRACK_UNPUBLISHED="105",W.LOCAL_TRACK_REPLACED="106",W.SWITCH_DEVICE_SUCCESS="107",W.TRACK_MUTED="108",W.TRACK_UNMUTED="109",W.REMOTE_TRACK_SUBSCRIBED="110",W.REMOTE_TRACK_UNSUBSCRIBED="111",W.LOCAL_TRACK_RECAPTURE="112",W.LOCAL_AUDIO_STARTED="113",W.LOCAL_AUDIO_STOPPED="114",W.REMOTE_AUDIO_STARTED="115",W.REMOTE_AUDIO_STOPPED="116",W.PLAY_TRACK_START="151",W.PLAYER_STATE_CHANGED="152",W.VIDEO_LOADED_DATA="153",W.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",W.AUDIO_CONTEXT_LONG_SUSPENDED="155",W.REMOTE_VIDEO_PLAY_START="156",W.REMOTE_VIDEO_PLAY_FINISH="157",W.SIGNAL_CONNECTION_STATE_CHANGED="201",W.PEER_CONNECTION_STATE_CHANGED="202",W.SINGLE_CONNECTION_STAT="203",W.SPC_RECONNECTED="204",W.HEARTBEAT_REPORT="251",W.RECEIVED_PUBLISHED_USER_LIST="252",W.REMOTE_PUBLISH_STATE_CHANGED="253",W.AUDIO_LEVEL_INTERVAL="260",W.NETWORK_QUALITY="261",W.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",W.QUALITY_LIMITATION_CHANGED="263",W.LOG="264",W.AUDIO_PROCESSOR_DEBUG="265",W.SSO_SWITCH="266",W.SEI_MESSAGE="267",W.SWITCH_ROOM_START="401",W.SWITCH_ROOM_SUCCESS="407",W.SWITCH_ROOM_FAILED="408",W))(mt||{});var C=mt;var xl=class{constructor(){d(this,"enable",!1);d(this,"ssoFailCount",0);S.on("22",({schedule:i})=>{var e;(e=i==null?void 0:i.config)!=null&&e.sso&&S.emit("266",{enable:!0})}),S.on("266",({enable:i})=>{this.enable=i})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&S.emit("266",{enable:!1})}},Ir=new xl;var aT="%cTRTC%c%s",cT="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",dT="display: inline",ic=class ic{constructor(){d(this,"_isEnableUploadLog",!0);d(this,"_localJoinedUser",new Map);d(this,"_queue",[]);d(this,"_timeoutId",-1);d(this,"_logLevel",1);d(this,"_logLevelToUpload",2);!Do&&!xs&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){S.on(C.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var e;(e=i==null?void 0:i.config)!=null&&e.logLevelToUpload&&Xt[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),S.on(C.JOIN_START,({params:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),S.on(C.LEAVE_SUCCESS,({room:i})=>{this.deleteJoinedUser(i.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(i){this._localJoinedUser.set(i.userId,i),this.startUpload()}deleteJoinedUser(i){this._localJoinedUser.delete(i)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),5e3)}getLogsToUpload(){let i={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return i;let e=0;for(;e<this._queue.length&&e!==50;e++){let t=this._queue[e];if(t.forAllJoinedClients)this._localJoinedUser.forEach(({userId:r,sdkAppId:s})=>{i.map.has(r)?i.map.get(r).logs.push(t):i.map.set(r,{userId:r,sdkAppId:s,logs:[t]})});else if(ie(t.userId)&&z(t.sdkAppId)){let{userId:r,sdkAppId:s}=t;i.map.has(r)?i.map.get(r).logs.push(t):i.map.set(r,{userId:r,sdkAppId:s,logs:[t]})}}return i.map.size>0&&(i.splicedQueue=this._queue.splice(0,e)),i}upload(){return p(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:i,splicedQueue:e}=this.getLogsToUpload();if(i.size===0)return;try{let r=[...i.values()];for(let s=0;s<r.length;s++){let{userId:n,sdkAppId:a,logs:c}=r[s],l={timestamp:la(),sdkAppId:String(a),userId:n,version:He,log:c.map(h=>h.log).join(`
|
|
6
6
|
`)},u=JSON.stringify(l),m=Ir.enable?Gi(l,2002,a):u;yield this.uploadLogWithRetry(m,a,m instanceof Uint8Array,u),c.forEach(h=>h.uploaded=!0)}}catch(r){}let t=e.filter(r=>!r.uploaded);t.length>0&&(this._queue=t.concat(this._queue))})}uploadLogWithRetry(i,e,t,r){return Ai({retryFunction:()=>qi({url:Wi(e,mr.LOG),body:i,timeout:5e3,priority:"low"}).then(s=>{t&&s.data!=="ok"&&(Ir.handleUploadFailed(),this.uploadLogWithRetry(r,e,!1,r))}),settings:{retries:3,timeout:2e3},onError:({retry:s})=>{s()}})()}getPrefix(i){let e=new Date;return e.setTime(Fi()),`[${No(e)}] <${Xt[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){T(Xt[i])||(this._logLevel!==i&&this.info("setLogLevel",i),this._logLevel=i)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(i){if(ie(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch(e){return""}}addLogToQueue(i,e,t=!0,r,s){let n={log:e.reduce((a,c)=>`${a} ${this.logChunkToString(c)}`.trim(),""),level:i,userId:r,sdkAppId:s,forAllJoinedClients:t};S.emit(C.LOG,{log:n}),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push(n)}log(i,e,t=!0,r,s){var a;if(e.unshift(this.getPrefix(i)),this.addLogToQueue(i,e,t,r,s),i<this._logLevel)return;let n=((a=Xt[i])==null?void 0:a.toLowerCase())||"info";ic.PRINT_LOG_TAG?console[n](aT,cT,dT,...e):console[n](...e)}debug(...i){this.log(1,i)}info(...i){this.log(2,i)}warn(...i){this.log(3,i)}error(...i){this.log(4,i)}createLogger(i){if(i.parent instanceof Er){let e=i,{parent:t}=e,r=aa(e,["parent"]),s=new Er(r);return s.bindParent(t),s}return new Er(i)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;Xt[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}};d(ic,"PRINT_LOG_TAG",!(ge||_e||vl));var Ul=ic,R=new Ul;var lT=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,o=>{let i=Math.random()*16|0;return(o=="x"?i:i&3|8).toString(16)})},cn=lT;var Vl=class{constructor(){d(this,"_prefix","TRTC");d(this,"_queue",new Map)}getRealKey(i){return`${this._prefix}_${i}`}checkStorage(){if(!zi())return;setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(t=>{if(t.startsWith(this._prefix))try{let r=localStorage.getItem(t);if(!r)return!1;let s=JSON.parse(r);if(s&&s.expiresIn<Date.now())return!0}catch(r){return!1}return!1}).forEach(t=>localStorage.removeItem(t))}doFlush(){if(zi())try{for(let[i,e]of this._queue)localStorage.setItem(i,JSON.stringify(e))}catch(i){R.warn(i)}}getItem(i){if(!zi())return null;try{let e=localStorage.getItem(this.getRealKey(i));if(!e)return null;let t=JSON.parse(e);return t&&t.expiresIn>=Date.now()?t.value:null}catch(e){R.warn(e)}}setItem(i,e){if(zi())try{let t={expiresIn:Date.now()+pa,value:e};this._queue.set(this.getRealKey(i),t)}catch(t){R.warn(t)}}deleteItem(i){if(!zi())return!1;try{return i=this.getRealKey(i),this._queue.delete(i),localStorage.removeItem(i),!0}catch(e){return R.warn(e),!1}}clear(){if(zi())try{localStorage.clear()}catch(i){R.warn(i)}}},es=new Vl;var bi={};Vi(bi,{HTTPS_API:()=>PT,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>du,IS_GET_CAPABILITIES_SUPPORTED:()=>cu,IS_GET_SETTINGS_SUPPORTED:()=>yi,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>au,IS_INSERTABLE_STREAM_SUPPORTED:()=>hi,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>Sc,IS_RTC_RTP_SENDER_SUPPORTED:()=>gn,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>ss,IS_SEI_SUPPORTED:()=>En,IS_SPC_SUPPORTED:()=>os,basis:()=>xT,capabilityCheck:()=>hu,checkSystemRequirementsInternal:()=>_c,decodeSupportStatus:()=>fc,detectVideoCodecCapabilities:()=>mu,detectVideoDecoderCapabilities:()=>Mp,detectVideoEncoderCapabilities:()=>Dp,encodeSupportStatus:()=>su,getBrowserInfo:()=>bT,getDisplayResolution:()=>Ip,getH264ProfileLevelIds:()=>Op,isAddTransceiverSupported:()=>St,isBrowserSupported:()=>ou,isCanvasCaptureStreamAPISupported:()=>Rp,isCanvasSmallStreamSupported:()=>gc,isGetReceiversSupported:()=>oo,isGetSendersSupported:()=>Rr,isGetTransceiversSupported:()=>yr,isGetUserMediaSupported:()=>Ap,isMediaDevicesSupported:()=>pc,isMediaSessionSupported:()=>bp,isMediaStreamTrackGeneratorSupported:()=>vT,isMediaStreamTrackProcessorSupported:()=>fn,isReplaceTrackSupported:()=>nu,isRequestVideoFrameCallbackSupported:()=>Ki,isSIMDSupported:()=>uu,isScaleResolutionDownBySupported:()=>yp,isScreenCaptureApiAvailable:()=>_n,isSelectedCandidatePair:()=>Cr,isSetParametersSupported:()=>Tn,isSetSinkIdSupported:()=>MT,isSmallStreamSupported:()=>Tc,isStopTransceiverSupported:()=>LT,isTRTCSupported:()=>DT,isUnifiedPlanDefault:()=>wT,isUsedInHttpProtocol:()=>Zi,isWebAudioSupported:()=>Cp,isWebCodecSupported:()=>Ec,isWebCodecsSupported:()=>pn,isWebRTCSupported:()=>lu,isWebTransportSupported:()=>vp});var Yl={};Vi(Yl,{AUDIO_LEVEL_SCALE:()=>Dt,AlphaStitchingType:()=>hn,AudioCodecPipelineType:()=>ln,AudioDecoderDowngradeState:()=>$l,AudioPlayerMode:()=>Jl,AudioType:()=>ip,BASIC_TYPE:()=>Qi,BannedReason:()=>jl,CONNECTION_CLOSED_REASON:()=>Bl,CheckPermissionType:()=>Ql,ClientEvent:()=>Km,CodecType:()=>ap,ConnectionEvent:()=>ai,ConnectionState:()=>Nt,DECODE_FAILED_ERROR_CODE:()=>zl,DenoiserMode:()=>Xl,DeviceType:()=>cc,FacingMode:()=>sc,FrameWorkType:()=>rc,LeaveReason:()=>np,LocalTrackEvent:()=>Kr,MULTI_VIDEO_DATA_TYPE:()=>li,MediaType:()=>Ve,MediaTypeLabel:()=>uT,MonitorEventId:()=>dn,MutedFlag:()=>tp,NetworkQualityValue:()=>ql,PlayerState:()=>Ar,ReceiveMode:()=>sp,RemoteStreamType:()=>Et,RemoteTrackEvent:()=>eo,RoomEvent:()=>ci,SMALL_MODE:()=>un,SceneNumber:()=>Hl,StreamEvent:()=>ep,StreamType:()=>op,SubscribeMediaType:()=>Fl,TIMER_TYPE:()=>ui,TRACK_ACTION:()=>Gl,TRACK_KIND:()=>Wl,TrackEvent:()=>di,UserRole:()=>lt,UserRoleNumber:()=>to,VideoCodec:()=>Bt,VideoCodecPipelineType:()=>ac,VideoContentHint:()=>ts,VideoDecoderDowngradeState:()=>oc,VideoPlayerMode:()=>nc,VideoType:()=>rp});var rc=(e=>(e[e.WEBRTC=30]="WEBRTC",e[e.WASM=37]="WASM",e))(rc||{}),ai=(E=>(E.TRACK_ADDED="track-added",E.TRACK_UPDATED="track-updated",E.TRACK_SUBSCRIBED="track-subscribed",E.STREAM_ADDED="stream-added",E.STREAM_REMOVED="stream-removed",E.STREAM_UPDATED="stream-updated",E.STREAM_PUBLISHED="stream-published",E.STREAM_SUBSCRIBED="stream-subscribed",E.STREAM_UNSUBSCRIBED="stream-unsubscribed",E.STATE_CHANGED="state-changed",E.ERROR="error",E.CONNECTION_STATE_CHANGED="connection-state-changed",E.FIREWALL_RESTRICTION="firewall-restriction",E.SEI_MESSAGE="sei-message",E.CLOSED="closed",E))(ai||{}),Bl=(n=>(n.REMOTE_LEAVE="remote user exitRoom",n.REMOTE_UNPUBLISH="remote user unpublished",n.LOCAL_LEAVE="you exitRoom",n.LOCAL_UNPUBLISH="you unpublished",n.LOCAL_UNSUBSCRIBE="you unsubscribed",n.SWITCH_ROLE="you switch role to audience",n))(Bl||{}),Km=(A=>(A.STREAM_ADDED="stream-added",A.STREAM_REMOVED="stream-removed",A.STREAM_UPDATED="stream-updated",A.STREAM_SUBSCRIBED="stream-subscribed",A.CONNECTION_STATE_CHANGED="connection-state-changed",A.PEER_JOIN="peer-join",A.PEER_LEAVE="peer-leave",A.MUTE_AUDIO="mute-audio",A.MUTE_VIDEO="mute-video",A.UNMUTE_AUDIO="unmute-audio",A.UNMUTE_VIDEO="unmute-video",A.CLIENT_BANNED="client-banned",A.NETWORK_QUALITY="network-quality",A.AUDIO_VOLUME="audio-volume",A.SEI_MESSAGE="sei-message",A.ERROR="error",A))(Km||{}),ep=(s=>(s.PLAYER_STATE_CHANGED="player-state-changed",s.SCREEN_SHARING_STOPPED="screen-sharing-stopped",s.CONNECTION_STATE_CHANGED="connection-state-changed",s.DEVICE_AUTO_RECOVERED="device-auto-recovered",s.ERROR="error",s))(ep||{}),Kr=(c=>(c.DEVICE_AUTO_RECOVERED="1",c.DEVICE_RECOVER_FAILED="5",c.DEVICE_CHANGED="2",c.ERROR="3",c.PUBLISH_STATE_CHANGED="4",c.ENCODE_FAILED="6",c.TRACK_ENDED="7",c.RENDER="render",c))(Kr||{}),Ar=(t=>(t.PAUSED="PAUSED",t.PLAYING="PLAYING",t.STOPPED="STOPPED",t))(Ar||{}),ci=(b=>(b.PEER_JOIN="peer-join",b.PEER_LEAVE="peer-leave",b.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",b.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",b.BANNED="banned",b.NETWORK_QUALITY="network-quality",b.AUDIO_VOLUME="audio-volume",b.SEI_MESSAGE="sei-message",b.ERROR="error",b.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",b.REMOTE_PUBLISHED="remote-published",b.REMOTE_UNPUBLISHED="remote-unpublished",b.FIREWALL_RESTRICTION="firewall-restriction",b.HEARTBEAT_REPORT="heartbeat-report",b.CUSTOM_MESSAGE="custom-message",b.LAYER_DATA="layerData",b.FIRST_VIDEO_FRAME="first-video-frame",b.DUMP="dump",b.AUDIO_FRAME="audio-frame",b.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",b.LOCAL_PUBLISH_FLAG_CHANGED="local-publish-flag-changed",b.NTP_TIME_UPDATED="ntp-time-updated",b))(ci||{}),di=(c=>(c.PLAYER_STATE_CHANGED="player-state-changed",c.MUTE="mute",c.UNMUTE="unmute",c.ERROR="error",c.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",c.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",c.FIRST_VIDEO_FRAME="first-video-frame",c.VIDEO_SIZE_CHANGED="video-size-changed",c))(di||{}),eo=(r=>(r.DECODE_FAILED="decode-failed",r.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",r.REMOTE_PUBLISH_CHANGED="remote-publish-changed",r.AUDIO_FRAME_WITH_NTP="audio-frame-with-ntp",r))(eo||{}),tp=(a=>(a[a.VIDEO=1]="VIDEO",a[a.SMALL=2]="SMALL",a[a.AUX=4]="AUX",a[a.AUDIO=8]="AUDIO",a[a.VIDEO_MUTE=16]="VIDEO_MUTE",a[a.AUX_MUTE=32]="AUX_MUTE",a[a.AUDIO_MUTE=64]="AUDIO_MUTE",a))(tp||{}),Hl=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(Hl||{}),to=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(to||{}),lt=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(lt||{}),Nt=(s=>(s.CONNECTED="CONNECTED",s.DISCONNECTED="DISCONNECTED",s.CONNECTING="CONNECTING",s.RECONNECTED="RECONNECTED",s.RECONNECTING="RECONNECTING",s))(Nt||{}),$l=(r=>(r.INITIALIZED="INITIALIZED",r.STARTING="STARTING",r.STARTED="STARTED",r.FAILED="FAILED",r))($l||{}),oc=(r=>(r.INITIALIZED="INITIALIZED",r.STARTING="STARTING",r.STARTED="STARTED",r.FAILED="FAILED",r))(oc||{}),Wl=(t=>(t.AUDIO="audio",t.VIDEO="video",t.AUXILIARY="auxVideo",t))(Wl||{}),Gl=(e=>(e.ADD="add",e.REMOVE="remove",e))(Gl||{}),Ve=(s=>(s[s.NULL=0]="NULL",s[s.AUDIO=1]="AUDIO",s[s.AUX_VIDEO=2]="AUX_VIDEO",s[s.BIG_VIDEO=4]="BIG_VIDEO",s[s.SMALL_VIDEO=8]="SMALL_VIDEO",s))(Ve||{}),uT={1:"audio",2:"auxVideo",4:"video"},ip=(i=>(i[i.opus=111]="opus",i))(ip||{}),rp=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(rp||{}),op=(e=>(e.Big="big",e.Small="small",e))(op||{}),Et=(e=>(e.Main="main",e.Aux="auxiliary",e))(Et||{}),li=(s=>(s[s.MULTI_DATA_AUDIO=1]="MULTI_DATA_AUDIO",s[s.MULTI_DATA_BIG_IMG=2]="MULTI_DATA_BIG_IMG",s[s.MULTI_DATA_SMALL_IMG=3]="MULTI_DATA_SMALL_IMG",s[s.MULTI_DATA_AUX_IMG=7]="MULTI_DATA_AUX_IMG",s[s.MULTI_DATA_TYPE_BUTT=12]="MULTI_DATA_TYPE_BUTT",s))(li||{}),dn=(w=>(w[w.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",w[w.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",w[w.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",w[w.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",w[w.MUTE_AUDIO=32772]="MUTE_AUDIO",w[w.MUTE_VIDEO=32773]="MUTE_VIDEO",w[w.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",w[w.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",w[w.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",w[w.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",w[w.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",w[w.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",w[w.SWITCH_CAMERA=32780]="SWITCH_CAMERA",w[w.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",w[w.REPLACE_VIDEO=32782]="REPLACE_VIDEO",w[w.REPLACE_AUDIO=32783]="REPLACE_AUDIO",w[w.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",w[w.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",w[w.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",w[w.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",w[w.JOIN=32788]="JOIN",w[w.LEAVE=32789]="LEAVE",w[w.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",w[w.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",w[w.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",w[w.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",w[w.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",w[w.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",w[w.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",w[w.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",w[w.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",w[w.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",w[w.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",w[w.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",w[w.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",w[w.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",w[w.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",w[w.PUBLISH_AUX=32805]="PUBLISH_AUX",w[w.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",w[w.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",w[w.VIDEO_ENCODER=4004]="VIDEO_ENCODER",w[w.VIDEO_DECODER=4005]="VIDEO_DECODER",w))(dn||{}),ql=(a=>(a[a.UNKNOWN=0]="UNKNOWN",a[a.EXCELLENT=1]="EXCELLENT",a[a.GOOD=2]="GOOD",a[a.POOR=3]="POOR",a[a.BAD=4]="BAD",a[a.VERY_BAD=5]="VERY_BAD",a[a.DISCONNECTED=6]="DISCONNECTED",a))(ql||{}),sp=(r=>(r[r.MANUAL=0]="MANUAL",r[r.AUTO_AUDIO=1]="AUTO_AUDIO",r[r.AUTO_VIDEO=2]="AUTO_VIDEO",r[r.AUTO_ALL=3]="AUTO_ALL",r))(sp||{}),sc=(e=>(e.user="user",e.environment="environment",e))(sc||{}),nc=(t=>(t[t.ELEMENT=0]="ELEMENT",t[t.CANVAS_FROM_ELEMENT=1]="CANVAS_FROM_ELEMENT",t[t.CANVAS_WITHOUT_ELEMENT=2]="CANVAS_WITHOUT_ELEMENT",t))(nc||{}),Jl=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(Jl||{}),jl=(r=>(r.BANNED="banned",r.KICK="kick",r.USER_TIME_OUT="user_time_out",r.ROOM_DISBAND="room_disband",r))(jl||{}),np=(l=>(l[l.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",l[l.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",l[l.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",l[l.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",l[l.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",l[l.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",l[l.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",l[l.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",l[l.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",l))(np||{}),Dt=1e8,Xl=(e=>(e[e.NORMAL=0]="NORMAL",e[e.FAR_FIELD_REDUCTION=1]="FAR_FIELD_REDUCTION",e))(Xl||{}),Fl=class{constructor(){d(this,"mediaType",0)}set audio(i){i?this.mediaType|=1:this.mediaType&=-2}get audio(){return!!(this.mediaType&1)}set video(i){i?this.mediaType|=4:this.mediaType&=-5}get video(){return!!(this.mediaType&4)}set auxiliary(i){i?this.mediaType|=2:this.mediaType&=-3}get auxiliary(){return!!(this.mediaType&2)}set smallVideo(i){i?this.mediaType|=8:this.mediaType&=-9}get smallVideo(){return!!(this.mediaType&8)}},Qi=(s=>(s.String="string",s.Number="number",s.Boolean="boolean",s.Array="array",s.Object="object",s))(Qi||{}),Bt=(s=>(s.H264="h264",s.H265="h265",s.VP8="vp8",s.VP9="vp9",s.AV1="av1",s))(Bt||{}),ac=(r=>(r[r.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",r[r.DUMP=1]="DUMP",r[r.SEI=2]="SEI",r[r.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",r))(ac||{}),ln=(r=>(r[r.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",r[r.NTP_TO_AUDIO_FRAME=1]="NTP_TO_AUDIO_FRAME",r[r.DUMP=2]="DUMP",r[r.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",r))(ln||{}),ap=(t=>(t.WebRTC="webrtc",t.WebCodecs="webcodecs",t.WebAssembly="webassembly",t))(ap||{}),zl=(h=>(h[h.SUCCESS=0]="SUCCESS",h[h.FAILED=1]="FAILED",h[h.WEBCODEC_INIT=2]="WEBCODEC_INIT",h[h.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",h[h.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",h[h.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",h[h.WASM_INIT=6]="WASM_INIT",h[h.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",h[h.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",h[h.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",h[h.TEST=10]="TEST",h[h.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",h))(zl||{}),ts=(r=>(r.NONE="",r.DETAIL="detail",r.MOTION="motion",r.TEXT="text",r))(ts||{}),ui=(s=>(s.INTERVAL="interval",s.TIMEOUT="timeout",s.RAF="raf",s.RIC="ric",s.INTERVAL_IN_WORKER="intervalInWorker",s))(ui||{}),un=(e=>(e.CANVAS="canvas",e.API="api",e))(un||{}),Ql=(r=>(r[r.NONE=0]="NONE",r[r.MICROPHONE=1]="MICROPHONE",r[r.CAMERA=2]="CAMERA",r[r.BOTH=3]="BOTH",r))(Ql||{}),cc=(e=>(e.CAMERA="camera",e.MICROPHONE="microphone",e))(cc||{}),hn=(t=>(t[t.none=0]="none",t[t.horizontal=1]="horizontal",t[t.vertical=2]="vertical",t))(hn||{});var F={AVOID_REPEATED_CALL:"AVOID_REPEATED_CALL",INVALID_PARAMETER_REQUIRED:"INVALID_PARAMETER_REQUIRED",INVALID_PARAMETER_TYPE:"INVALID_PARAMETER_TYPE",INVALID_PARAMETER_EMPTY:"INVALID_PARAMETER_EMPTY",INVALID_PARAMETER_INSTANCE:"INVALID_PARAMETER_INSTANCE",INVALID_PARAMETER_RANGE:"INVALID_PARAMETER_RANGE",INVALID_PARAMETER_MIN:"INVALID_PARAMETER_MIN",INVALID_PARAMETER_MAX:"INVALID_PARAMETER_MAX",INVALID_PARAMETER_STREAMTYPE:"INVALID_PARAMETER_STREAMTYPE",API_CALL_TIMEOUT:"API_CALL_TIMEOUT",SIGNAL_CHANNEL_RECONNECTION_FAILED:"SIGNAL_CHANNEL_RECONNECTION_FAILED",SIGNAL_CHANNEL_SETUP_FAILED:"SIGNAL_CHANNEL_SETUP_FAILED",ERROR_MESSAGE:"ERROR_MESSAGE",EXCHANGE_SDP_TIMEOUT:"EXCHANGE_SDP_TIMEOUT",DOWNLINK_RECONNECTION_FAILED:"DOWNLINK_RECONNECTION_FAILED",EXCHANGE_SDP_FAILED:"EXCHANGE_SDP_FAILED",UPDATE_OFFER_TIMEOUT:"UPDATE_OFFER_TIMEOUT",UPLINK_RECONNECTION_FAILED:"UPLINK_RECONNECTION_FAILED",INVALID_RECORDID:"INVALID_RECORDID",INVALID_PURE_AUDIO:"INVALID_PURE_AUDIO",INVALID_STREAMID:"INVALID_STREAMID",INVALID_USER_DEFINE_RECORDID:"INVALID_USER_DEFINE_RECORDID",INVALID_USER_DEFINE_PUSH_ARGS:"INVALID_USER_DEFINE_PUSH_ARGS",INVALID_PROXY:"INVALID_PROXY",INVALID_JOIN:"INVALID_JOIN",INVALID_ROOMID_STRING:"INVALID_ROOMID_STRING",INVALID_ROOMID_INTEGER:"INVALID_ROOMID_INTEGER",INVALID_SIGNAL_CHANNEL:"INVALID_SIGNAL_CHANNEL",JOIN_ROOM_TIMEOUT:"JOIN_ROOM_TIMEOUT",JOIN_ROOM_FAILED:"JOIN_ROOM_FAILED",REJOIN_ROOM_FAILED:"REJOIN_ROOM_FAILED",INVALID_DESTROY:"INVALID_DESTROY",INVALID_PUBLISH:"INVALID_PUBLISH",INVALID_UNPUBLISH:"INVALID_UNPUBLISH",INVALID_AUDIENCE:"INVALID_AUDIENCE",INVALID_INITIALIZE:"INVALID_INITIALIZE",INVALID_DUPLICATE_PUBLISHING:"INVALID_DUPLICATE_PUBLISHING",INVALID_SUBSCRIBE_UNDEFINED:"INVALID_SUBSCRIBE_UNDEFINED",INVALID_SUBSCRIBE_LOCAL:"INVALID_SUBSCRIBE_LOCAL",INVALID_REMOTE_STREAM:"INVALID_REMOTE_STREAM",SUBSCRIBE_FAILED:"SUBSCRIBE_FAILED",INVALID_ROLE:"INVALID_ROLE",INVALID_PARAMETER_SWITCH_ROLE:"INVALID_PARAMETER_SWITCH_ROLE",INVALID_OPERATION_SWITCH_ROLE:"INVALID_OPERATION_SWITCH_ROLE",SWITCH_ROLE_TIMEOUT:"SWITCH_ROLE_TIMEOUT",SWITCH_ROLE_FAILED:"SWITCH_ROLE_FAILED",CLIENT_BANNED:"CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"INVALID_OPERATION_START_PUBLISH_CDN",INVALID_OPERATION_STOP_PUBLISH_CDN:"INVALID_OPERATION_STOP_PUBLISH_CDN",INVALID_STREAM_ID:"INVALID_STREAM_ID",START_PUBLISH_CDN_FAILED:"START_PUBLISH_CDN_FAILED",STOP_PUBLISH_CDN_FAILED:"STOP_PUBLISH_CDN_FAILED",START_MIX_TRANSCODE:"START_MIX_TRANSCODE",STOP_MIX_TRANSCODE:"STOP_MIX_TRANSCODE",INVALID_AUDIO_VOLUME:"INVALID_AUDIO_VOLUME",ENABLE_SMALL_STREAM_PUBLISHED:"ENABLE_SMALL_STREAM_PUBLISHED",DISABLE_SMALL_STREAM_PUBLISHED:"DISABLE_SMALL_STREAM_PUBLISHED",NOT_SUPPORTED_SMALL_STREAM:"NOT_SUPPORTED_SMALL_STREAM",INVALID_SMALL_STREAM_PROFILE:"INVALID_SMALL_STREAM_PROFILE",INVALID_PARAMETER_REMOTE_STREAM:"INVALID_PARAMETER_REMOTE_STREAM",INVALID_OPERATION_CHANGE_SMALL:"INVALID_OPERATION_CHANGE_SMALL",REMOTE_NOT_PUBLISH_SMALL_STREAM:"REMOTE_NOT_PUBLISH_SMALL_STREAM",INVALID_SWITCH_DEVICE:"INVALID_SWITCH_DEVICE",INVALID_SWITCH_DEVICE_PUBLISHING:"INVALID_SWITCH_DEVICE_PUBLISHING",INVALID_REPLACE_TRACK:"INVALID_REPLACE_TRACK",INVALID_INITIALIZE_LOCAL_STREAM:"INVALID_INITIALIZE_LOCAL_STREAM",INVALID_ADD_TRACK_REPETITIVE:"INVALID_ADD_TRACK_REPETITIVE",INVALID_ADD_TRACK_REMOVING:"INVALID_ADD_TRACK_REMOVING",INVALID_ADD_TRACK_PUBLISHING:"INVALID_ADD_TRACK_PUBLISHING",INVALID_STREAM_INITIALIZED:"INVALID_STREAM_INITIALIZED",INVALID_ADD_TRACK_NUMBER:"INVALID_ADD_TRACK_NUMBER",INVALID_REMOVE_AUDIO_TRACK:"INVALID_REMOVE_AUDIO_TRACK",INVALID_REMOVE_AUDIO_ADDING:"INVALID_REMOVE_AUDIO_ADDING",INVALID_REMOVE_AUDIO_ON:"INVALID_REMOVE_AUDIO_ON",INVALID_REMOVE_TRACK_PUBLISHING:"INVALID_REMOVE_TRACK_PUBLISHING",INVALID_REMOVE_TRACK_NOT_TRACK:"INVALID_REMOVE_TRACK_NOT_TRACK",INVALID_REMOVE_TRACK_NUMBER:"INVALID_REMOVE_TRACK_NUMBER",INVALID_REPLACE_TRACK_NO_TRACK:"INVALID_REPLACE_TRACK_NO_TRACK",REPEAT_JOIN:"REPEAT_JOIN",CLIENT_DESTROYED:"CLIENT_DESTROYED",NOT_BUG_PACKAGE:"NOT_BUG_PACKAGE",START_MIX_TRANSCODE_FAILED:"START_MIX_TRANSCODE_FAILED",STOP_MIX_TRANSCODE_FAILED:"STOP_MIX_TRANSCODE_FAILED",MIX_TRANSCODE_NOT_STARTED:"MIX_TRANSCODE_NOT_STARTED",CANNOT_LESS_THAN_ZERO:"CANNOT_LESS_THAN_ZERO",MIX_PARAMS_VIDEO_FRAMERATE:"MIX_PARAMS_VIDEO_FRAMERATE",MIX_PARAMS_VIDEO_GOP:"MIX_PARAMS_VIDEO_GOP",MIX_PARAMS_AUDIO_BITRATE:"MIX_PARAMS_AUDIO_BITRATE",MIX_PARAMS_USER_Z_ORDER:"MIX_PARAMS_USER_Z_ORDER",MIX_PARAMS_NOT_SELF:"MIX_PARAMS_NOT_SELF",MIX_PARAMS_USER_STREAM:"MIX_PARAMS_USER_STREAM",INVALID_PLAY:"INVALID_PLAY",INVALID_ELEMENT_ID:"INVALID_ELEMENT_ID",INVALID_ELEMENT_ID_TYPE:"INVALID_ELEMENT_ID_TYPE",PLAY_FAILED:"PLAY_FAILED",INVALID_USERID:"INVALID_USERID",INVALID_CREATE_STREAM_SOURCE:"INVALID_CREATE_STREAM_SOURCE",INVALID_CREATE_STREAM_SCREEN:"INVALID_CREATE_STREAM_SCREEN",INVALID_CREATE_STREAM_AUDIO:"INVALID_CREATE_STREAM_AUDIO",INVALID_CREATE_STREAM_SCREEN_AUDIO:"INVALID_CREATE_STREAM_SCREEN_AUDIO",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",NOT_SUPPORTED_WEBRTC:"NOT_SUPPORTED_WEBRTC",NOT_SUPPORTED_PROFILE:"NOT_SUPPORTED_PROFILE",NOT_SUPPORTED_MEDIA:"NOT_SUPPORTED_MEDIA",NOT_SUPPORTED_H264ENCODE:"NOT_SUPPORTED_H264ENCODE",NOT_SUPPORTED_H264DECODE:"NOT_SUPPORTED_H264DECODE",NOT_SUPPORTED_TRACK:"NOT_SUPPORTED_TRACK",NOT_SUPPORTED_SWITCH_DEVICE:"NOT_SUPPORTED_SWITCH_DEVICE",NOT_SUPPORTED_CAPTURE:"NOT_SUPPORTED_CAPTURE",NOT_SUPPORTED_AUX:"NOT_SUPPORTED_AUX",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND",SIGNAL_RESPONSE_FAILED:"SIGNAL_RESPONSE_FAILED",CATCH_HANDLER_ERROR:"CATCH_HANDLER_ERROR",API_NOT_EXIST:"API_NOT_EXIST",CONNECTION_CLOSED:"CONNECTION_CLOSED",SUBSCRIBE_ALL_FALSE:"SUBSCRIBE_ALL_FALSE",SEI_NOT_SUPPORT:"SEI_NOT_SUPPORT",SEI_DISABLED:"SEI_DISABLED",SEI_BEFORE_PUBLISH:"SEI_BEFORE_PUBLISH",SEI_NOT_VIDEO:"SEI_NOT_VIDEO",CALL_FREQUENCY_LIMIT:"CALL_FREQUENCY_LIMIT",CONNECTION_ABORTED:"CONNECTION_ABORTED",API_CALL_ABORTED:"API_CALL_ABORTED",DUPLICATE_AUX:"DUPLICATE_AUX"},Je={AVOID_REPEATED_CALL(o){return`previous ${o.name}() is ongoing, please avoid repeated calls.`},INVALID_PARAMETER_REQUIRED({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s="";return Array.isArray(i.type)?s=i.type.join("|"):s=i.type,`'${r}' must be type of ${s} when calling ${e}(), received type: ${Me(t)}.`},INVALID_PARAMETER_EMPTY({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${s} when calling ${e}(), received type: ${Me(t)}.`},INVALID_PARAMETER_RANGE({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_MIN({key:o,rule:i,fnName:e,value:t}){return`the min value of ${o||i.name} is ${i.min}, received: ${t}.`},INVALID_PARAMETER_MAX({key:o,rule:i,fnName:e,value:t}){return`the max value of ${o||i.name} is ${i.max}, received: ${t}.`},API_CALL_TIMEOUT(o){return`${o.commandDesc||o.command} timeout observed.`},SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED(o){return`SignalChannel setup failure: (errorCode: ${o.errorCode}, errorMsg: ${o.errorMsg} }).`},ERROR_MESSAGE(o){let i=`${o.type} failed`;return o.message&&(i=`${i}: ${o.message}.`),i},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED(o){return`exchange sdp failed ${o.errMsg}.`},UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING(o){return`'${o}' must be validate string when useStringRoomId is true.`},INVALID_ROOMID_INTEGER(o){return`'${o}' must be an integer between [1, 4294967294] when useStringRoomId is false.`},INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED({error:o,code:i}){return`Failed to join room - ${o} code: ${i}`},REJOIN_ROOM_FAILED(o){return`reJoin room: ${o.roomId} failed, please check your network.`},INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:'no permission to publish() under live/audience, please call switchRole("anchor") firstly before publish().',INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING(o){return`duplicate ${o} stream publishing, please unpublish your prev ${o} stream and then re-publish.`},INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED({message:o,userId:i,streamType:e}){return`failed to subscribe ${i} ${e} stream, reason: ${o}.`},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:"role could only be set to a value as anchor or audience.",INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED(o){return`switchRole failed, errCode: ${o.code} errMsg: ${o.message}.`},CLIENT_BANNED(o){return`client was banned because of ${o.message}.`},INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED(o){return`startPublishCDNStream failed, errMsg: ${o.message}.`},STOP_PUBLISH_CDN_FAILED(o){return`stopPublishCDNStream failed, errMsg: ${o.message}.`},INVALID_STREAM_ID(o){return`'${o}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK(o){return`cannot replace ${o.kind} track because stream has not ${o.kind} track`},NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED(o){return`startMixTranscode failed, errMsg: ${o.message}.`},STOP_MIX_TRANSCODE_FAILED(o){return`stopMixTranscode failed, errMsg: ${o.message}.`},MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' cannot be less than 0 when calling ${e}().`},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER(o){return`'${o}' is required and must be between 1 and 15.`},MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:({key:o,fnName:i})=>`'${o}' is not found in the document object when calling ${i}().`,INVALID_ELEMENT_ID_TYPE:({key:o,fnName:i,type:e})=>`the element corresponding to '${o}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`,PLAY_FAILED:o=>`${o.media} play failed, browser exception: ${o.error.toString()}`,INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK(o){return`${o}Track is not supported on your browser.`},NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED(o){return`${o.signalResponse} failed, response code is ${o.code} , errMsg: ${o.message}.`},CATCH_HANDLER_ERROR({name:o,event:i}){return`an error was caught in ${o}.on('${i}', handler), please check your code in 'handler'.`},API_NOT_EXIST({name:o}){return`experimental api ${o} does not exist.`},REPEAT_JOIN:o=>"please avoid repeated join.",CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED({funName:o}){return`failed to call ${o}() because client was destroyed.`},SEI_NOT_SUPPORT:o=>`not support to sendSEIMessage${o===!1?" without using h264 codec":""}`,SEI_DISABLED:"SEI is disabled",SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:({isSize:o,name:i,timesInSecond:e,maxSizeInSecond:t})=>`api ${i} call ${o?"size":"times"} is over ${o?`${t} bytes`:e} in a second.`,CONNECTION_ABORTED(o){return`connection aborted due to: ${o}`},API_CALL_ABORTED(o){let i;return o.message.includes("REMOTE_STREAM_NOT_EXIST")?i=`Subscribe ${o.userId} ${o.streamType} stream aborted, reason: remote user ${o.userId} unpublished stream.`:i=`API aborted, reason: ${o.message}`,i},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:o=>`'streamType' is required when 'userId' is not '*', calling ${o}()`};var cp=(o,i)=>i?`${ft}/${o}/${i}`:`${ft}/${o}/index.html`;var hT=()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};let o=localStorage==null?void 0:localStorage.getItem(Xd);if(o){o=JSON.parse(o);let i=document.createElement("script");i.type="text/javascript",i.text=o.message,document.body.appendChild(i);let e=window.TRTC_ERROR_INFO,t=window.TRTC_ERROR_LINK;return document.body.removeChild(i),{TRTC_ERROR_INFO:e,TRTC_ERROR_LINK:t}}return{}};function H(o){let{key:i,data:e,link:t,addDocLink:r=!0}=o,s="",n="",a="";le(Je[i])?s=Je[i](e):ie(Je[i])&&(s=Je[i]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=hT();t?a=`${t.className}.html#${t.fnName}`:l&&l[i]&&(le(l[i])?a=l[i](e):ie(l[i])&&(a=l[i]));let u=s;return Yt()&&(c&&c[i]&&(le(c[i])?n=c[i](e):ie(c[i])&&(n=c[i])),n&&(r?u=`${n}
|
|
7
7
|
\u8BF7\u67E5\u770B\u6587\u6863: ${cp("zh-cn",a)}
|
|
8
8
|
|
|
@@ -30,7 +30,7 @@ ${t.stack}`));let s=Ir.enable?Gi(r,2002,Number(this._configs.sdkAppId)):JSON.str
|
|
|
30
30
|
<path d="m512 960c-247.04 0-448-200.96-448-448s200.96-448 448-448 448 200.96 448 448-200.96 448-448 448zm0-831.71c-211.58 0-383.71 172.13-383.71 383.71 0 211.55 172.13 383.71 383.71 383.71 211.55 0 383.71-172.16 383.71-383.71 0-211.58-172.16-383.71-383.71-383.71z" p-id="2032"/>
|
|
31
31
|
<path d="m512 673.7c-17.665 0-32.001-14.336-32.001-31.999v-54.112c0-52.353 40-92.352 75.328-127.65 25.887-25.92 52.672-52.672 52.672-74.017 0-53.343-43.072-96.735-95.999-96.735-53.823 0-95.999 41.536-95.999 94.559 0 17.665-14.336 31.999-32.001 31.999s-32.001-14.336-32.001-31.999c0-87.424 71.775-158.56 160-158.56s160 72.095 160 160.74c0 47.904-36.32 84.192-71.424 119.3-27.84 27.776-56.576 56.512-56.576 82.336v54.112c0 17.665-14.336 32.032-32.001 32.032z" p-id="2033"/>
|
|
32
32
|
</svg>
|
|
33
|
-
`,t.onclick=this.onQuestionClick.bind(this);let r=document.createElement("div");r.className=Su,r.innerText=`${Yt()?"\u8BE6\u60C5 >":"Detail >"}`,r.onclick=this.onCollapseClick.bind(this);let s=i.content.firstChild,n=s.querySelector(`.${Ac}`);return n.appendChild(r),n.appendChild(t),n.appendChild(e),s}addDiaLog(){br()||(Iu=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${bn}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",R.info("show autoplay dialog"),se.uploadEvent({log:$T}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,Iu=!1)}onConfirm(){R.warn("confirm clicked, try resume stream"),S.emit(C.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDialog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${Up}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||se.uploadEvent({log:WT}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Hp,"_blank"),this._isQuestionClicked||se.uploadEvent({log:GT}),this._isQuestionClicked=!0}},vn=null;function ns(){vn||(vn=new Au)}function $p(){vn&&(vn.deleteDialog(),vn=null)}var it=class o extends mi{constructor(e){super(e,f.VIDEO);d(this,"stat",{});d(this,"_calculateTimeout",-1);d(this,"viewMirror",!1);d(this,"objectFit","cover");d(this,"container");d(this,"canvas");d(this,"shouldRenderAlpha",!1);d(this,"_preSize",{width:0,height:0});d(this,"posterImg");d(this,"_originContainerPosition");this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,T(e.viewMirror)||(this.viewMirror=e.viewMirror),T(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}get isPlaying(){var e;return this._state!=="PLAYING"||this.element&&this.element.paused?!1:((e=this.track)==null?void 0:e.readyState)==="live"&&!this.track.muted}initializeElement(){var t;let e=document.createElement(f.VIDEO);this.track&&this.mode!==2&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,_e&&(e.poster="noposter"),(t=this.container)==null||t.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let e=`width:100%;height:100%;object-fit:${this.objectFit};${this.shouldRenderAlpha?"":"background-color:black"};`;return this.viewMirror&&(e+="transform:scaleX(-1);"),e}setContainer(e){var t;this.container=e,this.track&&this.elementToRender&&((t=this.container)==null||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(f.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(f.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(f.RESIZE,this.handleElementEvent)}handleTrackEvent(e){var t;return e.type===f.MUTE&&((t=this.stat)!=null&&t.fps)&&(this.stat.fps=0),super.handleTrackEvent(e)}handleElementEvent(e){var r,s,n,a,c,l;if(this.mode===2)return;super.handleElementEvent(e);let t=e.type;if(t===f.PAUSE&&(this.container&&!this.container.isConnected&&(this._log.warn(`${this.kind} player has been remove, element ID: ${this.container.id}`),Ke(500).then(()=>{var u;(u=this.container)!=null&&u.isConnected&&(this._pausedRetryCount=$r,this._log.info(`view container ${this.container.id} is in dom, reset pausedRetryCount`))})),this._pausedRetryCount>0&&!br()&&!this._isPausedByUserCall&&(this._log.info(`[${$r-this._pausedRetryCount+1}/${$r}] ${this.kind} player auto resume when paused`),this.doResume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let u=this.element.style.transform;t===f.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=u.replace("scaleX(-1)",""):t===f.LEAVE_PICTURE_IN_PICTURE&&!u.includes("scaleX")&&(this.element.style.transform=`${u} scaleX(-1)`)}t===f.RESIZE&&(this._preSize.height!==((r=this.element)==null?void 0:r.videoHeight)||this._preSize.width!==((s=this.element)==null?void 0:s.videoWidth))&&(this._log.info(`video size changed to ${(n=this.element)==null?void 0:n.videoWidth}x${(a=this.element)==null?void 0:a.videoHeight}`),this._preSize.height=((c=this.element)==null?void 0:c.videoHeight)||0,this._preSize.width=((l=this.element)==null?void 0:l.videoWidth)||0,this.emit(ue.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height}))}setCanvas(e,t=1){var r,s,n,a;this.canvas!==e&&((r=this.canvas)==null||r.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?t:0,this.mode===2&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?((s=this.element)==null||s.remove(),(n=this.container)==null||n.appendChild(e)):this.element&&((a=this.container)==null||a.appendChild(this.element)))}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width=`${e}px`,this.elementToRender.style.height=`${t}px`)}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit=`${e}`),this.objectFit=e}setPoster(e,t=!1){return new Promise(r=>{if(this.element)if(this._log.info("setPoster",e.slice(0,10)),this.element.poster=e,t&&(Re||K)){if(e==="")this.removePosterImg();else if(!this.posterImg){let s=document.createElement("img");s.src=e,s.style=`position:absolute;top:0;left:0;width:100%;height:auto;aspect-ratio:${this.element.videoWidth/this.element.videoHeight};max-height: 100%;`,s.onload=()=>p(this,null,function*(){var n;s.decode&&(yield s.decode()),this.container&&window.getComputedStyle(this.container).position==="static"&&(this._originContainerPosition=this.container.style.position,this.container.style.position="relative"),this.posterImg=s,(n=this.container)==null||n.appendChild(s),r()})}}else r()})}removePosterImg(){this.posterImg&&(this.posterImg.remove(),URL.revokeObjectURL(this.posterImg.src),this.container&&this._originContainerPosition&&this.container.style.position==="relative"&&(this.container.style.position=this._originContainerPosition),delete this.posterImg)}pause(e=!0){return p(this,null,function*(){return($e&&qe>=128||e&&(K||Re))&&(yield this.setPoster(this.getVideoFrame(),!0)),Pe(o.prototype,this,"pause").call(this)})}resume(e=!1){return this.posterImg&&this.setPoster("",!0),super.resume(e)}doResume(e=!1){return e&&this.element&&this.track&&$e&&qe>=128&&this.track.kind==="video"&&(this.element.srcObject=new MediaStream([this.track])),super.doResume()}stop(e=0){var t;super.stop(e),(t=this.canvas)==null||t.remove(),this.removePosterImg()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(ue.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(Ki()&&this.element&&this._calculateTimeout<0){let e=0,t=null,r=(s,n)=>{this.stat.width=n.width,this.stat.height=n.height,t&&(this.stat.fps=Math.round((n.presentedFrames-t.presentedFrames)/(s-e)*1e3)),e=s,t=n,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var a;return(a=this.element)==null?void 0:a.requestVideoFrameCallback(r)},2e3))};this.element.requestVideoFrameCallback(r)}}catch(e){this._log.warn("init stat failed",e)}}enterFullscreen(){return p(this,null,function*(){let e=this.elementToRender;if(!e)throw this._log.warn("no element to render, cannot enter fullscreen"),new Error("No element available for fullscreen");try{if(e.requestFullscreen)yield e.requestFullscreen();else if(e.webkitRequestFullscreen)yield e.webkitRequestFullscreen();else if(e.webkitEnterFullscreen)yield e.webkitEnterFullscreen();else if(e.mozRequestFullScreen)yield e.mozRequestFullScreen();else if(e.msRequestFullscreen)yield e.msRequestFullscreen();else throw this._log.warn("fullscreen API not supported"),new Error("Fullscreen API not supported");this._log.info("entered fullscreen mode")}catch(t){throw this._log.error("failed to enter fullscreen:",t),t}})}exitFullscreen(){return p(this,null,function*(){try{if(document.exitFullscreen)yield document.exitFullscreen();else if(document.webkitExitFullscreen)yield document.webkitExitFullscreen();else if(document.mozCancelFullScreen)yield document.mozCancelFullScreen();else if(document.msExitFullscreen)yield document.msExitFullscreen();else throw this._log.warn("exit fullscreen API not supported"),new Error("Exit fullscreen API not supported");this._log.info("exited fullscreen mode")}catch(e){throw this._log.error("failed to exit fullscreen:",e),e}})}isFullscreen(){let e=this.elementToRender;return e?(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)===e:!1}toggleFullscreen(){return p(this,null,function*(){this.isFullscreen()?yield this.exitFullscreen():yield this.enterFullscreen()})}enterPictureInPicture(){return p(this,null,function*(){if(!this.element)throw new Error("No video element available for picture-in-picture");if(this.canvas&&this.mode!==1)throw new Error("Picture-in-picture is not supported for canvas-only mode");let{element:e}=this;try{if(this._log.warn(!!e.requestPictureInPicture,!!e.webkitSetPresentationMode),e.requestPictureInPicture){this._log.info("requestPictureInPicture");let t=yield e.requestPictureInPicture();return this._log.info("entered picture-in-picture mode"),t}if(e.webkitSetPresentationMode)return this._log.info("webkitSetPresentationMode"),yield e.webkitSetPresentationMode("picture-in-picture"),this._log.info("entered picture-in-picture mode (webkit)"),{};throw new Error("Picture-in-picture API not supported")}catch(t){throw this._log.error("failed to enter picture-in-picture:",t.name,t.message),t}})}exitPictureInPicture(){return p(this,null,function*(){try{if(document.pictureInPictureElement&&document.exitPictureInPicture)yield document.exitPictureInPicture(),this._log.info("exited picture-in-picture mode");else if(this.element&&this.element.webkitSetPresentationMode)yield this.element.webkitSetPresentationMode("inline"),this._log.info("exited picture-in-picture mode (webkit)");else throw this._log.warn("exit picture-in-picture API not supported or not in PiP mode"),new Error("Exit picture-in-picture API not supported or not in PiP mode")}catch(e){throw this._log.error("failed to exit picture-in-picture:",e),e}})}isPictureInPicture(){if(!this.element)return!1;let{element:e}=this;return document.pictureInPictureElement?document.pictureInPictureElement===e:e.webkitPresentationMode?e.webkitPresentationMode==="picture-in-picture":!1}togglePictureInPicture(){return p(this,null,function*(){this.isPictureInPicture()?yield this.exitPictureInPicture():yield this.enterPictureInPicture()})}};function tr(o,i){return p(this,null,function*(){if(!o.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield o.audioWorklet.addModule(i),R.info("worklet addModule success")}catch(e){throw R.info(`worklet addModule catch error. ${e.message}`),e}})}var Nn;typeof AudioContext!="undefined"?Nn=AudioContext:typeof webkitAudioContext!="undefined"?Nn=webkitAudioContext:typeof mozAudioContext!="undefined"&&(Nn=mozAudioContext);var vu=1500,rt,Wp=-1,Rc=0,Dn=-1,bu=!1,Gp=0,qp=-1,Jp=-1;jp();function jp(){try{if(rt)return;rt=new Nn({sampleRate:48e3}),rt.onstatechange=()=>{R.info(`context state: ${rt.state}${rt.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),as()},clearTimeout(Wp)}catch(o){R.error(`initAudioContext failed: ${o} typeof AudioContextClass: ${typeof Nn}`),Wp=setTimeout(jp,1e3)}}var as=()=>{rt.state==="suspended"?(Rc=U(),JT(),vr(),document.addEventListener("click",as)):rt.state==="interrupted"?vr():(Rc&&(v.addNumber({key:507800,value:U()-Rc,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),Rc=0),jT(),document.removeEventListener("visibilitychange",as),document.removeEventListener("click",as))},Ru=0,yu=-1;function vr(){return new Promise((o,i)=>{if(rt.state==="running")return o();Date.now()-Ru<1e3?(clearTimeout(yu),yu=setTimeout(()=>{Ru=Date.now(),rt.resume().then(o,i)},1e3)):(clearTimeout(yu),Ru=Date.now(),rt.resume().then(o,i))}).catch(o=>{R.warn(`context resume failed: ${o}`),document.addEventListener("visibilitychange",as)})}document.addEventListener("click",as);function JT(){Dn===-1&&(Dn=setTimeout(()=>{rt.state==="suspended"&&(bu=!0,S.emit("155",{isSuspended:!0}))},vu))}function jT(){Dn!==-1&&(clearTimeout(Dn),Dn=-1,bu&&(bu=!1,S.emit("155",{isSuspended:!1})))}function Xp(){if(!ge||Jp!==-1)return;let o=()=>{U()-Gp<500||(rt&&rt.state==="running"&&rt.currentTime===qp&&(R.warn("context is fake running, auto resume"),rt.suspend().catch(i=>{R.warn(`context suspend failed: ${i}`)})),qp=rt.currentTime,Gp=U())};Jp=setInterval(()=>{o()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&o()})}var Ee=o=>rt;var xe=class{constructor(i){this.name=i;d(this,"node");d(this,"node2");d(this,"pre",new Set);d(this,"next",new Set);d(this,"context");d(this,"connectedNodes",new Set);d(this,"nextInputChannelMap",new Map);d(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(i){this._channelCount=i,this.setChannelCount(this.node,i),this.setChannelCount(this.node2,i),this.next.forEach(e=>e.channelCount=i)}setChannelCount(i,e){!i||i instanceof ScriptProcessorNode||(i.channelCountMode="explicit",i.channelCount=e||this.channelCount||1)}setContext(i){this.context=i,this.node&&i.addMixWeight()}removeContext(){var i;this.node&&((i=this.context)==null||i.reduceMixWeight()),delete this.context}replaceNode(i){var e;if(i!==this.node)try{this.node?this._disconnect():(e=this.context)==null||e.addMixWeight(),this.node=i,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(t){R.error(t)}}setNode(i,e){var t;if(!this.node)try{(t=this.context)==null||t.addMixWeight(),this.node=i,this.setChannelCount(this.node),e&&(this.node2=e,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),v.addSuccessEvent({key:502701})}catch(r){R.error(r),v.addFailedEvent({key:502701,error:r})}}deleteNode(){var i;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(i=this.context)==null||i.reduceMixWeight(),this.preNodeReconnect(),v.addSuccessEvent({key:502702})}catch(e){R.error(e),v.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(i=>{i.node?i.reconnect():i.preNodeReconnect()})}connectNext(i){this.next.forEach(e=>{let t=this.nextInputChannelMap.get(e);i._connect(e.node,t)||e.connectNext(i)})}_connect(i,e=0){return!this.node||!i?!1:((this.node2||this.node).connect(i,0,e),this.connectedNodes.add(i),!0)}_disconnect(){this.connectedNodes.forEach(i=>{var e;return(e=this.node2||this.node)==null?void 0:e.disconnect(i)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(i,e=0){return this.next.add(i),i.pre.add(this),this.nextInputChannelMap.set(i,e),i}},yc=class extends xe{constructor(e=256){super();this.fftSize=e;d(this,"dataArray",new Uint8Array(0))}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),t=1,r=0,s=0,n=`M${r},${s}`;for(let a=0;a<e.length;a++)s=e[a]/128*100/2,n+=`L${r},${s}`,r+=t;return n}},Mn=class{constructor(){d(this,"source",new xe);d(this,"gain",new xe);d(this,"destination",new xe)}get volume(){var i;return((i=this.gain.node)==null?void 0:i.gain.value)||1}setVolume(i){if(i===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(Ee().createGain()),this.gain.node.gain.value=i}replaceSource(i){let e=On(i);e&&this.source.replaceNode(e)}get track(){var i;return(i=this.stream)==null?void 0:i.getAudioTracks()[0]}get stream(){var i;return(i=this.destination.node)==null?void 0:i.stream}},cs=class extends Mn{constructor(e){super();this.context=e;d(this,"aec",new xe("aec"));d(this,"mixNode",new xe("mixNode"));d(this,"silentNode",new xe("silentNode"));d(this,"denoiser",new xe("denoiser"));d(this,"voiceChanger",new xe("voiceChanger"));this.source.pipeTo(this.aec).pipeTo(this.denoiser).pipeTo(this.voiceChanger).pipeTo(this.gain).pipeTo(this.destination),this.silentNode.pipeTo(this.mixNode).pipeTo(this.aec,1)}get isProcessEnabled(){return this.aec.node||this.denoiser.node||this.voiceChanger.node||this.gain.node}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.aec.setContext(this.context),this.silentNode.setContext(this.context),this.mixNode.setContext(this.context),this.denoiser.setContext(this.context),this.voiceChanger.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){this.context.inputs.has(this)&&(this.destination.deleteNode(),this.source.removeContext(),this.aec.removeContext(),this.silentNode.removeContext(),this.mixNode.removeContext(),this.denoiser.removeContext(),this.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.aec.deleteNode(),this.silentNode.deleteNode(),this.mixNode.deleteNode(),this.denoiser.deleteNode(),this.voiceChanger.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){if(e===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e}},bc=class{constructor(){d(this,"audioContext",Ee("audio-mixer"));d(this,"destination",this.audioContext.createMediaStreamDestination());d(this,"inputs",new Set);d(this,"mixWeight",0);this.destination.channelCount=1}addMixWeight(i=1){this.mixWeight+=i,this.mixWeight-1===i+1>>1&&this.mixOnChange()}reduceMixWeight(i=1){this.addMixWeight(-i)}close(){this.inputs.forEach(i=>i.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},zp=new WeakMap;function On(o){try{let i=zp.get(o);if(i)return i;let e=Ee();if(o instanceof HTMLAudioElement)i=e.createMediaElementSource(o);else if(o instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([o]));else return o;return zp.set(o,i),i}catch(i){if(K&&i instanceof Error&&i.name==="NotSupportedError")R.warn(i);else throw i}}var Ot=class Ot{constructor(i){d(this,"_volume",0);d(this,"_volumeDb",0);d(this,"_log");d(this,"_scriptProcessorNode",null);d(this,"_audioWorkletNode",null);d(this,"_interval",200);d(this,"ready",this.preload());let{log:e}=i;this._log=e,S.on(C.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-Ot.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!Ot.workletReady){let i='class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,s){t=t[0],s=s[0];if(t||s){if(this.isStop)return!1;var i=s&&s[0]?s[0].length:0,h=this.cache.length,a=(i<h?(s[0].set(this.cache.slice(0,i)),this.cache=this.cache.slice(i)):this.unmute&&s[0].set(t[0]),(i<h?s:t)[0]);if(a){let e=0;for(let t=0;t<a.length;++t)e=Math.max(Math.abs(a[t]),e);s=a.reduce((t,e)=>t+e*e,0)/a.length;this.volume=e,this.tick-=a.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,volumeDb:Math.max(10*Math.log10(s)+100,0)/100,cacheLen:h,outputLen:i}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';Ot.workletReady=tr(Ot.audioContext,URL.createObjectURL(new Blob([i],{type:"application/javascript"})))}return Ot.workletReady.then(()=>this.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Ot.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{Ot.lastMessageTime=Date.now(),this._volume=e.data.volume||0,this._volumeDb=e.data.volumeDb||0,!i&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),i=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(i){this._log.error(`volumeMeter init audio worklet error: ${i}`),se.logFailedEvent({userId:this._log.userId,eventType:Ze.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=Ee("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{Ot.lastMessageTime=Date.now();let e=i.inputBuffer.getChannelData(0),t=0;for(let r=0;r<e.length;++r)t+=e[r]*e[r];this._volume=Math.sqrt(t/e.length)||0}}catch(i){this._log.error(`volumeMeter init script processor error: ${i}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,S.off(C.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}getVolumeDb(){return Math.floor(this._volumeDb*100)}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}};d(Ot,"lastMessageTime",0),d(Ot,"audioContext",Ee("volume-meter")),d(Ot,"workletReady");var vc=Ot,kn=class extends xe{constructor(e){super();d(this,"_volumeMeter");this._volumeMeter=new vc(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return p(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}getVolumeDb(){return this._volumeMeter.getVolumeDb()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),r=new Float32Array(t>>2);e.copyTo(r,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:r},[r.buffer]),e.close()}}},so=vc;var Kp=Ge(at(),1);var Yp=o=>i=>i.deviceId===o;var Pn=class{constructor(i,e){d(this,"kind");d(this,"type");d(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(r=>r.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&ls(this.devices[0])){this.devices=t;return}e&&(t.forEach(r=>{if(r.deviceId&&!this.devices.find(Yp(r.deviceId))){let s=`${this.kind}${this.type}Added`;R.warn(`${s}: ${JSON.stringify(r)}`),e.emit(s,r)}}),this.devices.forEach(r=>{if(r.deviceId&&!t.find(Yp(r.deviceId))){let s=`${this.kind}${this.type}Removed`;R.warn(`${s}: ${JSON.stringify(r)}`),e.emit(s,r)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},Nu=class extends Kp.EventEmitter{constructor(){super();d(this,"audioInputs",new Pn(f.AUDIO,"Input"));d(this,"videoInputs",new Pn(f.VIDEO,"Input"));d(this,"audioOutputs",new Pn(f.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||oe.run("interval",()=>{this.update()},{delay:1e4}))}init(){ds().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return p(this,arguments,function*(e=0){let t=yield ds(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}hasBlueTooth(){var t;if(((t=Ee())==null?void 0:t.outputLatency)*1e3>150)return!0;let e=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some(r=>e.some(s=>r.label.toLowerCase().includes(s)))||this.audioInputs.devices.some(r=>e.some(s=>r.label.toLowerCase().includes(s)))}},be=xs||Do?null:new Nu;function ls(o){return o.deviceId===o.groupId&&o.groupId===""}function ds(){return p(this,arguments,function*(o=0){if(Zi()||!pc())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(o!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{ls(t)&&(t.kind===f.AUDIO_INPUT?e.audio=!0:t.kind===f.VIDEO_INPUT&&(e.video=!0))}),o===2&&(e.audio=!1),o===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e),e.audio&&vr()}catch(r){R.debug("capture before getDevices failed: ",r)}i=yield navigator.mediaDevices.enumerateDevices(),t==null||t.getTracks().forEach(r=>r.stop())}}return i.map((e,t)=>{let r={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${t}`};return e.deviceId.length>0&&Du.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(r.getCapabilities=()=>e.getCapabilities()),r})})}function It(o=!1){return be.update(o?1:0).then(i=>i.audioInputs.devices)}function At(o=!1){return be.update(o?2:0).then(i=>i.videoInputs.devices)}var Zp=!1;function ef(){return p(this,null,function*(){try{Zp||(Zp=!0,R.info(`speakers:${(yield Nr()).map(o=>` ${o.deviceId.slice(0,8)}: ${o.label}`)}`))}catch(o){}})}function Nr(o=!1){return p(this,null,function*(){return(ge||Re)&&(o=!1),be.update(o?1:0).then(i=>i.audioOutputs.devices)})}var Du=new Set;function tf(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let i=o.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let t=`${((o==null?void 0:o.getSettings())||{}).deviceId}_${f.VIDEO_INPUT}`;return!!Du.has(t)}function rf(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let i=o.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("\u9EA6\u514B\u98CE"))return!0;let t=`${((o==null?void 0:o.getSettings())||{}).deviceId}_${f.AUDIO_INPUT}`;return!!Du.has(t)}function Mu(o,i){return p(this,null,function*(){let t=(yield It()).find(r=>r.deviceId===Wr);return!i&&(t==null?void 0:t.groupId)===o||(t==null?void 0:t.groupId)===o&&t.label===i})}function of(s){return p(this,arguments,function*({newDeviceId:o,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:r}){return o!==i?!1:r===f.AUDIO&&o===Wr?yield Mu(e,t):!0})}var Nc,Ou=class extends Mn{constructor(e){super();this.log=e;d(this,"volumeMeter");d(this,"volumeMeterAfter3A");d(this,"volumeDestination");d(this,"analyser",new yc);this.volumeMeter=new kn({log:this.log}),this.volumeMeterAfter3A=new kn({log:this.log}),this.volumeDestination=new xe,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},us=class o extends mi{constructor(e){super(e,f.AUDIO);d(this,"_outputDeviceId");d(this,"_floatVolume",1);d(this,"_destination",Ee("player").createMediaStreamDestination());d(this,"pipeline");d(this,"volumeMeterMode","worklet");d(this,"enableVolumeControlInIOS");this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this.mode=0,e.url&&(this.url=e.url),this.pipeline=new Ou(this._log)}setTrack(e){}get duration(){var e;return Math.floor((((e=this.element)==null?void 0:e.duration)||0)*1e3)}get currentTime(){var e;return Math.floor((((e=this.element)==null?void 0:e.currentTime)||0)*1e3)}set currentTime(e){this.element&&(this.element.currentTime=e/1e3)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((Tt==="15.2"||Tt==="15.3"||Tt==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let r=Nc||new Audio;r.setAttribute("autoplay","autoplay"),r.srcObject=this.getMediaStream(),r.muted=this.muted,this.url&&(r.crossOrigin="anonymous",r.src=this.url),this.element=r,this.setVolume(z(e)?e/100:this._floatVolume),r===Nc&&(Nc=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(ue.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}play(e){return p(this,null,function*(){if(!(!this.track&&!this.url))return!this.pipeline.source.node&&this.track&&this.pipeline.replaceSource(this.track),this.element||this.initializeElement(e==null?void 0:e.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?(this.pipeline.volumeMeter.init(),this.pipeline.volumeMeterAfter3A.init()):this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(Ee("player").createAnalyser()),ef(),Pe(o.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(e)}setVolume(e){this._floatVolume=e,this.element&&(this.element.volume=e)}setSinkId(e){return p(this,null,function*(){var t,r;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(r=(t=this.element).setSinkId)==null?void 0:r.call(t,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){this.element&&(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}getInternalAudioLevelAfter3A(){return this.pipeline.volumeMeterAfter3A.getInternalAudioLevel()}},Dc=class extends us{setTrack(i){this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(ue.MEDIA_TRACK_CHANGED,i),i&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([i]))))}},hs=class extends us{constructor(e){super(e);d(this,"_sourceElement");d(this,"_output",new xe);this.pipeline.source.pipeTo(this.pipeline.gain),this.pipeline.gain.pipeTo(this.pipeline.volumeMeter).pipeTo(this._output),this.pipeline.gain.pipeTo(this.pipeline.destination)}setOutput(){this.mode=1,this._output.setNode(Ee("player").destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,r,s;((r=(t=this.element)==null?void 0:t.error)==null?void 0:r.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(ue.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=((s=e.getSettings())==null?void 0:s.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){if(this._floatVolume=e,this.useDestination)this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`);else if(e<=1&&!ge)this.element?(this._log.info(`set element volume: ${e}`),this.element.volume=e):this._log.info("set element volume: no element");else{if(ge)if(this.enableVolumeControlInIOS)Xp();else return;if(K&&!this.pipeline.source.node){this._log.warn("set pipeline volume failed: no source node");return}this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),Le(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play())}}stop(e=0){this.pipeline.destroy();let t=this._sourceElement||this.element;t&&Ft&&(Nc=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var no=class extends J{constructor({userId:e,sdkAppId:t,mediaType:r,room:s,PlayerClass:n=r===1?hs:it}){var a;super();d(this,"id",cn());d(this,"userId","");d(this,"isRemote");d(this,"mediaType");d(this,"room");d(this,"user");d(this,"_log");d(this,"_inputTrack");d(this,"_outputTrack");d(this,"isPlayCalled");d(this,"container",null);d(this,"player");d(this,"subVideoPlayerMap");d(this,"muted",!1);d(this,"abortCtrl");d(this,"objectFit","cover");d(this,"mirror");d(this,"rotation");d(this,"isScreen",!1);d(this,"manager");d(this,"trackSettings");d(this,"isFirstVideoFrameEmitted",!1);this.userId=e||"",this.mediaType=r,this._log=R.createLogger({parent:s==null?void 0:s.getLogger(),id:`${this.kind[0]}t`,userId:(a=s||this.room)==null?void 0:a.userId,remoteUserId:this instanceof pi?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof pi}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:s==null?void 0:s.enableVolumeControlInIOS}),this.player.on(ue.PLAYER_STATE_CHANGED,c=>{if(S.emit(C.PLAYER_STATE_CHANGED,O({track:this},c)),this.emit("player-state-changed",c),c.state==="PLAYING"&&this.room){let l=!0;for(let{remoteAudioTrack:u,remoteVideoTrack:m,remoteAuxiliaryTrack:h}of[...this.room.remotePublishedUserMap.values()])if(u.isAvailable&&!u.player.isPlaying||m.isAvailable&&!m.player.isPlaying||h.isAvailable&&!h.player.isPlaying){l=!1;break}l&&br()&&$p()}}),this.kind===f.VIDEO&&(this.player.on(ue.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(ue.LOADED_DATA),S.emit(C.VIDEO_LOADED_DATA,{track:this})}),this.player.on(ue.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(ue.LOADED_META_DATA)}),this.player.on(ue.MEDIA_TRACK_CHANGED,c=>{var l;(l=this.subVideoPlayerMap)==null||l.forEach(u=>u.setTrack(c))}),this.player.on(ue.RESIZE,c=>{this.emitFirstVideoFrameEvent(ue.RESIZE),this.emit("video-size-changed",O({userId:this.userId,streamType:this.mediaType===2?"auxiliary":"main"},c))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(ue.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||R}get kind(){return this.mediaType===1?f.AUDIO:f.VIDEO}get isAudio(){return this.kind===f.AUDIO}get strMediaType(){return this.mediaType===4?f.VIDEO:this.mediaType===2?f.SCREEN:f.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}get isMediaTrackActive(){return this.mediaTrack?!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled:!1}play(e,t){return p(this,null,function*(){let r=Ie(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(t)}`),t&&!T(t.muted)&&this.setPlayerMute(t.muted),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof it&&(this.player.setObjectFit(this.objectFit),this.container!==r&&r&&(this.container=r,this.player.setContainer(r)),Ie(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t)));return}if(t&&!T(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===f.VIDEO)&&this.setPlayerMute(!0),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof it&&(this.player.setObjectFit(this.objectFit),t&&!T(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,r&&(this.container=r,this.player instanceof it&&this.player.setContainer(r)),S.emit(C.PLAY_TRACK_START,{track:this}),!this._outputTrack){this.log.info("play has not mediaTrack, abort");return}this._log.info(`play with options: ${JSON.stringify(t)}`);try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(t),Ie(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(s){throw this.handleAutoPlayFailed(s),s}})}setMirror(e,t){if(this.isScreen||this.kind!==f.VIDEO||T(e)||e===this.mirror)return;this.mirror=e;let r=this.player;t&&(r=t);let s=this.manager;if(he(this.mirror)){r.setViewMirror(this.mirror),!this.isRemote&&s&&(s.mirror=!1);return}switch(this.mirror){case"view":{s&&(s.mirror=!1),r.setViewMirror(!0);break}case"publish":{s&&(s.mirror=!0),r.setViewMirror(!0);break}case"both":s&&(s.mirror=!0),r.setViewMirror(!1)}}playSubContainer(e,t){return p(this,null,function*(){if(!this._outputTrack||this.kind===f.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((s,n)=>{var a;e.find(c=>n===c)||(s.stop(),(a=this.subVideoPlayerMap)==null||a.delete(n))});for(let[s,n]of e.entries()){let a=this.subVideoPlayerMap.get(n);a?t&&(T(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new it({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${s+1}`})}))}let r=[...this.subVideoPlayerMap.values()];for(let s of r)s.setViewMirror(this.player.mirror),yield s.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(e=!1){this.isPlayCalled&&(this.isPlayCalled=!1,this.isFirstVideoFrameEmitted=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(Sl(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(t=>{t.stop()}),this.container=null)}resume(){return p(this,null,function*(){var e;this.isPlayCalled&&(yield(e=this.player)==null?void 0:e.resume())})}close(){this.log.info("close"),this.isPlayCalled&&this.stop(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),S.emit(e?C.TRACK_MUTED:C.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(e){tt(e,e).add(f.MUTE,this.onTrackMuted).add(f.UNMUTE,this.onTrackUnmuted).add(f.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===f.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){Le(e)}setInputMediaStreamTrack(e){var r;let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.trackSettings=(r=e.getSettings)==null?void 0:r.call(e),e.enabled=!this.muted,t&&this.uninstallTrackEvent(t),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,t||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var r;let t=this._outputTrack;e!==t&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(r=e.getSettings)==null?void 0:r.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(t=>this.handleAutoPlayFailed(t)),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(Sl(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(e){return p(this,null,function*(){var r;this.log.warn("handleAutoPlayFailed",e);let t=()=>{this.resume().then(()=>{document.removeEventListener("click",t,!0)})};if(this.room&&this.room.enableAutoPlayDialog){if((Ji||ji)&&(yield Ke(100),(r=this.player)!=null&&r.isPlaying))return;ns()}else document.addEventListener("click",t,!0);S.once(C.LOCAL_TRACK_CAPTURE_SUCCESS,({track:s})=>{s.kind==="audio"&&br()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&t()}),this.emit("error",e)})}getVideoFrame(){return this.player instanceof it?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var n,a,c;if(this.isFirstVideoFrameEmitted)return;let t=(n=this.mediaTrack)==null?void 0:n.getSettings(),r=(t==null?void 0:t.width)||((a=this.player.element)==null?void 0:a.videoWidth)||0,s=(t==null?void 0:t.height)||((c=this.player.element)==null?void 0:c.videoHeight)||0;e===ue.RESIZE&&!r&&!s||e===ue.LOADED_META_DATA&&!r&&!s||(e===ue.LOADED_DATA&&!r&&!s&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,bt(this.rotation)&&([r,s]=[s,r]),this.emit("first-video-frame",{width:r,height:s,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};M([ye([],J.INIT,{sync:!0})],no.prototype,"close",1);var XT=Object.prototype.hasOwnProperty,{toString:Db}=Object.prototype;function zT(o){if(o==null)return!0;if(typeof o=="boolean")return!1;if(typeof o=="number")return o===0;if(typeof o=="string"||typeof o=="function"||Array.isArray(o))return o.length===0;if(o instanceof Error)return o.message==="";if(dt(o))switch(Object.prototype.toString.call(o)){case"[object File]":case"[object Map]":case"[object Set]":return o.size===0;case"[object Object]":{for(let i in o)if(XT.call(o,i))return!1;return!0}}return!1}var fi=zT;var QT=function(o){return p(this,null,function*(){let i=ZT(o);R.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],r=["label","deviceId","groupId"];if(i.audio&&(e=yield It(),R.info(`microphones: ${_t(e.map(s=>L(O({},s),{groupId:s.groupId.substring(0,8)})),{keysToInclude:r})}`)),i.video&&(t=yield At(),R.info(`cameras: ${_t(t,{keysToInclude:r})}`),!he(i.video)&&i.video.facingMode==="user"&&!i.video.deviceId)){let n=t.filter(a=>!a.label.includes("infrared")).find(a=>a.label.includes("facing front"));n&&(i.video.deviceId=n.deviceId,R.info(`exclude infrared camera: ${JSON.stringify(i)}`))}try{let s=yield navigator.mediaDevices.getUserMedia(i);return cu&&s.getTracks().forEach(n=>{var c;let a=n.getCapabilities();R.info(`${n.kind} capabilities: ${_t(a,{keysToInclude:Ia})}`),!T(o.echoCancellation)&&((c=a.echoCancellation)==null?void 0:c.indexOf(o.echoCancellation))===-1&&R.warn(`Invalid argument for 'echoCancellation'. Expected one of [${JSON.stringify(a.echoCancellation)}], but received '${o.echoCancellation}'`)}),i.audio&&vr(),s}catch(s){let{message:n}=s;throw s.name==="NotFoundError"&&(o.video&&t&&t.length===0&&(n=H({key:F.CAMERA_NOT_FOUND})),o.audio&&e&&e.length===0&&(n=H({key:F.MICROPHONE_NOT_FOUND}))),new D({code:I.INITIALIZE_FAILED,name:s.name,message:n,constraint:s.constraint})}})},YT=Ai({retryFunction:QT,settings:{retries:3,timeout:500},onError:({error:o,retry:i,reject:e,retryFuncArgs:t,retriedCount:r})=>{let s=r+1;o.name==="NotReadableError"||o.name==="OverconstrainedError"||o.name==="AbortError"?(s===1?(t[0].video&&(t[0].maxResolution=!1,(!Re||t[0].width*t[0].height<=1920*1080)&&t[0].frameRate&&(t[0].frameRate=t[0].frameRate>10?10:5)),t[0].retryWhenExactFailed&&t[0].useExactDeviceId&&(t[0].useExactDeviceId=!1)):s===2?t[0].useDeviceIdOnly=!0:s===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(o),t[0].microphoneId&&sf(t[0].microphoneId,!1),t[0].cameraId&&sf(t[0].cameraId,!0)},onRetrying:o=>{R.warn(`getUserMedia NotReadableError observed, retrying [${o}/3]`)},onRetryFailed:o=>{se.logFailedEvent({eventType:Ze.GET_USER_MEDIA_RETRY,error:o})},onRetrySuccess:o=>{se.logSuccessEvent({eventType:Ze.GET_USER_MEDIA_RETRY}),se.uploadEvent({log:`stat-${Ze.GET_USER_MEDIA_RETRY}-success-${o}`})}});function sf(o,i){return p(this,null,function*(){let t=(i?yield At():yield It()).find(r=>r.deviceId===o);t&&le(t.getCapabilities)&&R.warn(_t(t.getCapabilities(),{keysToInclude:Ia}))})}function ZT(o){return{audio:KT(o),video:eE(o)}}function KT(o){if(!o.audio)return!1;if(o.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:o.sampleRate};return!fi(o.microphoneId)&&(i.deviceId=o.useExactDeviceId?{exact:o.microphoneId}:o.microphoneId,o.useDeviceIdOnly)?i:(z(o.channelCount)&&(i.channelCount=o.channelCount),(he(o.echoCancellation)||o.echoCancellation==="remote-only"||o.echoCancellation==="all")&&(i.echoCancellation=o.echoCancellation),he(o.noiseSuppression)&&!o.noiseSuppression&&(i.noiseSuppression=!1),he(o.autoGainControl)&&!o.autoGainControl&&(i.autoGainControl=!1),fi(i)?!0:i)}function eE(o){if(!o.video)return!1;if(o.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=o,e={};return o.cameraId?e.deviceId=o.useExactDeviceId?{exact:o.cameraId}:o.cameraId:o.facingMode&&(e.facingMode=o.facingMode),o.useDeviceIdOnly&&!fi(e)?e:(o.width&&(e.width={ideal:o.width},i&&!K&&(e.width.max=o.width)),o.height&&(e.height={ideal:o.height},i&&!K&&(e.height.max=o.height)),K&&ri&&o.width&&o.height&&o.width*o.height<352*288&&(e.width=o.width,e.height=o.height),o.frameRate&&(e.frameRate=o.frameRate),fi(e)?!0:e)}var nf=YT;function Mc(o){return Q((i,e)=>function(...t){return p(this,null,function*(){return yield o.apply(this,t),i.apply(this,t)})})}function Ct(o){return Q((i,e)=>function(...t){return p(this,null,function*(){let r=yield i.apply(this,t);return yield o.call(this,...t),r})})}function Oc(o){return Q((i,e)=>function(...t){return p(this,null,function*(){try{return yield i.apply(this,t)}catch(r){o.call(this,r)}})})}function Q(o){return function(i,e,t){return t.value=o(t.value,e),t}}var af=(()=>{let o=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&R.info(`visibility change: ${document.visibilityState}`),!o&&(document.addEventListener("visibilitychange",()=>{R.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),o=!0)}})();var tE=0,kc=class{constructor(){d(this,"log",R.createLogger({id:`fq${++tE}`}));d(this,"isRunning",!1);d(this,"queue",[])}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(i,e=!1){var s,n;let t=O({},i),r=new Promise((a,c)=>{t.resolve=a,t.reject=c});return t.promise=r,e?this.length<=1?this.queue.push(t):(n=(s=this.lastQueueItem)==null?void 0:s.promise)==null||n.then(t.resolve,t.reject):this.queue.push(t),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),r}shift(){let i=this.queue.shift();return this.log.debug(`shift ${this.length}`),i}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:i,args:e,context:t,resolve:r,reject:s}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(r,s).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},Pc=new WeakMap,wc=new WeakMap;function ir(o=!1){return function(i,e,t){let r=t.value;return t.value=function(...s){let n=Pc.get(this)||new kc;return Pc.set(this,n),n.push({fn:r,args:s,context:this},o)},t}}function Lc(o){return function(i,e,t){let r=t.value;return t.value=function(...s){var a,c,l;let n=[];return(c=(a=Pc.get(this))==null?void 0:a.queue)==null||c.forEach(u=>n.push(u)),(l=wc.get(this))==null||l.forEach(u=>u==null?void 0:u.queue.forEach(m=>n.push(m))),n.forEach(u=>{u.reject(new D({code:I.API_CALL_ABORTED,message:o}))}),Pc.delete(this),wc.delete(this),r.apply(this,s)},t}}function _i(o){return function(i,e,t){let r=t.value,s=n=>o(...n);return t.value=function(...n){let a=wc.get(this)||new Map,c=a.get(s(n))||new kc;return a.set(s(n),c),wc.set(this,a),c.push({fn:r,args:n,context:this})},t}}function Rt(o,i){return Q((e,t)=>function(...r){let s=o;try{let n=e.apply(this,r),a=U();return Tr(n)?n.then(c=>(i?v.addSuccessEvent({key:s,cost:U()-a}):v.addSuccessEvent({key:s}),c)).catch(c=>{throw v.addFailedEvent({key:s,error:c}),c}):(v.addSuccessEvent({key:s}),n)}catch(n){throw v.addFailedEvent({key:s,error:n}),n}})}var gh={};Vi(gh,{Events:()=>Oe,Inspect:()=>Ht,LastSink:()=>ao,Sink:()=>j,Subscribe:()=>co,TimeoutError:()=>wn,audit:()=>VE,bindCallback:()=>CE,bindNodeCallback:()=>RE,buffer:()=>lE,bufferCount:()=>dE,bufferTime:()=>rS,call:()=>cf,catchError:()=>ph,combineLatest:()=>lf,concat:()=>oE,concatMap:()=>zE,concatMapTo:()=>QE,count:()=>vE,create:()=>ae,debounce:()=>FE,debounceTime:()=>BE,defer:()=>uf,delay:()=>oS,deliver:()=>X,dispose:()=>xc,elementAt:()=>HE,empty:()=>Vn,every:()=>JE,exhaustMap:()=>KE,exhaustMapTo:()=>eS,expand:()=>sS,filter:()=>$t,find:()=>$E,findIndex:()=>WE,first:()=>GE,fromAnimationFrame:()=>IE,fromArray:()=>fE,fromEvent:()=>ce,fromEventPattern:()=>_E,fromFetch:()=>gE,fromIterable:()=>TE,fromPromise:()=>pf,fromReadableStream:()=>SE,fromReader:()=>EE,groupBy:()=>tS,identity:()=>iE,ignoreElements:()=>OE,iif:()=>nE,inspect:()=>df,interval:()=>Vu,last:()=>qE,map:()=>Fn,mapTo:()=>XE,max:()=>NE,merge:()=>Ln,mergeMap:()=>YE,mergeMapTo:()=>ZE,min:()=>DE,never:()=>yE,nothing:()=>pe,of:()=>pE,pairwise:()=>jE,pipe:()=>de,race:()=>xu,range:()=>AE,reduce:()=>Fu,retry:()=>dS,scan:()=>mh,setAsapScheduler:()=>mE,share:()=>rr,shareReplay:()=>sE,skip:()=>PE,skipUntil:()=>wE,skipWhile:()=>Hc,startWith:()=>xn,subject:()=>ot,subscribe:()=>Te,sum:()=>ME,switchMap:()=>Mr,switchMapTo:()=>mo,take:()=>or,takeLast:()=>kE,takeUntil:()=>ke,takeWhile:()=>ff,tap:()=>Bn,throttle:()=>xE,throwError:()=>bE,timeInterval:()=>iS,timeout:()=>cS,timer:()=>Un,toPromise:()=>nS,toReadableStream:()=>aS,withLatestFrom:()=>cE,zip:()=>aE});function pe(...o){}var cf=o=>o(),iE=o=>o;function xc(){this.dispose()}var df=()=>typeof __FASTRX_DEVTOOLS__!="undefined",rE=1,Ht=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new ku(i,this,this.streamId++);return Oe.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},ao=class{constructor(){this.defers=new Set,this.disposed=!1}next(i){}complete(){this.dispose()}error(i){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=pe,this.error=pe,this.next=pe,this.dispose=pe,this.subscribe=pe,this.doDefer()}subscribe(i){return i instanceof Ht?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(cf),this.defers.clear()}defer(i){this.defers.add(i)}removeDefer(i){this.defers.delete(i)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},j=class extends ao{constructor(i){super(),this.sink=i,i.defer(this.bindDispose)}next(i){this.sink.next(i)}complete(){this.sink.complete()}error(i){this.sink.error(i)}},co=class extends ao{constructor(i,e=pe,t=pe,r=pe){if(super(),this._next=e,this._error=t,this._complete=r,this.then=pe,i instanceof Ht){let s={toString:()=>"subscribe",id:0,source:i};this.defer(()=>{Oe.defer(s,0)}),Oe.create(s),Oe.pipe(s),this.sourceId=s.id,this.subscribe(i),Oe.subscribe({id:s.id,end:!0}),e==pe?this._next=n=>Oe.next(s,0,n):this.next=n=>{Oe.next(s,0,n),e(n)},r==pe?this._complete=()=>Oe.complete(s,0):this.complete=()=>{this.dispose(),Oe.complete(s,0),r()},t==pe?this._error=n=>Oe.complete(s,0,n):this.error=n=>{this.dispose(),Oe.complete(s,0,n),t(n)}}else this.subscribe(i)}next(i){this._next(i)}complete(){this.dispose(),this._complete()}error(i){this.dispose(),this._error(i)}};function de(o,...i){return i.reduce((e,t)=>t(e),o)}function ae(o,i,e){if(df()){let t=Object.defineProperties(Object.setPrototypeOf(o,Ht.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:i,writable:!0,configurable:!0},args:{value:e,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});Oe.create(t);for(let r=0;r<e.length;r++){let s=e[r];typeof s=="function"&&s instanceof Ht&&Oe.addSource(t,s)}return t}return o}function X(o,i){return function(...e){return t=>{if(t instanceof Ht){let r=ae(s=>{let n=new o(s,...e);n.sourceId=r.id,n.subscribe(t)},i,arguments);return r.source=t,Oe.pipe(r),r}else return r=>t(new o(r,...e))}}}function Dr(o,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:o,payload:i}})}var ku=class extends j{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{Oe.defer(this.source,this.id)})}next(i){Oe.next(this.source,this.id,i),this.sink.next(i)}complete(){Oe.complete(this.source,this.id),this.sink.complete()}error(i){Oe.complete(this.source,this.id,i),this.sink.error(i)}},Oe={addSource(o,i){Dr("addSource",{id:o.id,name:o.toString(),source:{id:i.id,name:i.toString()}})},next(o,i,e){Dr("next",{id:o.id,streamId:i,data:e&&e.toString()})},subscribe({id:o,end:i},e){Dr("subscribe",{id:o,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(o,i,e){Dr("complete",{id:o.id,streamId:i,err:e?e.toString():null})},defer(o,i){Dr("defer",{id:o.id,streamId:i})},pipe(o){Dr("pipe",{name:o.toString(),id:o.id,source:{id:o.source.id,name:o.source.toString()}})},update(o){Dr("update",{id:o.id,name:o.toString()})},create(o){o.id||(o.id=rE++),Dr("create",{name:o.toString(),id:o.id})}},wn=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var Uc=class extends ao{constructor(i){super(),this.source=i,this.sinks=new Set}add(i){i.defer(()=>this.remove(i)),this.sinks.add(i).size===1&&(this.reset(),this.subscribe(this.source))}remove(i){this.sinks.delete(i),this.sinks.size===0&&this.dispose()}next(i){this.sinks.forEach(e=>e.next(i))}complete(){this.sinks.forEach(i=>i.complete()),this.sinks.clear()}error(i){this.sinks.forEach(e=>e.error(i)),this.sinks.clear()}};function rr(){return o=>{let i=new Uc(o);if(o instanceof Ht){let e=ae(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=o,Oe.pipe(e),e}return ae(i.add.bind(i),"share",arguments)}}function Ln(...o){return ae(i=>{let e=new j(i),t=o.length;e.complete=()=>{--t===0&&i.complete()},o.forEach(e.bindSubscribe)},"merge",arguments)}function xu(...o){return ae(i=>{let e=new Map;o.forEach(t=>{let r=new j(i);e.set(t,r),r.complete=()=>{e.delete(t),e.size===0?i.complete():r.dispose()},r.next=s=>{e.delete(t),e.forEach(n=>n.dispose()),r.resetNext(),r.resetComplete(),r.next(s)}}),o.forEach(t=>e.get(t).subscribe(t))},"race",arguments)}function oE(...o){return ae(i=>{let e=0,t=o.length,r=new j(i);r.complete=()=>{e<t&&!r.disposed?(r.doDefer(),r.subscribe(o[e++])):i.complete()},r.complete()},"concat",arguments)}function sE(o){return i=>{let e=new Uc(i),t=[];return e.next=function(r){t.push(r),t.length>o&&t.shift(),this.sinks.forEach(s=>s.next(r))},ae(r=>{r.defer(()=>e.remove(r)),t.forEach(s=>r.next(s)),e.add(r)},"shareReplay",arguments)}}function nE(o,i,e){return ae(t=>o()?i(t):e(t),"iif",arguments)}function lf(...o){return ae(i=>{let e=o.length,t=e,r=e,s=new Array(e),n=()=>{--r===0&&i.complete()},a=(c,l)=>{let u=new j(i);u.next=m=>{t--,u.next=h=>{s[l]=h,t===0&&i.next(s)},u.next(m)},u.complete=n,u.subscribe(c)};o.forEach(a)},"combineLatest",arguments)}function aE(...o){return ae(i=>{let e=o.length,t=e,r=new Array(e),s=()=>{--t===0&&i.complete()},n=(a,c)=>{let l=new j(i),u=[];r[c]=u,l.next=m=>{u.push(m),r.every(h=>h.length)&&i.next(r.map(h=>h.shift()))},l.complete=s,l.subscribe(a)};o.forEach(n)},"zip",arguments)}function xn(...o){return i=>ae((e,t=0,r=o.length)=>{for(;t<r&&!e.disposed;)e.next(o[t++]);e.disposed||e.subscribe(i)},"startWith",arguments)}var Pu=class extends j{constructor(i,...e){super(i);let t=new j(this.sink);t.next=r=>this.buffer=r,t.complete=pe,t.subscribe(lf(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},cE=X(Pu,"withLatestFrom"),wu=class extends j{constructor(i,e,t){super(i),this.bufferSize=e,this.startBufferEvery=t,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(i){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(i)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(i),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(i=>this.sink.next(i)),super.complete()}},dE=X(wu,"bufferCount"),Lu=class extends j{constructor(i,e){super(i),this.buffer=[];let t=new j(i);t.next=r=>{i.next(this.buffer),this.buffer=[]},t.complete=pe,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},lE=X(Lu,"buffer");var uE=function(o,i,e,t){function r(s){return s instanceof e?s:new e(function(n){n(s)})}return new(e||(e=Promise))(function(s,n){function a(u){try{l(t.next(u))}catch(m){n(m)}}function c(u){try{l(t.throw(u))}catch(m){n(m)}}function l(u){u.done?s(u.value):r(u.value).then(a,c)}l((t=t.apply(o,i||[])).next())})};function ot(o){let i=arguments,e=rr()(ae(t=>{e.next=r=>t.next(r),e.complete=()=>t.complete(),e.error=r=>t.error(r),o&&t.subscribe(o)},"subject",i));return e.next=pe,e.complete=pe,e.error=pe,e}function uf(o){return ae(i=>i.subscribe(o()),"defer",arguments)}var ms={promise:o=>{Promise.resolve().then(o)},setImmediate:typeof setImmediate!="undefined"?o=>setImmediate(o):null,setTimeout:o=>setTimeout(o,0)},hE=()=>typeof Promise!="undefined"?ms.promise:ms.setImmediate?ms.setImmediate:ms.setTimeout,Uu=hE(),hf=o=>i=>{Uu(()=>o(i))},mE=o=>{typeof o=="function"?Uu=o:ms[o]&&(Uu=ms[o])};var mf=o=>hf(i=>{for(let e=0;!i.disposed&&e<o.length;e++)i.next(o[e]);i.complete()});function pE(...o){return ae(mf(o),"of",arguments)}function fE(o){return ae(mf(o),"fromArray",arguments)}function Vu(o){return ae(i=>{let e=0,t=setInterval(()=>i.next(e++),o);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}function Un(o,i){return ae(e=>{let t=0,r=setTimeout(()=>{if(e.removeDefer(s),e.next(t++),i){let n=setInterval(()=>e.next(t++),i);e.defer(()=>{clearInterval(n)})}else e.complete()},o),s=()=>clearTimeout(r);e.defer(s)},"timer",arguments)}function Vc(o,i){return e=>{let t=r=>e.next(r);e.defer(()=>i(t)),o(t)}}function _E(o,i){return ae(Vc(o,i),"fromEventPattern",arguments)}function ce(o,i){if("on"in o&&"off"in o)return ae(Vc(e=>o.on(i,e),e=>o.off(i,e)),"fromEvent",arguments);if("addListener"in o&&"removeListener"in o)return ae(Vc(e=>o.addListener(i,e),e=>o.removeListener(i,e)),"fromEvent",arguments);if("addEventListener"in o)return ae(Vc(e=>o.addEventListener(i,e),e=>o.removeEventListener(i,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function pf(o){return ae(i=>{o.then(i.next.bind(i),i.error.bind(i))},"fromPromise",arguments)}function gE(o,i){return ae(uf(()=>pf(fetch(o,i))),"fromFetch",arguments)}function TE(o){return ae(hf(i=>{try{for(let e of o){if(i.disposed)return;i.next(e)}i.complete()}catch(e){i.error(e)}}),"fromIterable",arguments)}function EE(o){let i=e=>uE(this,void 0,void 0,function*(){if(e.disposed)return;let{done:t,value:r}=yield o.read();if(t){e.complete();return}else e.next(r),i(e)});return ae(e=>{i(e)},"fromReader",arguments)}function SE(o){return ae(i=>{let e=new AbortController,t=e.signal;i.defer(()=>e.abort("cancelled")),o.pipeTo(new WritableStream({write(r){i.next(r)},close(){i.complete()},abort(r){i.error(r)}}),{signal:t}).then(()=>i.complete(),r=>i.error(r))},"fromReadableStream",arguments)}function IE(){return ae(o=>{let i=requestAnimationFrame(function e(t){o.disposed||(o.next(t),i=requestAnimationFrame(e))});o.defer(()=>cancelAnimationFrame(i))},"fromAnimationFrame",arguments)}function AE(o,i){return ae((e,t=o,r=i+o)=>{for(;t<r&&!e.disposed;)e.next(t++);return e.complete(),"range"},"range",arguments)}function CE(o,i,...e){return ae(t=>{let r=e.concat(s=>(t.next(s),t.complete()));o.apply(i,r)},"bindCallback",arguments)}function RE(o,i,...e){return ae(t=>{let r=e.concat((s,n)=>s?t.error(s):(t.next(n),t.complete()));o.apply(i,r)},"bindNodeCallback",arguments)}function yE(){return ae(()=>{},"never",arguments)}function bE(o){return ae(i=>i.error(o),"throwError",arguments)}function Vn(){return ae(o=>o.complete(),"empty",arguments)}var lo=class extends j{constructor(i,e,t){super(i),this.f=e;let r=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=s=>{this.acc=s,this.complete=r,this.resetNext()}:(this.acc=t,this.complete=r)}next(i){this.acc=this.f(this.acc,i)}},Fu=X(lo,"reduce"),vE=o=>X(lo,"count")((i,e)=>o(e)?i+1:i,0),NE=()=>X(lo,"max")(Math.max),DE=()=>X(lo,"min")(Math.min),ME=()=>X(lo,"sum")((o,i)=>o+i,0);var Bu=class extends j{constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},$t=X(Bu,"filter"),Hu=class extends j{next(i){}},OE=X(Hu,"ignoreElements"),$u=class extends j{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&(this.doDefer(),this.complete())}},or=X($u,"take"),Wu=class extends j{constructor(i,e){super(i);let t=new j(i);t.next=()=>{t.doDefer(),i.complete()},t.complete=xc,t.subscribe(e)}},ke=X(Wu,"takeUntil"),Gu=class extends j{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):(this.doDefer(),this.complete())}},ff=X(Gu,"takeWhile"),kE=o=>Fu((i,e)=>(i.push(e),i.length>o&&i.shift(),i),[]),qu=class extends j{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},PE=X(qu,"skip"),Ju=class extends j{constructor(i,e){super(i),i.next=pe;let t=new j(i);t.next=()=>{t.doDefer(),i.resetNext()},t.complete=xc,t.subscribe(e)}},wE=X(Ju,"skipUntil"),ju=class extends j{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},Hc=X(ju,"skipWhile"),LE={leading:!0,trailing:!1},Xu=class extends j{constructor(i,e,t){super(i),this.durationSelector=e,this.trailing=t}cacheValue(i){this.last=i,this.disposed&&this.throttle(i)}send(i){this.sink.next(i),this.throttle(i)}throttle(i){this.reset(),this.subscribe(this.durationSelector(i))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},Fc=class extends j{constructor(i,e,t=LE){super(i),this.durationSelector=e,this.config=t,this._throttle=new Xu(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(i){this._throttle.disposed&&this.config.leading?this._throttle.send(i):this._throttle.cacheValue(i)}complete(){this._throttle.throttle=pe,this._throttle.complete(),super.complete()}},xE=X(Fc,"throttle"),UE={leading:!1,trailing:!0},VE=o=>X(Fc,"audit")(o,UE),zu=class extends j{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Bc=class extends j{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new zu(this.sink),this._debounce.dispose()}next(i){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=i,this._debounce.subscribe(this.durationSelector(i))}complete(){this._debounce.complete(),super.complete()}},FE=X(Bc,"debounce"),BE=o=>X(Bc,"debounceTime")(i=>Un(o)),Qu=class extends j{constructor(i,e,t){super(i),this.count=e,this.defaultValue=t}next(i){this.count--===0&&(this.defaultValue=i,this.doDefer(),this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("not enough elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},HE=X(Qu,"elementAt"),$E=o=>i=>or(1)(Hc(e=>!o(e))(i)),Yu=class extends j{constructor(i,e){super(i),this.f=e,this.i=0}next(i){this.f(i)?(this.sink.next(this.i++),this.doDefer(),this.complete()):++this.i}},WE=X(Yu,"findIndex"),Zu=class extends j{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i,this.doDefer(),this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},GE=X(Zu,"first"),Ku=class extends j{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i)}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},qE=X(Ku,"last"),eh=class extends j{constructor(i,e){super(i),this.predicate=e,this.index=0}next(i){this.predicate(i,this.index++)?this.result=!0:(this.result=!1,this.doDefer(),this.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},JE=X(eh,"every");var th=class extends j{constructor(i,e,t){super(i),this.f=e,typeof t=="undefined"?this.next=r=>{this.acc=r,this.resetNext(),this.sink.next(this.acc)}:this.acc=t}next(i){this.sink.next(this.acc=this.f(this.acc,i))}},mh=X(th,"scan"),ih=class extends j{constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},jE=X(ih,"pairwise"),$c=class extends j{constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},Fn=X($c,"map"),XE=o=>X($c,"mapTo")(i=>o),uo=class extends j{constructor(i,e,t){super(i),this.data=e,this.context=t}next(i){let e=this.context.combineResults;e?this.sink.next(e(this.data,i)):this.sink.next(i)}tryComplete(){this.context.resetComplete(),this.dispose()}},ho=class o extends j{constructor(i,e,t){super(i),this.makeSource=e,this.combineResults=t,this.index=0}subInner(i,e){let t=this.currentSink=new e(this.sink,i,this);this.complete===o.prototype.complete&&(this.complete=this.tryComplete),t.complete=t.tryComplete,t.subscribe(this.makeSource(i,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},Wc=class extends uo{},Gc=class extends ho{next(i){this.subInner(i,Wc),this.next=e=>{this.currentSink.dispose(),this.subInner(e,Wc)}}},Mr=X(Gc,"switchMap");function Xc(o){return(i,e)=>o(()=>i,e)}var mo=Xc(X(Gc,"switchMapTo")),rh=class extends uo{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},qc=class extends ho{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(i){this.next2(i),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),rh),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},zE=X(qc,"concatMap"),QE=Xc(X(qc,"concatMapTo")),oh=class extends uo{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Jc=class extends ho{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,oh),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},YE=X(Jc,"mergeMap"),ZE=Xc(X(Jc,"mergeMapTo")),sh=class extends uo{dispose(){this.context.resetNext(),super.dispose()}},jc=class extends ho{next(i){this.next=pe,this.subInner(i,sh)}},KE=X(jc,"exhaustMap"),eS=Xc(X(jc,"exhaustMapTo")),nh=class extends j{constructor(i,e){super(i),this.f=e,this.groups=new Map}next(i){let e=this.f(i),t=this.groups.get(e);typeof t=="undefined"&&(t=ot(),t.key=e,this.groups.set(e,t),super.next(t)),t.next(i)}complete(){this.groups.forEach(i=>i.complete()),super.complete()}error(i){this.groups.forEach(e=>e.error(i)),super.error(i)}},tS=X(nh,"groupBy"),ah=class extends j{constructor(){super(...arguments),this.start=new Date}next(i){this.sink.next({value:i,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},iS=X(ah,"timeInterval"),ch=class extends j{constructor(i,e){super(i),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(i){this.buffer.push(i)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},rS=X(ch,"bufferTime"),dh=class extends j{constructor(i,e){super(i),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(i){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:t,data:r}=e;super.next(r),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(t))}},i)}next(i){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:i})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},oS=X(dh,"delay"),lh=class extends j{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},ph=X(lh,"catchError"),uh=class extends uo{tryComplete(){let i=this.context.inners.delete(this);super.dispose(),i&&this.context.checkComplete()}next(i){this.sink.next(i),this.context.expandValue(i)}},hh=class extends ho{constructor(i,e){super(i,e),this.project=e,this.inners=new Set,this.sourceCompleted=!1}next(i){this.sink.next(i),this.expandValue(i)}expandValue(i){let e=new uh(this.sink,i,this);this.currentSink=e,this.complete=this.tryComplete,e.complete=e.tryComplete,this.inners.add(e),e.subscribe(this.makeSource(i,this.index++))}complete(){this.sourceCompleted=!0,this.checkComplete()}checkComplete(){this.sourceCompleted&&this.inners.size===0&&(this.resetComplete(),super.complete())}tryComplete(){this.sourceCompleted=!0,this.checkComplete()}},sS=X(hh,"expand");var nS=()=>o=>new Promise((i,e)=>{let t;new co(o,r=>t=r,e,()=>i(t))}),aS=()=>o=>{let i;return new ReadableStream({start(e){i=new co(o,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){i.dispose()}})},Te=(o=pe,i=pe,e=pe)=>t=>new co(t,o,i,e),fh=class extends j{constructor(i,e){super(i),e instanceof Function?this.next=t=>{e(t),i.next(t)}:(e.next&&(this.next=t=>{e.next(t),i.next(t)}),e.complete&&(this.complete=()=>{e.complete(),i.complete()}),e.error&&(this.error=t=>{e.error(t),i.error(t)}))}},Bn=X(fh,"tap"),_h=class extends j{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new wn(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},cS=X(_h,"timeout"),dS=(o=1/0)=>i=>{if(i instanceof Ht){let e=ae(t=>{let r=o,s=new j(t);s.error=n=>{r-- >0?s.subscribe(i):t.error(n)},s.sourceId=e.id,s.subscribe(i)},"retry",[o]);return e.source=i,Oe.pipe(e),e}else return e=>{let t=o,r=new j(e);r.error=s=>{t-- >0?i(r):e.error(s)},i(r)}};var ps=(e=>(e[e.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",e[e.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",e))(ps||{}),po=class po extends no{constructor(e,t){super({mediaType:e,PlayerClass:t});d(this,"isRemote",!1);d(this,"deviceId");d(this,"groupId","");d(this,"label","");d(this,"sourceTrack");d(this,"enableAutoSwitchWhenRecapturing",!0);d(this,"_isRecapturing",!1);d(this,"_lastRecaptureTime",0);d(this,"_onMuteTimeoutId",-1);d(this,"_encodeCheckTimeoutId",-1);d(this,"recaptureMode",0);d(this,"profile");d(this,"retryEncodeFailed")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}get isUseCustomSource(){return this.sourceTrack&&this.mediaTrack&&this.sourceTrack!==this.mediaTrack}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){e.addEventListener(f.MUTE,this.onTrackMuted),e.addEventListener(f.UNMUTE,this.onTrackUnmuted),e.addEventListener(f.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===f.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){e.removeEventListener(f.MUTE,this.onTrackMuted),e.removeEventListener(f.UNMUTE,this.onTrackUnmuted),e.removeEventListener(f.ENDED,this.onTrackEnded)}setStateToReady(){}capture(e,t=!1){return p(this,null,function*(){var s;let r=this.sourceTrack;try{let n=U();S.emit(C.LOCAL_TRACK_CAPTURE_START,{track:this});let a;e.customSource?(a=new MediaStream,a.addTrack(e.customSource)):(t||(s=this.sourceTrack)==null||s.stop(),a=yield nf(e));let c=a.getTracks()[0];return yield this.setInputMediaStreamTrack(c),e.customSource||(this.sourceTrack=c,this.updateDeviceIdInUse(),this.listenDeviceChange()),S.emit(C.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:U()-n}),a}catch(n){throw S.emit(C.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:n}),this.log.error(`getUserMedia error observed ${n}`),n}finally{t&&(r==null||r.stop())}})}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),this.isPublishing||this.isPublished)return(t=this.room)==null?void 0:t.replaceTrack(this)}get hasFlag(){var t,r;let e=Kt(((t=this.room)==null?void 0:t.localPublishFlag)||0,((r=this.room)==null?void 0:r.userId)||"");return this.mediaType===4&&e.hasVideo||this.mediaType===1&&e.hasAudio||this.mediaType===2&&e.hasAuxiliary}publish(e,t){return p(this,null,function*(){return this.room=e,this.room.localTracks.add(this),this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.bindParent(e.getLogger()),yield t,this._checkPublishFlag(e)})}_checkPublishFlag(e){return new Promise((t,r)=>p(this,null,function*(){var l,u,m,h;let s=()=>r(new D({code:I.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?t():((this.state===J.INIT||this.state==="ready")&&s(),de(ce(e,"local-publish-flag-changed"),$t(()=>this.hasFlag),ke(Ln(ce(this,J.INIT),ce(this,"ready"))),Te(t,r,s))),(((u=(l=this.room)==null?void 0:l.networkQuality)==null?void 0:u.uplinkNetworkQuality)||0)>3)return t();let a=e.heartbeatCount,c=((h=(m=this.mediaTrack)==null?void 0:m.stats)==null?void 0:h.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout(()=>p(this,null,function*(){var g,E,A,k,re,P,Qe;if((((E=(g=this.room)==null?void 0:g.networkQuality)==null?void 0:E.uplinkNetworkQuality)||0)>3||e.heartbeatCount-a<3)return t();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if((A=this.mediaTrack)!=null&&A.stats){let te=this.mediaTrack.stats.totalFrames||0;te-c===0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",te)}let N=this.kind===f.AUDIO,b=this.stat.bytesSent>0;if(v[b?"addSuccessEvent":"addFailedEvent"]({key:N?503700:513702}),!N){let te=((re=(k=this.room)==null?void 0:k.videoCodec)==null?void 0:re.toUpperCase())||"H264",ve={H264:513704,H265:513705,VP8:513706}[te];ve&&v[b?"addSuccessEvent":"addFailedEvent"]({key:ve})}if(!b){if(v.addEnum({key:N?503701:513703,value:Zr()}),se.uploadEvent({log:`stat-encode-failed-${this.kind}-${si()||ni()}`,userId:this.userId}),this.log.warn(N?"encode failed":`${(Qe=(P=this.room)==null?void 0:P.videoCodec)==null?void 0:Qe.toUpperCase()} encode failed`),this.retryEncodeFailed&&(this.log.warn("retry encode"),yield this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(yield Ke(5e3),this.stat.bytesSent>0||this.hasFlag)))return t();this.emit("6",this),r(new D({message:`${this.strMediaType} encode failed`,code:N?I.AUDIO_ENCODE_FAILED:I.VIDEO_ENCODE_FAILED}))}}}),1e4)}))}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),S.emit(C.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return p(this,null,function*(){if(this.sourceTrack&&yi){let{deviceId:e,groupId:t}=this.sourceTrack.getSettings(),{label:r}=this.sourceTrack;(yield of({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=r,t&&(this.groupId=t),ds().then(n=>{let a=n.find(c=>{let l=c.deviceId===e;return t&&(l=l&&c.groupId===t),l});a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.sourceTrack||this.kind===f.AUDIO&&!rf(this.sourceTrack)||this.kind===f.VIDEO&&!tf(this.sourceTrack)||this._isRecapturing||e&&ri&&Re)}onTrackMuted(){if(super.onTrackMuted(),af(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<ko){setTimeout(()=>this.onTrackMuted(),ko);return}this._onMuteTimeoutId=setTimeout(()=>p(this,null,function*(){var e;if((e=this.sourceTrack)!=null&&e.muted){if((ge||_e)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return p(this,null,function*(){if(Pe(po.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()&&this.recaptureMode===0){if(Date.now()-this._lastRecaptureTime<ko){setTimeout(()=>this.onTrackEnded(),ko);return}this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e,t=!1){return p(this,null,function*(){var n;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");let r=this.sourceTrack;t||(n=this.sourceTrack)==null||n.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let s={useExactDeviceId:!0};if(e==="user"||e==="environment")s.facingMode=e;else{let a;(this.kind==="audio"?yield It():yield At()).find(l=>l.deviceId===e)&&(a=e),s.deviceId=a}return this.capture(s,t).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),S.emit(C.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(a=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${a.message}`),this.emit("5",a),S.emit(C.LOCAL_TRACK_RECAPTURE,{track:this,error:a})}).finally(()=>{t&&(r==null||r.stop())})})}getRecoverCaptureDeviceId(){return p(this,null,function*(){let e=this instanceof je;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let r=(Hn.get(t)||0)+1;if(Hn.set(t,r),r>=3&&this.enableAutoSwitchWhenRecapturing){let s=e?(yield At()).find(n=>!Hn.has(n.deviceId)):(yield It()).find(n=>!Hn.has(n.deviceId));s&&(this.log.warn(`${t} capture fail ${r} times, change new ${s.deviceId}`),t=s.deviceId)}}return t})}stopCapture(){var e;this.sourceTrack&&(this.sourceTrack.stop(),this.uninstallTrackEvent(this.sourceTrack)),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack),(e=this.manager)==null||e.removeInput(this)}close(){super.close(),this.stopCapture()}};M([ye(J.INIT,"ready",{ignoreError:!0,sync:!0})],po.prototype,"setStateToReady",1),M([ir()],po.prototype,"capture",1),M([ye("ready","publish",{ignoreError:!0,success(){S.emit(C.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this.log.info("published")},fail(e){var n;(n=this.room)==null||n.localTracks.delete(this);let t="error",r=e instanceof D?e:e.cause instanceof D?e.cause:e,s=!1;r instanceof D&&(r.message.includes("timeout")?t="timeout":r.code===I.API_CALL_ABORTED&&(s=!0,t="api-call")),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:r}),this.log[s?"info":"error"]("publish failed",r)}}),Rt(521714,!1)],po.prototype,"publish",1),M([Q(e=>function(){return p(this,null,function*(){let t=this.state==="publish"?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),ye([],"ready",{sync:!0})],po.prototype,"unpublish",1);var pi=po,Hn=new Map;S.on(C.SWITCH_DEVICE_SUCCESS,o=>{o.track.deviceId&&Hn.delete(o.track.deviceId)});var kt=class o extends pi{constructor(e){super(1,Dc);d(this,"mediaType",1);d(this,"volume",0);d(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});d(this,"playerMuted",!0);d(this,"pipeline");d(this,"earMonitorGainNode",new xe);d(this,"_output",new xe);d(this,"codecPipeline",[]);d(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});d(this,"mixedAudioReferenceMap",new Map);d(this,"isAudioContextLongSuspended",!1);d(this,"after3aSilenceStartTime",0);this.manager=e,this.pipeline=new cs(e),this.pipeline.source.pipeTo(this.player.pipeline.volumeMeter),this.pipeline.gain.pipeTo(this.earMonitorGainNode).pipeTo(this._output),this.pipeline.gain.pipeTo(this.player.pipeline.volumeMeterAfter3A),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this),S.on(C.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this)}get dbVolume(){return so.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}getInternalAudioLevelAfter3A(){if(this.pipeline.aec.node||this.pipeline.denoiser.node)return this.player.getInternalAudioLevelAfter3A()}updateAfter3aSilenceStartTime(e){T(e)||(e===0&&!this.after3aSilenceStartTime?this.after3aSilenceStartTime=U():e>0&&(this.after3aSilenceStartTime=0))}setInputMediaStreamTrack(e){return p(this,null,function*(){let t=this.trackSettings||{};v.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),v.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),v.addEnum({key:502700,value:0});let{sampleRate:r,channelCount:s}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:r,channelCount:s})}`),this.pipeline.source.channelCount=s||1,this.pipeline.replaceSource(e),yield Pe(o.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture(a){return p(this,arguments,function*({deviceId:e,customSource:t,useExactDeviceId:r=!0,retryWhenExactFailed:s},n=!1){let c=yield Pe(o.prototype,this,"capture").call(this,{video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:r,retryWhenExactFailed:s,customSource:t},n);return vr(),c})}switchDevice(e){return p(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e&&!this.isUseCustomSource)if(e===Wr){if(yield Mu(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.sourceTrack&&this.sourceTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),S.emit(C.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(t){throw this.log.error(`switch microphone failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}}})}listenDeviceChange(){be&&!be.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&be.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return p(this,null,function*(){if(e.deviceId===this.deviceId){let t=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${ps[this.recaptureMode]}. Current microphone is lost: ${JSON.stringify(e)}`),this.recaptureMode===0){Ne(this.userId,{eventId:2003,param1:6,streamType:1});let r=yield It();r[0]?this.recapture(r[0].deviceId):t=!0}t&&be.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.recaptureMode===1&&e.deviceId!==this.deviceId||(be.off("audioInputAdded",this.handleMicrophoneAdded,this),this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId))}update3A(s){return p(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:r}){let n=this.sourceTrack||this.mediaTrack;if(!n)return;let a=n.getConstraints(),c=!1;!T(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,a.echoCancellation=e,c=!0),!T(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,a.noiseSuppression=t,c=!0),!T(r)&&r!==this.profile.autoGainControl&&(this.profile.autoGainControl=r,a.autoGainControl=r,c=!0),c&&(K||Re?yield n.applyConstraints(a).catch(l=>this._log.warn("update3A failed: ",l)):this.deviceId&&(yield this.recapture(this.deviceId,!0)))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&v.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),ge&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(Ee().createGain()),this._output.setNode(Ee().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this.sourceTrack&&!(Re||ge))return this.update3A({echoCancellation:e})}addDenoiser(e){var t;if(qe<=92&&((t=this.trackSettings)==null?void 0:t.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}v.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.enableTrackANS(!1)}mixAudioReference(e,t){if(this.mixedAudioReferenceMap.has(t))return;this.log.info(`mixAudioReference() => ${t}`);let r=On(e);if(!r)return;let s=new xe,n=Ee().createGain();n.gain.value=1;let a=new xe;s.pipeTo(a).pipeTo(this.pipeline.mixNode),s.setNode(r),a.setNode(n),this.mixedAudioReferenceMap.set(t,[s,a])}unMixAudioReference(e){let[t,r]=this.mixedAudioReferenceMap.get(e)||[];t&&(this.log.info(`unMixAudioReference() => ${e}`),t.deleteNode(),r==null||r.deleteNode(),this.mixedAudioReferenceMap.delete(e))}setAudioReferenceVolume(e,t){let[r,s]=this.mixedAudioReferenceMap.get(e)||[];s!=null&&s.node&&(s.node.gain.value=t/100,this.log.info(`setAudioReferenceVolume() => ${e} ${s.node.gain.value}`))}addAudioProcessor(e,t,r){this.pipeline.silentNode.setNode(r),this.pipeline.mixNode.setNode(t),this.pipeline.aec.setNode(e)}removeDenoiser(e){if(this.pipeline.denoiser.node===e)return this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0)}removeAudioProcessor(e){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode())}close(){this.mixedAudioReferenceMap.forEach(([e,t])=>{e.deleteNode(),t.deleteNode()}),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),be.off("audioInputAdded",this.handleMicrophoneAdded,this),be.off("audioInputRemoved",this.handleMicrophoneRemoved,this),S.off(C.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this),super.close()}recapture(e,t=!1){return p(this,null,function*(){try{yield Pe(o.prototype,this,"recapture").call(this,e,t)}catch(r){let s=(yield It()).find(n=>n.deviceId!==e);if(s)yield Pe(o.prototype,this,"recapture").call(this,s.deviceId);else throw r}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((t,r)=>r?r({frame:t,ntp:Fi()}):t,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}get enableEncryptFrame(){return this.manager&&!!this.manager.encodePipeline[0]}handleAudioContextLongSuspended({isSuspended:e}){if(this.pipeline.isProcessEnabled)if(e){this.isAudioContextLongSuspended=!0,this.log.warn(`context has suspended for ${vu/1e3} seconds, change to source audio${Ft?"":", non-Safari"}`);let t=this.sourceTrack||this.mediaTrack;t&&this.setOutputMediaStreamTrack(t)}else this.isAudioContextLongSuspended=!1,this.log.warn("context has resumed, change to processed audio"),this.pipeline.track&&this.setOutputMediaStreamTrack(this.pipeline.track)}setOutputMediaStreamTrack(e){if(this.isAudioContextLongSuspended){let t=this.sourceTrack||this.mediaTrack;t&&(e=t)}super.setOutputMediaStreamTrack(e)}};function zc(o,i=!1){let e=new DataView(o),t=[],r=0;for(;r<e.byteLength;){let s=0;if(r+4<=e.byteLength&&e.getUint8(r)===0&&e.getUint8(r+1)===0&&e.getUint8(r+2)===0&&e.getUint8(r+3)===1)s=4;else if(r+3<=e.byteLength&&e.getUint8(r)===0&&e.getUint8(r+1)===0&&e.getUint8(r+2)===1)s=3;else{r+=1;continue}let n=-1;for(let m=r+s;m<e.byteLength;m+=1){if(m+4<=e.byteLength&&e.getUint8(m)===0&&e.getUint8(m+1)===0&&e.getUint8(m+2)===0&&e.getUint8(m+3)===1){n=m;break}if(m+3<=e.byteLength&&e.getUint8(m)===0&&e.getUint8(m+1)===0&&e.getUint8(m+2)===1){n=m;break}}let a=n===-1?e.byteLength:n,c=a-r,l=new ArrayBuffer(c),u=new DataView(l);for(let m=0;m<c;m+=1)u.setUint8(m,e.getUint8(r+m));t.push(new sr(u,i)),r=a}return t}var sr=class{constructor(i,e=!1){this.dataView=i;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let{seiPayloadStartIndex:i}=this,e=this.dataView.byteLength-2,t=[],r=0;for(let n=i;n<=e;n++){let a=this.dataView.getInt8(n);switch(a){case 0:case 1:case 2:case 3:r===2&&(t.push(3),r=0),a===0?r+=1:r=0,t.push(a);break;default:r=0,t.push(a);break}}t.push(this.dataView.getInt8(this.dataView.byteLength-1));let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=s}removePreventionByte(){let{seiPayloadStartIndex:i}=this,e=this.dataView.byteLength-1,t=[],r=0;for(let n=i;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:r++,t.push(this.dataView.getInt8(n));break;case 3:r!==2&&t.push(this.dataView.getInt8(n)),r=0;break;default:t.push(this.dataView.getInt8(n)),r=0;break}let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=s}get seiPayloadStartIndex(){let i=6;for(let e=6;e<this.dataView.buffer.byteLength&&(i+=1,this.dataView.getUint8(e)===255);e+=1);return i}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let i=0,e=6;for(let n=6;n<this.dataView.buffer.byteLength;n+=1){let a=this.dataView.getUint8(n);if(e+=1,a===255)i+=255;else{i+=a;break}}let t=new ArrayBuffer(i),r=new DataView(t),s=e;for(let n=0;n<t.byteLength;n+=1)r.setInt8(n,this.dataView.getInt8(s+n));return r}get naluType(){let i=this.getStartCodeLength();return i>=this.dataView.byteLength?0:this.dataView.getUint8(i)&31}getStartCodeLength(){return this.dataView.byteLength>=4&&this.dataView.getUint8(0)===0&&this.dataView.getUint8(1)===0&&this.dataView.getUint8(2)===0&&this.dataView.getUint8(3)===1?4:this.dataView.byteLength>=3&&this.dataView.getUint8(0)===0&&this.dataView.getUint8(1)===0&&this.dataView.getUint8(2)===1?3:0}get isIDR(){return this.naluType===5}get isSPS(){return this.naluType===7}get isPPS(){return this.naluType===8}get isSEI(){return this.naluType===6}};var Qc=class{constructor(){d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_seiPayloadType",243)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,s=[];s.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)s.push(255);s.push(r);let n=new DataView(i);return s.push(...new Uint8Array(n.buffer)),s.push(128),new sr(new DataView(new Uint8Array(s).buffer),!0)}sendSEI(i,e){e!=null&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(i),e!=null&&e.small&&this._smallSeiMessageList.push(i)}isEmpty(){return!this._seiMessageList.length}getNaluCount(i){let e=0,t=0,r=new DataView(i);for(let s=0;s<i.byteLength;s++)switch(r.getUint8(s)){case 0:e++;break;case 1:(e===2||e===3)&&t++,e=0;break;default:e=0;break}return t}encode(i,e){let t=e?this._smallSeiMessageList:this._seiMessageList;if(t.length>0&&i.data.byteLength>0){let s=9-this.getNaluCount(i.data);if(s<=0)return 0;let n=t.splice(0,s).reverse().map(this.encodeSEINalu.bind(this)),a=n.reduce((h,_)=>h+_.dataView.byteLength,0),c=new ArrayBuffer(a+i.data.byteLength),l=new DataView(c),u=new DataView(i.data),m=0;for(let h=0;h<n.length;h++)for(let _=0;_<n[h].dataView.byteLength;_++)l.setInt8(m++,n[h].dataView.getInt8(_));for(let h=0;h<i.data.byteLength;h++)l.setInt8(m++,u.getInt8(h));return i.data=c,n.length}return 0}};var Or=class Or extends pi{constructor(e,t=4){super(t,it);d(this,"profile",O({},pr));d(this,"avoidCropping",!1);d(this,"_scaleResolutionDownBy");d(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0,framesCaptured:0});d(this,"small");d(this,"isNeedToSetBandwidth");d(this,"muteImage");d(this,"manager");d(this,"_seiCodec",new Qc);this.manager=e;let r=()=>{var s;if(this.isAllowed2k4k(this.profile))this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1});else{let n=Ut(((s=this.room)==null?void 0:s.sdkAppId)||0)?ha:ua;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${n}`),this.setProfile(L(O({},this.profile),{width:1920,height:1080})),this.applyProfile()}};this.on("input-media-track-changed",r),this.on("publish",r),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!yi||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get contentHint(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)||""}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}get hasSmall(){var e;return!!((e=this.manager)!=null&&e.hasSmall)}setMute(e){return p(this,null,function*(){var t,r,s;if(ie(e)){if(this.muteImage===e)return;yield(t=this.manager)==null?void 0:t.deleteWatermark("mute"),yield(r=this.manager)==null?void 0:r.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e,fillVideo:!0}),this.muteImage=e,Pe(Or.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield(s=this.manager)==null?void 0:s.deleteWatermark("mute"),this.muteImage=void 0),Pe(Or.prototype,this,"setMute").call(this,e)})}capture(a){return p(this,arguments,function*({deviceId:e,facingMode:t,useExactDeviceId:r=!0,customSource:s,retryWhenExactFailed:n=!0}){let c={audio:!1,video:!0,facingMode:t||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:r,retryWhenExactFailed:n,customSource:s};if(c.facingMode==="environment"){let l=yield this.getDeviceIdWhenUsingBackCamera();l&&(c.cameraId=l)}return Pe(Or.prototype,this,"capture").call(this,c)})}setProfile(e){var r;let t=this.fallbackProfile(e);if(t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile))super.setProfile(t);else{let s=Ut(((r=this.room)==null?void 0:r.sdkAppId)||0)?ha:ua;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${s}`),super.setProfile(L(O({},this.profile),{width:1920,height:1080}))}}applyProfile(){return p(this,null,function*(){var a;if(!this.mediaTrack)return;let{width:e=0,height:t=0}=(this.sourceTrack||this.mediaTrack).getSettings(),r=e*t,s=this.settings,n=s.height!==this.profile.height||s.width!==this.profile.width||s.frameRate!==this.profile.frameRate;if(n&&(et===16&&this.deviceId?yield this.recapture(this.deviceId):(yield(a=this.sourceTrack||this.mediaTrack)==null?void 0:a.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1})),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth){this.isNeedToSetBandwidth=!1;let{width:c=0,height:l=0}=(this.sourceTrack||this.mediaTrack).getSettings(),u=c*l;if(n&&u&&r&&u===r){this.log.warn("set bandwidth failed: resolution is not changed");return}return this.room.setBandWidth({bandwidth:this.profile.bitrate,type:f.VIDEO,videoType:f.BIG})}})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},t=this.sourceTrack||this.mediaTrack;return yi&&t&&Object.assign(e,t.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:Ho(this.settings,this.profile)}isAllowed2k4k(e){var t;return!this.room||!this.room.scheduleResult||this.isScreen||e.height*e.width<2560*1440?!0:((t=this.room.scheduleResult.trtcAutoConf)==null?void 0:t["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return p(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e)&&!this.isUseCustomSource)return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.sourceTrack&&this.sourceTrack.stop(),yield this.capture(t),S.emit(C.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(t){throw this.log.error(`switch camera failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}})}getDeviceIdWhenUsingBackCamera(){return p(this,null,function*(){let e;try{if(rn&&!Qo&&du){let r=(yield At(!0)).map(n=>{var a;return L(O({},n),{capabilities:(a=n.getCapabilities)==null?void 0:a.call(n)})}).filter(n=>{var a,c;return(c=(a=n.capabilities)==null?void 0:a.facingMode)==null?void 0:c.includes("environment")}),s=r[0];r.forEach(n=>{var u,m,h,_;let{capabilities:a}=n,c=(u=a.width)!=null&&u.max&&((m=a.height)!=null&&m.max)?a.width.max*a.height.max:0,l=(h=s.capabilities.width)!=null&&h.max&&((_=s.capabilities.height)!=null&&_.max)?s.capabilities.width.max*s.capabilities.height.max:0;c>l&&(s=n)}),s!=null&&s.capabilities&&(this._log.info("use max resolution back camera",s),e=s.deviceId)}}catch(t){this._log.warn("get max res camera failed",t)}return e})}updateSmallConfig(e){var r,s;this._log.info(`update small stream config: ${JSON.stringify(e)}`);let t=!this.small;this.small=this.fallbackProfile(e,!0),(r=this.manager)==null||r.update(),t&&((s=this.room)==null||s.enableSmall(!0)),this.log.info("update small stream config success")}fallbackProfile(e,t=!1){let r=e.width>e.height,s=O({},e);return e.width*e.height<=160*120&&_e&&$e&&(this.log.warn(`${t?"small ":""}resolution is ${e.width}*${e.height}, fallback to 240*180 for android chrome`),s.width=r?240:180,s.height=r?180:240,s.bitrate=Math.max(e.bitrate,150)),e.width*e.height>1280*720&&Ol&&(s.width=r?1280:720,s.height=r?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),nn(Tt,"14.3")&&Dl(Tt,"14.0",!0)&&this.on("7",()=>{let n=this.profile.width>this.profile.height;this.profile.width*this.profile.height>640*480?(this.profile.width=n?640:480,this.profile.height=n?480:640,this.log.warn("reduce the resolution to 480p on iOS 14.0 ~ 14.2")):this.profile.width*this.profile.height>640*360&&(this.profile.width=n?640:360,this.profile.height=n?360:640,this.log.warn("reduce the resolution to 360p on iOS 14.0 ~ 14.2"))}),!t&&this.avoidCropping&&($e||K)&&!an()&&e.width*e.height<=640*360&&e.width/e.height===16/9&&(this._scaleResolutionDownBy=1280/e.width,e.width=1280,e.height=720,this.log.warn(`capture 720p, scale: ${this._scaleResolutionDownBy}`)),s}stopSmall(){var e,t;this.small&&(delete this.small,(e=this.manager)==null||e.update(),(t=this.room)==null||t.enableSmall(!1))}listenDeviceChange(){be&&!be.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&be.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return p(this,null,function*(){if(e.deviceId===this.deviceId){let t=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${ps[this.recaptureMode]}. Current camera is lost: ${JSON.stringify(e)}`),this.recaptureMode===0){Ne(this.userId,{eventId:2003,param1:7,streamType:2});let r=yield At();r[0]?this.recapture(r[0].deviceId):t=!0}t&&be.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return p(this,null,function*(){this.recaptureMode===1&&e.deviceId!==this.deviceId||(be.off("videoInputAdded",this.handleCameraAdded,this),this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId))})}encodeFrame(e,t){if(!this.manager)return e;let r=t?8:this.mediaType;return this.manager.encodePipeline.reduceRight((s,n)=>n?n({frame:s,mediaType:r}):s,e)}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}play(e,t){return T(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){be.off("videoInputAdded",this.handleCameraAdded,this),be.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return p(this,null,function*(){try{yield Pe(Or.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield At()).find(s=>s.deviceId!==e);if(r)yield Pe(Or.prototype,this,"recapture").call(this,r.deviceId);else throw t}})}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info(`setContentHint ${e}`),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}setRotation(e){this.manager&&(this.isScreen||T(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};M([Ct(function(e){this.setContentHint(e.contentHint||"motion")})],Or.prototype,"capture",1);var je=Or;var Eh={};Vi(Eh,{REPORT_TYPE:()=>$o,buildSSOPackage:()=>Gi,bytes2ms:()=>Mm,calculateScaleResolutionDownNumber:()=>Ho,concatArrayBuffers:()=>ka,convertObjectNumberToInt:()=>Js,copyProperties:()=>Dm,deepClone:()=>Gr,deepCloneBasic:()=>ya,deepMerge:()=>ei,delay:()=>Ke,fibonacci:()=>Jr,formatedTime:()=>Fm,getConstructorName:()=>xo,getContainerFromElement:()=>Vm,getEnv:()=>bm,getFirst16Bits:()=>Hm,getInternalVersion:()=>xm,getLast16Bits:()=>Pa,getLoggerUrl:()=>Wi,getMediaStreamTrackInfo:()=>Oa,getMuteStateFromFlag:()=>Kt,getNetworkType:()=>ba,getNumNetworkType:()=>qr,getReconnectionTimeout:()=>Zt,getStringByteLength:()=>qs,getTurnServer:()=>Um,getUint32Version:()=>Na,getValueType:()=>Me,getViewListFromView:()=>Fo,glog:()=>_l,ipv4ToUint32:()=>Vo,isArray:()=>Ie,isAudioWorkletSupported:()=>wm,isBoolean:()=>he,isConstructor:()=>jr,isEmpty:()=>Uo,isFunction:()=>le,isLangChinese:()=>Yt,isMediaStreamTrack:()=>km,isNumber:()=>z,isObject:()=>yt,isOverseaSdkAppId:()=>Ut,isPlainObject:()=>dt,isPortrait:()=>gl,isPromise:()=>Tr,isRemoteTrack:()=>Pm,isRotate90Or270:()=>bt,isSetSinkIdSupported:()=>Lm,isString:()=>ie,isUndefined:()=>T,loadImage:()=>Bo,loadVideo:()=>Bm,ms2bytes:()=>Om,ms2samples:()=>fl,normalizeUrl:()=>Ma,performanceNow:()=>U,promiseAny:()=>Xr,samples2ms:()=>pl,setNetworkTypeFromWebRTC:()=>va,stringify:()=>_t,stringifyIncludeValue:()=>Gs,throttlePromise:()=>Da});var hS=[-1,-1,1,-1,-1,1,1,1],mS=[0,0,1,0,0,1,1,1];var kr=class kr extends J{constructor(e,t){super();this.context=e;d(this,"name");d(this,"input");d(this,"output");d(this,"texture");d(this,"ctx2d",null);d(this,"fbo");d(this,"width",0);d(this,"height",0);d(this,"x",0);d(this,"y",0);d(this,"program");d(this,"vertexShader");d(this,"fragmentShader");d(this,"totalFrames",0);d(this,"dropFrames",0);d(this,"matchInputSize",!0);d(this,"texCoordBuffer");d(this,"positionBuffer");d(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});d(this,"cost",0);d(this,"_canvas",null);d(this,"_image");d(this,"log");if(this.context.on("disconnect",this.close,this),this.name=t.name,this.log=t.logger,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof Xe){e.ctx&&t.create2d&&(typeof OffscreenCanvas=="function"&&et!==16?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);return}try{let r=e.ctx;this.texCoordBuffer=this.createBuffer(mS),this.positionBuffer=this.createBuffer(hS),t.createTexture!==!1&&(this.texture=r.createTexture(),this.useTexture(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.pixelStorei(r.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=r.createFramebuffer(),this.useBufferFrame(),this.useTexture(),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,this.width,this.height,0,r.RGBA,r.UNSIGNED_BYTE,null),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(r.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(r.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(r){this.context.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${r.message||r}`}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,r=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),r}connect(e,...t){return e.addInput(this,...t),this.output=e,e}addInput(e,...t){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();if(this.context instanceof Be&&this.render(e)||this.context instanceof Xe&&this.render2d(e))this.totalFrames++;else return!1;return this.cost=Date.now()-t,!0}render2d(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?this.draw2d(this.input.image,0,0,this.width,this.height):!1}update(e=0){var t;(t=this.output)==null||t.update(e)}disconnect(...e){var t;(t=this.output)==null||t.removeInput(this,...e),delete this.output}removeInput(e,...t){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),(e=this.output)==null||e.removeInput(this),delete this.output,(t=this.input)==null||t.disconnect(),this.context instanceof Be){let r=this.context.ctx;r.deleteBuffer(this.texCoordBuffer),r.deleteBuffer(this.positionBuffer),this.fbo&&r.deleteFramebuffer(this.fbo),this.texture&&r.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&r.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&r.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&r.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let t=this.context.ctx;e.forEach((r,s)=>{r&&(t.activeTexture(t.TEXTURE0+s),t.bindTexture(t.TEXTURE_2D,r))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,r=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,r),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),r}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,e),r.bufferData(r.ARRAY_BUFFER,new Float32Array(t),r.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((r,s)=>{t.enableVertexAttribArray(s),t.bindBuffer(t.ARRAY_BUFFER,r),t.vertexAttribPointer(s,2,t.FLOAT,!1,0,0)})}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(!(this.width===e&&this.height===t)){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let r=this.context.ctx;r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e,t,0,r.RGBA,r.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let r=this.context.ctx;r.drawArrays(r.TRIANGLE_STRIP,0,4)}draw2d(e,t,r,s,n,a,c,l,u){let m=!T(a)&&!T(c)&&!T(l)&&!T(u);return this.ctx2d&&e?(e instanceof ImageData?(m?this.ctx2d.putImageData(e,t,r,a,c,l,u):this.ctx2d.putImageData(e,t,r),this.emit(kr.RENDER,this.ctx2d.canvas)):(m?this.ctx2d.drawImage(e,a,c,l,u,t,r,s,n):this.ctx2d.drawImage(e,t,r,s,n),this.emit(kr.RENDER,e)),typeof VideoFrame!="undefined"&&e instanceof VideoFrame&&e.close(),!0):!1}drawBackGround2d(e){this.ctx2d&&(this.ctx2d.save(),this.ctx2d.fillStyle=e,this.ctx2d.fillRect(0,0,this.width,this.height),this.ctx2d.restore())}getInfo(){var m;let{totalFrames:e,x:t,y:r,width:s,height:n,name:a,cost:c}=this,l=Date.now(),u=(e-this.lastInfo.totalFrames)/((l-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:s,height:n,timestamp:l,fps:u,name:a,cost:c},O({parent:(m=this.input)==null?void 0:m.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,r=t.createTexture();return this.useTextures(r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),r}};d(kr,"RENDER","render"),M([ye(J.INIT,"connected",{sync:!0})],kr.prototype,"connect",1),M([ye("connected",J.INIT,{ignoreError:!0,sync:!0})],kr.prototype,"disconnect",1),M([ye([],"closed",{sync:!0})],kr.prototype,"close",1);var Ue=kr;var pS=de(Vu(250),Fn(()=>performance.now()),rr());var _f=o=>i=>{let e=performance.now();de(pS,Hc(t=>t-e<o),or(1))(i)};var _S=[0,1,1,1,0,0,1,0],fo=class extends Ue{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));d(this,"_intervalId",0);d(this,"_sequence",0);d(this,"checkGLError",!1);d(this,"checkVisibilityChange");e instanceof Xe?this.ctx2d=e.ctx||null:e.available&&(t!=null&&t.mirrorUpAndDown)&&this.setTexBuffer(_S)}start(e){this.log.info(`${this.name} start render ${e} fps`),oe.clearTask(this._intervalId),this._intervalId=oe.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(oe.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof Be){let r=this.context.ctx.getError();r&&this.context.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${r}`}))}},{fps:this.context.frameRate})}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),this.emit(Ue.RENDER,this.context._canvas),!0):!1}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}update(e=0){this.state!=="closed"&&(this._intervalId&&(oe.clearTask(this._intervalId),this._intervalId=0,e===1&&(this.log.info(`${this.name} use requestVideoFrameCallback`),this.checkVisibilityChange=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",this.checkVisibilityChange))},document.addEventListener("visibilitychange",this.checkVisibilityChange))),this.requestFrame(this._sequence++))}removeInput(e){super.removeInput(e),oe.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),oe.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},fs=class extends fo{constructor(e,t){super(e,t);d(this,"_videoTrack");d(this,"_muteOb");d(this,"_closedOb",ce(this,"closed"));d(this,"_subscription");d(this,"_canvasContainer");Number(Xi)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e.canvas.captureStream().getVideoTracks(),this._muteOb=ce(this._videoTrack,"mute"),de(ce(this._videoTrack,"ended"),ke(this._closedOb),Te(()=>{this.context.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=de(this._muteOb,ke(this._closedOb),mo(_f(5e3)),$t(()=>{var e;return!!((e=this._videoTrack)!=null&&e.muted)&&!document.hidden}),Te(()=>{this.context.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var e;(e=this._subscription)==null||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info(`${this.name} put canvas to body`),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,t;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack,(t=this._canvasContainer)==null||t.remove()}},Yc=class extends fs{render(i){var t;let e=!!((t=this.input)!=null&&t.requestFrame(i));if(this.context._canvas2d){let r=this.context._canvas2d.getContext("2d");r.clearRect(0,0,this.context._canvas2d.width,this.context._canvas2d.height),r.drawImage(this.context._canvas,0,0,this.context._canvas2d.width,this.context._canvas2d.height)}return e}};var Zc=class extends fs{constructor(e,t,r){super(e,{name:"smallDestination",logger:r});this.resolution=t}resize(e,t){let r,s=e*t,n=this.resolution.width*this.resolution.height;this.log.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),s>n?r=s/n:(this.log.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${t} small: ${this.resolution.width} * ${this.resolution.height}`),r=s/(160*120)),super.resize(e/Math.sqrt(r),t/Math.sqrt(r))}};var $n=class extends Ue{constructor(e,t){super(e,O({name:"imageSource"},t));d(this,"_lastImage");d(this,"_totalFrames",0);d(this,"_autoResize",!1);d(this,"_canvasRendered");d(this,"videoCallbackId",0);d(this,"waitingFirstFrame",!0);d(this,"shouldUpdate",!0);this._autoResize=(t==null?void 0:t.autoResize)!==!1,et===16&&(this._canvasRendered=ot(),de(this._canvasRendered,xn(this._image),Mr(r=>r instanceof HTMLCanvasElement?ce(r,"rendered"):Vn()),ke(ce(this,"closed")),Te(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let e=this.image;this.videoCallbackId&&e.cancelVideoFrameCallback(this.videoCallbackId),Ki()&&!document.hidden&&(this.videoCallbackId=e.requestVideoFrameCallback((t,r)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=r.presentedFrames,this.update(1))}))}_render(e,t){var a;let{width:r,height:s}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:r,videoHeight:s}=n,!r||!s)return!1;n.width=r,n.height=s}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if({width:r,height:s}=n,n!==this._lastImage)this._lastImage=n;else if(r===this.width&&s===this.height)return!0}else n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas?({width:r,height:s}=n,this._lastImage=n):typeof VideoFrame!="undefined"&&n instanceof VideoFrame&&({displayWidth:r,displayHeight:s}=n,(a=this._lastImage)==null||a.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===r&&this.height===s&&this.totalFrames){if(t){this.useTexture();let c=this.context.ctx;c.texSubImage2D(c.TEXTURE_2D,0,0,0,c.RGBA,c.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();let c=this.context.ctx;c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,n)}this.resize(r,s)}return!0}get image(){return this._image}set image(e){var t;(t=this._canvasRendered)==null||t.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},Wn=class extends $n{constructor(e,t,r){super(e,r);this._player=t;this.name="videoPlayerSource",de(ce(this._player,ue.PLAYER_STATE_CHANGED),ke(ce(this,"closed")),$t(({state:s})=>s==="PLAYING"),Te(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},Wt=class extends Wn{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(i,e,t){super(i,new it({id:t.name,track:e,muted:!0,container:null,objectFit:"contain",log:t.logger}),t),this.name="videoTrackSource",this._player.play()}replaceTrack(i){this.waitingFirstFrame=!0,this._player.setTrack(i),this._player.play()}close(){super.close(),this._player.stop()}},Kc=class extends Ue{constructor(e,t,r){super(e,L(O({name:"textSource"},r),{create2d:!0}));d(this,"hasChange",!0);d(this,"content","");this.ctx2d.textBaseline="top",this.content=t.content||"",t.font&&(this.font=t.font),t.color&&(this.color=t.color)}set font(e){this.ctx2d&&(this.ctx2d.font=e,this.hasChange=!0)}get font(){var e;return((e=this.ctx2d)==null?void 0:e.font)||""}set color(e){this.ctx2d&&(this.ctx2d.fillStyle=e,this.hasChange=!0)}get color(){var e;return((e=this.ctx2d)==null?void 0:e.fillStyle)||""}render2d(e){return this.ctx2d&&this.hasChange?(this.ctx2d.clearRect(0,0,this.width,this.height),this.drawMultilineText(0,0),this.hasChange=!1,!0):!1}render(e){return!1}resize(e,t){if(!this.ctx2d)return;let{color:r,font:s}=this;super.resize(e,t),this.color=r,this.font=s}drawMultilineText(e=0,t=0,r=1.2){if(!this.ctx2d)return;let s=this.ctx2d.measureText(this.content);t+=s.fontBoundingBoxAscent||s.actualBoundingBoxAscent||0;let n=this.font.match(/(\d+)px/),c=(n?parseInt(n[1],10):16)*r,l=this.content.split(`
|
|
33
|
+
`,t.onclick=this.onQuestionClick.bind(this);let r=document.createElement("div");r.className=Su,r.innerText=`${Yt()?"\u8BE6\u60C5 >":"Detail >"}`,r.onclick=this.onCollapseClick.bind(this);let s=i.content.firstChild,n=s.querySelector(`.${Ac}`);return n.appendChild(r),n.appendChild(t),n.appendChild(e),s}addDiaLog(){br()||(Iu=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${bn}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",R.info("show autoplay dialog"),se.uploadEvent({log:$T}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,Iu=!1)}onConfirm(){R.warn("confirm clicked, try resume stream"),S.emit(C.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDialog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${Up}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||se.uploadEvent({log:WT}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Hp,"_blank"),this._isQuestionClicked||se.uploadEvent({log:GT}),this._isQuestionClicked=!0}},vn=null;function ns(){vn||(vn=new Au)}function $p(){vn&&(vn.deleteDialog(),vn=null)}var it=class o extends mi{constructor(e){super(e,f.VIDEO);d(this,"stat",{});d(this,"_calculateTimeout",-1);d(this,"viewMirror",!1);d(this,"objectFit","cover");d(this,"container");d(this,"canvas");d(this,"shouldRenderAlpha",!1);d(this,"_preSize",{width:0,height:0});d(this,"posterImg");d(this,"_originContainerPosition");this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,T(e.viewMirror)||(this.viewMirror=e.viewMirror),T(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}get isPlaying(){var e;return this._state!=="PLAYING"||this.element&&this.element.paused?!1:((e=this.track)==null?void 0:e.readyState)==="live"&&!this.track.muted}initializeElement(){var t;let e=document.createElement(f.VIDEO);this.track&&this.mode!==2&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,_e&&(e.poster="noposter"),(t=this.container)==null||t.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}get styleAttribute(){let e=`width:100%;height:100%;object-fit:${this.objectFit};${this.shouldRenderAlpha?"":"background-color:black"};`;return this.viewMirror&&(e+="transform:scaleX(-1);"),e}setContainer(e){var t;this.container=e,this.track&&this.elementToRender&&((t=this.container)==null||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(f.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(f.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(f.RESIZE,this.handleElementEvent)}handleTrackEvent(e){var t;return e.type===f.MUTE&&((t=this.stat)!=null&&t.fps)&&(this.stat.fps=0),super.handleTrackEvent(e)}handleElementEvent(e){var r,s,n,a,c,l;if(this.mode===2)return;super.handleElementEvent(e);let t=e.type;if(t===f.PAUSE&&(this.container&&!this.container.isConnected&&(this._log.warn(`${this.kind} player has been remove, element ID: ${this.container.id}`),Ke(500).then(()=>{var u;(u=this.container)!=null&&u.isConnected&&(this._pausedRetryCount=$r,this._log.info(`view container ${this.container.id} is in dom, reset pausedRetryCount`))})),this._pausedRetryCount>0&&!br()&&!this._isPausedByUserCall&&(this._log.info(`[${$r-this._pausedRetryCount+1}/${$r}] ${this.kind} player auto resume when paused`),this.doResume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let u=this.element.style.transform;t===f.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=u.replace("scaleX(-1)",""):t===f.LEAVE_PICTURE_IN_PICTURE&&!u.includes("scaleX")&&(this.element.style.transform=`${u} scaleX(-1)`)}t===f.RESIZE&&(this._preSize.height!==((r=this.element)==null?void 0:r.videoHeight)||this._preSize.width!==((s=this.element)==null?void 0:s.videoWidth))&&(this._log.info(`video size changed to ${(n=this.element)==null?void 0:n.videoWidth}x${(a=this.element)==null?void 0:a.videoHeight}`),this._preSize.height=((c=this.element)==null?void 0:c.videoHeight)||0,this._preSize.width=((l=this.element)==null?void 0:l.videoWidth)||0,this.emit(ue.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height}))}setCanvas(e,t=1){var r,s,n,a;this.canvas!==e&&((r=this.canvas)==null||r.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?t:0,this.mode===2&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?((s=this.element)==null||s.remove(),(n=this.container)==null||n.appendChild(e)):this.element&&((a=this.container)==null||a.appendChild(this.element)))}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width=`${e}px`,this.elementToRender.style.height=`${t}px`)}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit=`${e}`),this.objectFit=e}setPoster(e,t=!1){return new Promise(r=>{if(this.element)if(this._log.info("setPoster",e.slice(0,10)),this.element.poster=e,t&&(Re||K)){if(e==="")this.removePosterImg();else if(!this.posterImg){let s=document.createElement("img");s.src=e,s.style=`position:absolute;top:0;left:0;width:100%;height:auto;aspect-ratio:${this.element.videoWidth/this.element.videoHeight};max-height: 100%;`,s.onload=()=>p(this,null,function*(){var n;s.decode&&(yield s.decode()),this.container&&window.getComputedStyle(this.container).position==="static"&&(this._originContainerPosition=this.container.style.position,this.container.style.position="relative"),this.posterImg=s,(n=this.container)==null||n.appendChild(s),r()})}}else r()})}removePosterImg(){this.posterImg&&(this.posterImg.remove(),URL.revokeObjectURL(this.posterImg.src),this.container&&this._originContainerPosition&&this.container.style.position==="relative"&&(this.container.style.position=this._originContainerPosition),delete this.posterImg)}pause(e=!0){return p(this,null,function*(){return($e&&qe>=128||e&&(K||Re))&&(yield this.setPoster(this.getVideoFrame(),!0)),Pe(o.prototype,this,"pause").call(this)})}resume(e=!1){return this.posterImg&&this.setPoster("",!0),super.resume(e)}doResume(e=!1){return e&&this.element&&this.track&&$e&&qe>=128&&this.track.kind==="video"&&(this.element.srcObject=new MediaStream([this.track])),super.doResume()}stop(e=0){var t;super.stop(e),(t=this.canvas)==null||t.remove(),this.removePosterImg()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(ue.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(Ki()&&this.element&&this._calculateTimeout<0){let e=0,t=null,r=(s,n)=>{this.stat.width=n.width,this.stat.height=n.height,t&&(this.stat.fps=Math.round((n.presentedFrames-t.presentedFrames)/(s-e)*1e3)),e=s,t=n,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var a;return(a=this.element)==null?void 0:a.requestVideoFrameCallback(r)},2e3))};this.element.requestVideoFrameCallback(r)}}catch(e){this._log.warn("init stat failed",e)}}enterFullscreen(){return p(this,null,function*(){let e=this.elementToRender;if(!e)throw this._log.warn("no element to render, cannot enter fullscreen"),new Error("No element available for fullscreen");try{if(e.requestFullscreen)yield e.requestFullscreen();else if(e.webkitRequestFullscreen)yield e.webkitRequestFullscreen();else if(e.webkitEnterFullscreen)yield e.webkitEnterFullscreen();else if(e.mozRequestFullScreen)yield e.mozRequestFullScreen();else if(e.msRequestFullscreen)yield e.msRequestFullscreen();else throw this._log.warn("fullscreen API not supported"),new Error("Fullscreen API not supported");this._log.info("entered fullscreen mode")}catch(t){throw this._log.error("failed to enter fullscreen:",t),t}})}exitFullscreen(){return p(this,null,function*(){try{if(document.exitFullscreen)yield document.exitFullscreen();else if(document.webkitExitFullscreen)yield document.webkitExitFullscreen();else if(document.mozCancelFullScreen)yield document.mozCancelFullScreen();else if(document.msExitFullscreen)yield document.msExitFullscreen();else throw this._log.warn("exit fullscreen API not supported"),new Error("Exit fullscreen API not supported");this._log.info("exited fullscreen mode")}catch(e){throw this._log.error("failed to exit fullscreen:",e),e}})}isFullscreen(){let e=this.elementToRender;return e?(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)===e:!1}toggleFullscreen(){return p(this,null,function*(){this.isFullscreen()?yield this.exitFullscreen():yield this.enterFullscreen()})}enterPictureInPicture(){return p(this,null,function*(){if(!this.element)throw new Error("No video element available for picture-in-picture");if(this.canvas&&this.mode!==1)throw new Error("Picture-in-picture is not supported for canvas-only mode");let{element:e}=this;try{if(this._log.warn(!!e.requestPictureInPicture,!!e.webkitSetPresentationMode),e.requestPictureInPicture){this._log.info("requestPictureInPicture");let t=yield e.requestPictureInPicture();return this._log.info("entered picture-in-picture mode"),t}if(e.webkitSetPresentationMode)return this._log.info("webkitSetPresentationMode"),yield e.webkitSetPresentationMode("picture-in-picture"),this._log.info("entered picture-in-picture mode (webkit)"),{};throw new Error("Picture-in-picture API not supported")}catch(t){throw this._log.error("failed to enter picture-in-picture:",t.name,t.message),t}})}exitPictureInPicture(){return p(this,null,function*(){try{if(document.pictureInPictureElement&&document.exitPictureInPicture)yield document.exitPictureInPicture(),this._log.info("exited picture-in-picture mode");else if(this.element&&this.element.webkitSetPresentationMode)yield this.element.webkitSetPresentationMode("inline"),this._log.info("exited picture-in-picture mode (webkit)");else throw this._log.warn("exit picture-in-picture API not supported or not in PiP mode"),new Error("Exit picture-in-picture API not supported or not in PiP mode")}catch(e){throw this._log.error("failed to exit picture-in-picture:",e),e}})}isPictureInPicture(){if(!this.element)return!1;let{element:e}=this;return document.pictureInPictureElement?document.pictureInPictureElement===e:e.webkitPresentationMode?e.webkitPresentationMode==="picture-in-picture":!1}togglePictureInPicture(){return p(this,null,function*(){this.isPictureInPicture()?yield this.exitPictureInPicture():yield this.enterPictureInPicture()})}};function tr(o,i){return p(this,null,function*(){if(!o.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield o.audioWorklet.addModule(i),R.info("worklet addModule success")}catch(e){throw R.info(`worklet addModule catch error. ${e.message}`),e}})}var Nn;typeof AudioContext!="undefined"?Nn=AudioContext:typeof webkitAudioContext!="undefined"?Nn=webkitAudioContext:typeof mozAudioContext!="undefined"&&(Nn=mozAudioContext);var vu=1500,rt,Wp=-1,Rc=0,Dn=-1,bu=!1,Gp=0,qp=-1,Jp=-1;jp();function jp(){try{if(rt)return;rt=new Nn({sampleRate:48e3}),rt.onstatechange=()=>{R.info(`context state: ${rt.state}${rt.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),as()},clearTimeout(Wp)}catch(o){R.error(`initAudioContext failed: ${o} typeof AudioContextClass: ${typeof Nn}`),Wp=setTimeout(jp,1e3)}}var as=()=>{rt.state==="suspended"?(Rc=U(),JT(),vr(),document.addEventListener("click",as)):rt.state==="interrupted"?vr():(Rc&&(v.addNumber({key:507800,value:U()-Rc,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),Rc=0),jT(),document.removeEventListener("visibilitychange",as),document.removeEventListener("click",as))},Ru=0,yu=-1;function vr(){return new Promise((o,i)=>{if(rt.state==="running")return o();Date.now()-Ru<1e3?(clearTimeout(yu),yu=setTimeout(()=>{Ru=Date.now(),rt.resume().then(o,i)},1e3)):(clearTimeout(yu),Ru=Date.now(),rt.resume().then(o,i))}).catch(o=>{R.warn(`context resume failed: ${o}`),document.addEventListener("visibilitychange",as)})}document.addEventListener("click",as);function JT(){Dn===-1&&(Dn=setTimeout(()=>{rt.state==="suspended"&&(bu=!0,S.emit("155",{isSuspended:!0}))},vu))}function jT(){Dn!==-1&&(clearTimeout(Dn),Dn=-1,bu&&(bu=!1,S.emit("155",{isSuspended:!1})))}function Xp(){if(!ge||Jp!==-1)return;let o=()=>{U()-Gp<500||(rt&&rt.state==="running"&&rt.currentTime===qp&&(R.warn("context is fake running, auto resume"),rt.suspend().catch(i=>{R.warn(`context suspend failed: ${i}`)})),qp=rt.currentTime,Gp=U())};Jp=setInterval(()=>{o()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&o()})}var Ee=o=>rt;var xe=class{constructor(i){this.name=i;d(this,"node");d(this,"node2");d(this,"pre",new Set);d(this,"next",new Set);d(this,"context");d(this,"connectedNodes",new Set);d(this,"nextInputChannelMap",new Map);d(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(i){this._channelCount=i,this.setChannelCount(this.node,i),this.setChannelCount(this.node2,i),this.next.forEach(e=>e.channelCount=i)}setChannelCount(i,e){!i||i instanceof ScriptProcessorNode||(i.channelCountMode="explicit",i.channelCount=e||this.channelCount||1)}setContext(i){this.context=i,this.node&&i.addMixWeight()}removeContext(){var i;this.node&&((i=this.context)==null||i.reduceMixWeight()),delete this.context}replaceNode(i){var e;if(i!==this.node)try{this.node?this._disconnect():(e=this.context)==null||e.addMixWeight(),this.node=i,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(t){R.error(t)}}setNode(i,e){var t;if(!this.node)try{(t=this.context)==null||t.addMixWeight(),this.node=i,this.setChannelCount(this.node),e&&(this.node2=e,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),v.addSuccessEvent({key:502701})}catch(r){R.error(r),v.addFailedEvent({key:502701,error:r})}}deleteNode(){var i;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(i=this.context)==null||i.reduceMixWeight(),this.preNodeReconnect(),v.addSuccessEvent({key:502702})}catch(e){R.error(e),v.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(i=>{i.node?i.reconnect():i.preNodeReconnect()})}connectNext(i){this.next.forEach(e=>{let t=this.nextInputChannelMap.get(e);i._connect(e.node,t)||e.connectNext(i)})}_connect(i,e=0){return!this.node||!i?!1:((this.node2||this.node).connect(i,0,e),this.connectedNodes.add(i),!0)}_disconnect(){this.connectedNodes.forEach(i=>{var e;return(e=this.node2||this.node)==null?void 0:e.disconnect(i)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(i,e=0){return this.next.add(i),i.pre.add(this),this.nextInputChannelMap.set(i,e),i}},yc=class extends xe{constructor(e=256){super();this.fftSize=e;d(this,"dataArray",new Uint8Array(0))}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),t=1,r=0,s=0,n=`M${r},${s}`;for(let a=0;a<e.length;a++)s=e[a]/128*100/2,n+=`L${r},${s}`,r+=t;return n}},Mn=class{constructor(){d(this,"source",new xe);d(this,"gain",new xe);d(this,"destination",new xe)}get volume(){var i;return((i=this.gain.node)==null?void 0:i.gain.value)||1}setVolume(i){if(i===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(Ee().createGain()),this.gain.node.gain.value=i}replaceSource(i){let e=On(i);e&&this.source.replaceNode(e)}get track(){var i;return(i=this.stream)==null?void 0:i.getAudioTracks()[0]}get stream(){var i;return(i=this.destination.node)==null?void 0:i.stream}},cs=class extends Mn{constructor(e){super();this.context=e;d(this,"aec",new xe("aec"));d(this,"mixNode",new xe("mixNode"));d(this,"silentNode",new xe("silentNode"));d(this,"denoiser",new xe("denoiser"));d(this,"voiceChanger",new xe("voiceChanger"));this.source.pipeTo(this.aec).pipeTo(this.denoiser).pipeTo(this.voiceChanger).pipeTo(this.gain).pipeTo(this.destination),this.silentNode.pipeTo(this.mixNode).pipeTo(this.aec,1)}get isProcessEnabled(){return this.aec.node||this.denoiser.node||this.voiceChanger.node||this.gain.node}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.aec.setContext(this.context),this.silentNode.setContext(this.context),this.mixNode.setContext(this.context),this.denoiser.setContext(this.context),this.voiceChanger.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){this.context.inputs.has(this)&&(this.destination.deleteNode(),this.source.removeContext(),this.aec.removeContext(),this.silentNode.removeContext(),this.mixNode.removeContext(),this.denoiser.removeContext(),this.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.aec.deleteNode(),this.silentNode.deleteNode(),this.mixNode.deleteNode(),this.denoiser.deleteNode(),this.voiceChanger.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){if(e===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e}},bc=class{constructor(){d(this,"audioContext",Ee("audio-mixer"));d(this,"destination",this.audioContext.createMediaStreamDestination());d(this,"inputs",new Set);d(this,"mixWeight",0);this.destination.channelCount=1}addMixWeight(i=1){this.mixWeight+=i,this.mixWeight-1===i+1>>1&&this.mixOnChange()}reduceMixWeight(i=1){this.addMixWeight(-i)}close(){this.inputs.forEach(i=>i.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},zp=new WeakMap;function On(o){try{let i=zp.get(o);if(i)return i;let e=Ee();if(o instanceof HTMLAudioElement)i=e.createMediaElementSource(o);else if(o instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([o]));else return o;return zp.set(o,i),i}catch(i){if(K&&i instanceof Error&&i.name==="NotSupportedError")R.warn(i);else throw i}}var Ot=class Ot{constructor(i){d(this,"_volume",0);d(this,"_volumeDb",0);d(this,"_log");d(this,"_scriptProcessorNode",null);d(this,"_audioWorkletNode",null);d(this,"_interval",200);d(this,"ready",this.preload());let{log:e}=i;this._log=e,S.on(C.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-Ot.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!Ot.workletReady){let i='class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,s){t=t[0],s=s[0];if(t||s){if(this.isStop)return!1;var i=s&&s[0]?s[0].length:0,h=this.cache.length,a=(i<h?(s[0].set(this.cache.slice(0,i)),this.cache=this.cache.slice(i)):this.unmute&&s[0].set(t[0]),(i<h?s:t)[0]);if(a){let e=0;for(let t=0;t<a.length;++t)e=Math.max(Math.abs(a[t]),e);s=a.reduce((t,e)=>t+e*e,0)/a.length;this.volume=e,this.tick-=a.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,volumeDb:Math.max(10*Math.log10(s)+100,0)/100,cacheLen:h,outputLen:i}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';Ot.workletReady=tr(Ot.audioContext,URL.createObjectURL(new Blob([i],{type:"application/javascript"})))}return Ot.workletReady.then(()=>this.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Ot.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{Ot.lastMessageTime=Date.now(),this._volume=e.data.volume||0,this._volumeDb=e.data.volumeDb||0,!i&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),i=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(i){this._log.error(`volumeMeter init audio worklet error: ${i}`),se.logFailedEvent({userId:this._log.userId,eventType:Ze.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=Ee("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{Ot.lastMessageTime=Date.now();let e=i.inputBuffer.getChannelData(0),t=0;for(let r=0;r<e.length;++r)t+=e[r]*e[r];this._volume=Math.sqrt(t/e.length)||0}}catch(i){this._log.error(`volumeMeter init script processor error: ${i}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,S.off(C.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}getVolumeDb(){return Math.floor(this._volumeDb*100)}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}};d(Ot,"lastMessageTime",0),d(Ot,"audioContext",Ee("volume-meter")),d(Ot,"workletReady");var vc=Ot,kn=class extends xe{constructor(e){super();d(this,"_volumeMeter");this._volumeMeter=new vc(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return p(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}getVolumeDb(){return this._volumeMeter.getVolumeDb()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),r=new Float32Array(t>>2);e.copyTo(r,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:r},[r.buffer]),e.close()}}},so=vc;var Kp=Ge(at(),1);var Yp=o=>i=>i.deviceId===o;var Pn=class{constructor(i,e){d(this,"kind");d(this,"type");d(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(r=>r.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&ls(this.devices[0])){this.devices=t;return}e&&(t.forEach(r=>{if(r.deviceId&&!this.devices.find(Yp(r.deviceId))){let s=`${this.kind}${this.type}Added`;R.warn(`${s}: ${JSON.stringify(r)}`),e.emit(s,r)}}),this.devices.forEach(r=>{if(r.deviceId&&!t.find(Yp(r.deviceId))){let s=`${this.kind}${this.type}Removed`;R.warn(`${s}: ${JSON.stringify(r)}`),e.emit(s,r)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},Nu=class extends Kp.EventEmitter{constructor(){super();d(this,"audioInputs",new Pn(f.AUDIO,"Input"));d(this,"videoInputs",new Pn(f.VIDEO,"Input"));d(this,"audioOutputs",new Pn(f.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||oe.run("interval",()=>{this.update()},{delay:1e4}))}init(){ds().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return p(this,arguments,function*(e=0){let t=yield ds(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}hasBlueTooth(){var t;if(((t=Ee())==null?void 0:t.outputLatency)*1e3>150)return!0;let e=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some(r=>e.some(s=>r.label.toLowerCase().includes(s)))||this.audioInputs.devices.some(r=>e.some(s=>r.label.toLowerCase().includes(s)))}},be=xs||Do?null:new Nu;function ls(o){return o.deviceId===o.groupId&&o.groupId===""}function ds(){return p(this,arguments,function*(o=0){if(Zi()||!pc())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(o!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{ls(t)&&(t.kind===f.AUDIO_INPUT?e.audio=!0:t.kind===f.VIDEO_INPUT&&(e.video=!0))}),o===2&&(e.audio=!1),o===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e),e.audio&&vr()}catch(r){R.debug("capture before getDevices failed: ",r)}i=yield navigator.mediaDevices.enumerateDevices(),t==null||t.getTracks().forEach(r=>r.stop())}}return i.map((e,t)=>{let r={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${t}`};return e.deviceId.length>0&&Du.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(r.getCapabilities=()=>e.getCapabilities()),r})})}function It(o=!1){return be.update(o?1:0).then(i=>i.audioInputs.devices)}function At(o=!1){return be.update(o?2:0).then(i=>i.videoInputs.devices)}var Zp=!1;function ef(){return p(this,null,function*(){try{Zp||(Zp=!0,R.info(`speakers:${(yield Nr()).map(o=>` ${o.deviceId.slice(0,8)}: ${o.label}`)}`))}catch(o){}})}function Nr(o=!1){return p(this,null,function*(){return(ge||Re)&&(o=!1),be.update(o?1:0).then(i=>i.audioOutputs.devices)})}var Du=new Set;function tf(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let i=o.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let t=`${((o==null?void 0:o.getSettings())||{}).deviceId}_${f.VIDEO_INPUT}`;return!!Du.has(t)}function rf(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let i=o.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("\u9EA6\u514B\u98CE"))return!0;let t=`${((o==null?void 0:o.getSettings())||{}).deviceId}_${f.AUDIO_INPUT}`;return!!Du.has(t)}function Mu(o,i){return p(this,null,function*(){let t=(yield It()).find(r=>r.deviceId===Wr);return!i&&(t==null?void 0:t.groupId)===o||(t==null?void 0:t.groupId)===o&&t.label===i})}function of(s){return p(this,arguments,function*({newDeviceId:o,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:r}){return o!==i?!1:r===f.AUDIO&&o===Wr?yield Mu(e,t):!0})}var Nc,Ou=class extends Mn{constructor(e){super();this.log=e;d(this,"volumeMeter");d(this,"volumeMeterAfter3A");d(this,"volumeDestination");d(this,"analyser",new yc);this.volumeMeter=new kn({log:this.log}),this.volumeMeterAfter3A=new kn({log:this.log}),this.volumeDestination=new xe,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},us=class o extends mi{constructor(e){super(e,f.AUDIO);d(this,"_outputDeviceId");d(this,"_floatVolume",1);d(this,"_destination");d(this,"pipeline");d(this,"volumeMeterMode","worklet");d(this,"enableVolumeControlInIOS");this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this.mode=0,e.url&&(this.url=e.url),this.pipeline=new Ou(this._log)}setTrack(e){}get duration(){var e;return Math.floor((((e=this.element)==null?void 0:e.duration)||0)*1e3)}get currentTime(){var e;return Math.floor((((e=this.element)==null?void 0:e.currentTime)||0)*1e3)}set currentTime(e){this.element&&(this.element.currentTime=e/1e3)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((Tt==="15.2"||Tt==="15.3"||Tt==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let r=Nc||new Audio;r.setAttribute("autoplay","autoplay"),r.srcObject=this.getMediaStream(),r.muted=this.muted,this.url&&(r.crossOrigin="anonymous",r.src=this.url),this.element=r,this.setVolume(z(e)?e/100:this._floatVolume),r===Nc&&(Nc=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(ue.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}play(e){return p(this,null,function*(){if(!(!this.track&&!this.url))return!this.pipeline.source.node&&this.track&&this.pipeline.replaceSource(this.track),this.element||this.initializeElement(e==null?void 0:e.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?(this.pipeline.volumeMeter.init(),this.pipeline.volumeMeterAfter3A.init()):this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(Ee("player").createAnalyser()),ef(),Pe(o.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(e)}setVolume(e){this._floatVolume=e,this.element&&(this.element.volume=e)}setSinkId(e){return p(this,null,function*(){var t,r;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(r=(t=this.element).setSinkId)==null?void 0:r.call(t,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){this.element&&(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}getInternalAudioLevelAfter3A(){return this.pipeline.volumeMeterAfter3A.getInternalAudioLevel()}},Dc=class extends us{setTrack(i){this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(ue.MEDIA_TRACK_CHANGED,i),i&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([i]))))}},hs=class extends us{constructor(e){super(e);d(this,"_sourceElement");d(this,"_output",new xe);this.pipeline.source.pipeTo(this.pipeline.gain),this.pipeline.gain.pipeTo(this.pipeline.volumeMeter).pipeTo(this._output),this.pipeline.gain.pipeTo(this.pipeline.destination)}setOutput(){this.mode=1,this._output.setNode(Ee("player").destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,r,s;((r=(t=this.element)==null?void 0:t.error)==null?void 0:r.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(ue.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=((s=e.getSettings())==null?void 0:s.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){if(this._floatVolume!==e)if(this._floatVolume=e,this.useDestination)this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`);else if(e<=1&&!ge)this.element?(this._log.info(`set element volume: ${e}`),this.element.volume=e):this._log.info("set element volume: no element");else{if(ge)if(this.enableVolumeControlInIOS)Xp();else return;if(K&&!this.pipeline.source.node){this._log.warn("set pipeline volume failed: no source node");return}this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this._destination||(this._destination=Ee("player").createMediaStreamDestination()),this.pipeline.destination.setNode(this._destination),Le(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play())}}stop(e=0){this.pipeline.destroy();let t=this._sourceElement||this.element;t&&Ft&&(Nc=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var no=class extends J{constructor({userId:e,sdkAppId:t,mediaType:r,room:s,PlayerClass:n=r===1?hs:it}){var a;super();d(this,"id",cn());d(this,"userId","");d(this,"isRemote");d(this,"mediaType");d(this,"room");d(this,"user");d(this,"_log");d(this,"_inputTrack");d(this,"_outputTrack");d(this,"isPlayCalled");d(this,"container",null);d(this,"player");d(this,"subVideoPlayerMap");d(this,"muted",!1);d(this,"abortCtrl");d(this,"objectFit","cover");d(this,"mirror");d(this,"rotation");d(this,"isScreen",!1);d(this,"manager");d(this,"trackSettings");d(this,"isFirstVideoFrameEmitted",!1);this.userId=e||"",this.mediaType=r,this._log=R.createLogger({parent:s==null?void 0:s.getLogger(),id:`${this.kind[0]}t`,userId:(a=s||this.room)==null?void 0:a.userId,remoteUserId:this instanceof pi?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof pi}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:s==null?void 0:s.enableVolumeControlInIOS}),this.player.on(ue.PLAYER_STATE_CHANGED,c=>{if(S.emit(C.PLAYER_STATE_CHANGED,O({track:this},c)),this.emit("player-state-changed",c),c.state==="PLAYING"&&this.room){let l=!0;for(let{remoteAudioTrack:u,remoteVideoTrack:m,remoteAuxiliaryTrack:h}of[...this.room.remotePublishedUserMap.values()])if(u.isAvailable&&!u.player.isPlaying||m.isAvailable&&!m.player.isPlaying||h.isAvailable&&!h.player.isPlaying){l=!1;break}l&&br()&&$p()}}),this.kind===f.VIDEO&&(this.player.on(ue.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(ue.LOADED_DATA),S.emit(C.VIDEO_LOADED_DATA,{track:this})}),this.player.on(ue.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(ue.LOADED_META_DATA)}),this.player.on(ue.MEDIA_TRACK_CHANGED,c=>{var l;(l=this.subVideoPlayerMap)==null||l.forEach(u=>u.setTrack(c))}),this.player.on(ue.RESIZE,c=>{this.emitFirstVideoFrameEvent(ue.RESIZE),this.emit("video-size-changed",O({userId:this.userId,streamType:this.mediaType===2?"auxiliary":"main"},c))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(ue.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||R}get kind(){return this.mediaType===1?f.AUDIO:f.VIDEO}get isAudio(){return this.kind===f.AUDIO}get strMediaType(){return this.mediaType===4?f.VIDEO:this.mediaType===2?f.SCREEN:f.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}get isMediaTrackActive(){return this.mediaTrack?!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled:!1}play(e,t){return p(this,null,function*(){let r=Ie(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(t)}`),t&&!T(t.muted)&&this.setPlayerMute(t.muted),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof it&&(this.player.setObjectFit(this.objectFit),this.container!==r&&r&&(this.container=r,this.player.setContainer(r)),Ie(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t)));return}if(t&&!T(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===f.VIDEO)&&this.setPlayerMute(!0),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof it&&(this.player.setObjectFit(this.objectFit),t&&!T(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,r&&(this.container=r,this.player instanceof it&&this.player.setContainer(r)),S.emit(C.PLAY_TRACK_START,{track:this}),!this._outputTrack){this.log.info("play has not mediaTrack, abort");return}this._log.info(`play with options: ${JSON.stringify(t)}`);try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(t),Ie(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(s){throw this.handleAutoPlayFailed(s),s}})}setMirror(e,t){if(this.isScreen||this.kind!==f.VIDEO||T(e)||e===this.mirror)return;this.mirror=e;let r=this.player;t&&(r=t);let s=this.manager;if(he(this.mirror)){r.setViewMirror(this.mirror),!this.isRemote&&s&&(s.mirror=!1);return}switch(this.mirror){case"view":{s&&(s.mirror=!1),r.setViewMirror(!0);break}case"publish":{s&&(s.mirror=!0),r.setViewMirror(!0);break}case"both":s&&(s.mirror=!0),r.setViewMirror(!1)}}playSubContainer(e,t){return p(this,null,function*(){if(!this._outputTrack||this.kind===f.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((s,n)=>{var a;e.find(c=>n===c)||(s.stop(),(a=this.subVideoPlayerMap)==null||a.delete(n))});for(let[s,n]of e.entries()){let a=this.subVideoPlayerMap.get(n);a?t&&(T(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new it({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${s+1}`})}))}let r=[...this.subVideoPlayerMap.values()];for(let s of r)s.setViewMirror(this.player.mirror),yield s.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(e=!1){this.isPlayCalled&&(this.isPlayCalled=!1,this.isFirstVideoFrameEmitted=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(Sl(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(t=>{t.stop()}),this.container=null)}resume(){return p(this,null,function*(){var e;this.isPlayCalled&&(yield(e=this.player)==null?void 0:e.resume())})}close(){this.log.info("close"),this.isPlayCalled&&this.stop(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),S.emit(e?C.TRACK_MUTED:C.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(e){tt(e,e).add(f.MUTE,this.onTrackMuted).add(f.UNMUTE,this.onTrackUnmuted).add(f.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===f.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){Le(e)}setInputMediaStreamTrack(e){var r;let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.trackSettings=(r=e.getSettings)==null?void 0:r.call(e),e.enabled=!this.muted,t&&this.uninstallTrackEvent(t),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,t||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var r;let t=this._outputTrack;e!==t&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(r=e.getSettings)==null?void 0:r.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(t=>this.handleAutoPlayFailed(t)),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(Sl(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(e){return p(this,null,function*(){var r;this.log.warn("handleAutoPlayFailed",e);let t=()=>{this.resume().then(()=>{document.removeEventListener("click",t,!0)})};if(this.room&&this.room.enableAutoPlayDialog){if((Ji||ji)&&(yield Ke(100),(r=this.player)!=null&&r.isPlaying))return;ns()}else document.addEventListener("click",t,!0);S.once(C.LOCAL_TRACK_CAPTURE_SUCCESS,({track:s})=>{s.kind==="audio"&&br()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&t()}),this.emit("error",e)})}getVideoFrame(){return this.player instanceof it?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var n,a,c;if(this.isFirstVideoFrameEmitted)return;let t=(n=this.mediaTrack)==null?void 0:n.getSettings(),r=(t==null?void 0:t.width)||((a=this.player.element)==null?void 0:a.videoWidth)||0,s=(t==null?void 0:t.height)||((c=this.player.element)==null?void 0:c.videoHeight)||0;e===ue.RESIZE&&!r&&!s||e===ue.LOADED_META_DATA&&!r&&!s||(e===ue.LOADED_DATA&&!r&&!s&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,bt(this.rotation)&&([r,s]=[s,r]),this.emit("first-video-frame",{width:r,height:s,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};M([ye([],J.INIT,{sync:!0})],no.prototype,"close",1);var XT=Object.prototype.hasOwnProperty,{toString:Ob}=Object.prototype;function zT(o){if(o==null)return!0;if(typeof o=="boolean")return!1;if(typeof o=="number")return o===0;if(typeof o=="string"||typeof o=="function"||Array.isArray(o))return o.length===0;if(o instanceof Error)return o.message==="";if(dt(o))switch(Object.prototype.toString.call(o)){case"[object File]":case"[object Map]":case"[object Set]":return o.size===0;case"[object Object]":{for(let i in o)if(XT.call(o,i))return!1;return!0}}return!1}var fi=zT;var QT=function(o){return p(this,null,function*(){let i=ZT(o);R.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],r=["label","deviceId","groupId"];if(i.audio&&(e=yield It(),R.info(`microphones: ${_t(e.map(s=>L(O({},s),{groupId:s.groupId.substring(0,8)})),{keysToInclude:r})}`)),i.video&&(t=yield At(),R.info(`cameras: ${_t(t,{keysToInclude:r})}`),!he(i.video)&&i.video.facingMode==="user"&&!i.video.deviceId)){let n=t.filter(a=>!a.label.includes("infrared")).find(a=>a.label.includes("facing front"));n&&(i.video.deviceId=n.deviceId,R.info(`exclude infrared camera: ${JSON.stringify(i)}`))}try{let s=yield navigator.mediaDevices.getUserMedia(i);return cu&&s.getTracks().forEach(n=>{var c;let a=n.getCapabilities();R.info(`${n.kind} capabilities: ${_t(a,{keysToInclude:Ia})}`),!T(o.echoCancellation)&&((c=a.echoCancellation)==null?void 0:c.indexOf(o.echoCancellation))===-1&&R.warn(`Invalid argument for 'echoCancellation'. Expected one of [${JSON.stringify(a.echoCancellation)}], but received '${o.echoCancellation}'`)}),i.audio&&vr(),s}catch(s){let{message:n}=s;throw s.name==="NotFoundError"&&(o.video&&t&&t.length===0&&(n=H({key:F.CAMERA_NOT_FOUND})),o.audio&&e&&e.length===0&&(n=H({key:F.MICROPHONE_NOT_FOUND}))),new D({code:I.INITIALIZE_FAILED,name:s.name,message:n,constraint:s.constraint})}})},YT=Ai({retryFunction:QT,settings:{retries:3,timeout:500},onError:({error:o,retry:i,reject:e,retryFuncArgs:t,retriedCount:r})=>{let s=r+1;o.name==="NotReadableError"||o.name==="OverconstrainedError"||o.name==="AbortError"?(s===1?(t[0].video&&(t[0].maxResolution=!1,(!Re||t[0].width*t[0].height<=1920*1080)&&t[0].frameRate&&(t[0].frameRate=t[0].frameRate>10?10:5)),t[0].retryWhenExactFailed&&t[0].useExactDeviceId&&(t[0].useExactDeviceId=!1)):s===2?t[0].useDeviceIdOnly=!0:s===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(o),t[0].microphoneId&&sf(t[0].microphoneId,!1),t[0].cameraId&&sf(t[0].cameraId,!0)},onRetrying:o=>{R.warn(`getUserMedia NotReadableError observed, retrying [${o}/3]`)},onRetryFailed:o=>{se.logFailedEvent({eventType:Ze.GET_USER_MEDIA_RETRY,error:o})},onRetrySuccess:o=>{se.logSuccessEvent({eventType:Ze.GET_USER_MEDIA_RETRY}),se.uploadEvent({log:`stat-${Ze.GET_USER_MEDIA_RETRY}-success-${o}`})}});function sf(o,i){return p(this,null,function*(){let t=(i?yield At():yield It()).find(r=>r.deviceId===o);t&&le(t.getCapabilities)&&R.warn(_t(t.getCapabilities(),{keysToInclude:Ia}))})}function ZT(o){return{audio:KT(o),video:eE(o)}}function KT(o){if(!o.audio)return!1;if(o.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:o.sampleRate};return!fi(o.microphoneId)&&(i.deviceId=o.useExactDeviceId?{exact:o.microphoneId}:o.microphoneId,o.useDeviceIdOnly)?i:(z(o.channelCount)&&(i.channelCount=o.channelCount),(he(o.echoCancellation)||o.echoCancellation==="remote-only"||o.echoCancellation==="all")&&(i.echoCancellation=o.echoCancellation),he(o.noiseSuppression)&&!o.noiseSuppression&&(i.noiseSuppression=!1),he(o.autoGainControl)&&!o.autoGainControl&&(i.autoGainControl=!1),fi(i)?!0:i)}function eE(o){if(!o.video)return!1;if(o.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=o,e={};return o.cameraId?e.deviceId=o.useExactDeviceId?{exact:o.cameraId}:o.cameraId:o.facingMode&&(e.facingMode=o.facingMode),o.useDeviceIdOnly&&!fi(e)?e:(o.width&&(e.width={ideal:o.width},i&&!K&&(e.width.max=o.width)),o.height&&(e.height={ideal:o.height},i&&!K&&(e.height.max=o.height)),K&&ri&&o.width&&o.height&&o.width*o.height<352*288&&(e.width=o.width,e.height=o.height),o.frameRate&&(e.frameRate=o.frameRate),fi(e)?!0:e)}var nf=YT;function Mc(o){return Q((i,e)=>function(...t){return p(this,null,function*(){return yield o.apply(this,t),i.apply(this,t)})})}function Ct(o){return Q((i,e)=>function(...t){return p(this,null,function*(){let r=yield i.apply(this,t);return yield o.call(this,...t),r})})}function Oc(o){return Q((i,e)=>function(...t){return p(this,null,function*(){try{return yield i.apply(this,t)}catch(r){o.call(this,r)}})})}function Q(o){return function(i,e,t){return t.value=o(t.value,e),t}}var af=(()=>{let o=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&R.info(`visibility change: ${document.visibilityState}`),!o&&(document.addEventListener("visibilitychange",()=>{R.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),o=!0)}})();var tE=0,kc=class{constructor(){d(this,"log",R.createLogger({id:`fq${++tE}`}));d(this,"isRunning",!1);d(this,"queue",[])}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(i,e=!1){var s,n;let t=O({},i),r=new Promise((a,c)=>{t.resolve=a,t.reject=c});return t.promise=r,e?this.length<=1?this.queue.push(t):(n=(s=this.lastQueueItem)==null?void 0:s.promise)==null||n.then(t.resolve,t.reject):this.queue.push(t),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),r}shift(){let i=this.queue.shift();return this.log.debug(`shift ${this.length}`),i}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:i,args:e,context:t,resolve:r,reject:s}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(r,s).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},Pc=new WeakMap,wc=new WeakMap;function ir(o=!1){return function(i,e,t){let r=t.value;return t.value=function(...s){let n=Pc.get(this)||new kc;return Pc.set(this,n),n.push({fn:r,args:s,context:this},o)},t}}function Lc(o){return function(i,e,t){let r=t.value;return t.value=function(...s){var a,c,l;let n=[];return(c=(a=Pc.get(this))==null?void 0:a.queue)==null||c.forEach(u=>n.push(u)),(l=wc.get(this))==null||l.forEach(u=>u==null?void 0:u.queue.forEach(m=>n.push(m))),n.forEach(u=>{u.reject(new D({code:I.API_CALL_ABORTED,message:o}))}),Pc.delete(this),wc.delete(this),r.apply(this,s)},t}}function _i(o){return function(i,e,t){let r=t.value,s=n=>o(...n);return t.value=function(...n){let a=wc.get(this)||new Map,c=a.get(s(n))||new kc;return a.set(s(n),c),wc.set(this,a),c.push({fn:r,args:n,context:this})},t}}function Rt(o,i){return Q((e,t)=>function(...r){let s=o;try{let n=e.apply(this,r),a=U();return Tr(n)?n.then(c=>(i?v.addSuccessEvent({key:s,cost:U()-a}):v.addSuccessEvent({key:s}),c)).catch(c=>{throw v.addFailedEvent({key:s,error:c}),c}):(v.addSuccessEvent({key:s}),n)}catch(n){throw v.addFailedEvent({key:s,error:n}),n}})}var gh={};Vi(gh,{Events:()=>Oe,Inspect:()=>Ht,LastSink:()=>ao,Sink:()=>j,Subscribe:()=>co,TimeoutError:()=>wn,audit:()=>VE,bindCallback:()=>CE,bindNodeCallback:()=>RE,buffer:()=>lE,bufferCount:()=>dE,bufferTime:()=>rS,call:()=>cf,catchError:()=>ph,combineLatest:()=>lf,concat:()=>oE,concatMap:()=>zE,concatMapTo:()=>QE,count:()=>vE,create:()=>ae,debounce:()=>FE,debounceTime:()=>BE,defer:()=>uf,delay:()=>oS,deliver:()=>X,dispose:()=>xc,elementAt:()=>HE,empty:()=>Vn,every:()=>JE,exhaustMap:()=>KE,exhaustMapTo:()=>eS,expand:()=>sS,filter:()=>$t,find:()=>$E,findIndex:()=>WE,first:()=>GE,fromAnimationFrame:()=>IE,fromArray:()=>fE,fromEvent:()=>ce,fromEventPattern:()=>_E,fromFetch:()=>gE,fromIterable:()=>TE,fromPromise:()=>pf,fromReadableStream:()=>SE,fromReader:()=>EE,groupBy:()=>tS,identity:()=>iE,ignoreElements:()=>OE,iif:()=>nE,inspect:()=>df,interval:()=>Vu,last:()=>qE,map:()=>Fn,mapTo:()=>XE,max:()=>NE,merge:()=>Ln,mergeMap:()=>YE,mergeMapTo:()=>ZE,min:()=>DE,never:()=>yE,nothing:()=>pe,of:()=>pE,pairwise:()=>jE,pipe:()=>de,race:()=>xu,range:()=>AE,reduce:()=>Fu,retry:()=>dS,scan:()=>mh,setAsapScheduler:()=>mE,share:()=>rr,shareReplay:()=>sE,skip:()=>PE,skipUntil:()=>wE,skipWhile:()=>Hc,startWith:()=>xn,subject:()=>ot,subscribe:()=>Te,sum:()=>ME,switchMap:()=>Mr,switchMapTo:()=>mo,take:()=>or,takeLast:()=>kE,takeUntil:()=>ke,takeWhile:()=>ff,tap:()=>Bn,throttle:()=>xE,throwError:()=>bE,timeInterval:()=>iS,timeout:()=>cS,timer:()=>Un,toPromise:()=>nS,toReadableStream:()=>aS,withLatestFrom:()=>cE,zip:()=>aE});function pe(...o){}var cf=o=>o(),iE=o=>o;function xc(){this.dispose()}var df=()=>typeof __FASTRX_DEVTOOLS__!="undefined",rE=1,Ht=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new ku(i,this,this.streamId++);return Oe.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},ao=class{constructor(){this.defers=new Set,this.disposed=!1}next(i){}complete(){this.dispose()}error(i){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=pe,this.error=pe,this.next=pe,this.dispose=pe,this.subscribe=pe,this.doDefer()}subscribe(i){return i instanceof Ht?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(cf),this.defers.clear()}defer(i){this.defers.add(i)}removeDefer(i){this.defers.delete(i)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},j=class extends ao{constructor(i){super(),this.sink=i,i.defer(this.bindDispose)}next(i){this.sink.next(i)}complete(){this.sink.complete()}error(i){this.sink.error(i)}},co=class extends ao{constructor(i,e=pe,t=pe,r=pe){if(super(),this._next=e,this._error=t,this._complete=r,this.then=pe,i instanceof Ht){let s={toString:()=>"subscribe",id:0,source:i};this.defer(()=>{Oe.defer(s,0)}),Oe.create(s),Oe.pipe(s),this.sourceId=s.id,this.subscribe(i),Oe.subscribe({id:s.id,end:!0}),e==pe?this._next=n=>Oe.next(s,0,n):this.next=n=>{Oe.next(s,0,n),e(n)},r==pe?this._complete=()=>Oe.complete(s,0):this.complete=()=>{this.dispose(),Oe.complete(s,0),r()},t==pe?this._error=n=>Oe.complete(s,0,n):this.error=n=>{this.dispose(),Oe.complete(s,0,n),t(n)}}else this.subscribe(i)}next(i){this._next(i)}complete(){this.dispose(),this._complete()}error(i){this.dispose(),this._error(i)}};function de(o,...i){return i.reduce((e,t)=>t(e),o)}function ae(o,i,e){if(df()){let t=Object.defineProperties(Object.setPrototypeOf(o,Ht.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:i,writable:!0,configurable:!0},args:{value:e,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});Oe.create(t);for(let r=0;r<e.length;r++){let s=e[r];typeof s=="function"&&s instanceof Ht&&Oe.addSource(t,s)}return t}return o}function X(o,i){return function(...e){return t=>{if(t instanceof Ht){let r=ae(s=>{let n=new o(s,...e);n.sourceId=r.id,n.subscribe(t)},i,arguments);return r.source=t,Oe.pipe(r),r}else return r=>t(new o(r,...e))}}}function Dr(o,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:o,payload:i}})}var ku=class extends j{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{Oe.defer(this.source,this.id)})}next(i){Oe.next(this.source,this.id,i),this.sink.next(i)}complete(){Oe.complete(this.source,this.id),this.sink.complete()}error(i){Oe.complete(this.source,this.id,i),this.sink.error(i)}},Oe={addSource(o,i){Dr("addSource",{id:o.id,name:o.toString(),source:{id:i.id,name:i.toString()}})},next(o,i,e){Dr("next",{id:o.id,streamId:i,data:e&&e.toString()})},subscribe({id:o,end:i},e){Dr("subscribe",{id:o,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(o,i,e){Dr("complete",{id:o.id,streamId:i,err:e?e.toString():null})},defer(o,i){Dr("defer",{id:o.id,streamId:i})},pipe(o){Dr("pipe",{name:o.toString(),id:o.id,source:{id:o.source.id,name:o.source.toString()}})},update(o){Dr("update",{id:o.id,name:o.toString()})},create(o){o.id||(o.id=rE++),Dr("create",{name:o.toString(),id:o.id})}},wn=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var Uc=class extends ao{constructor(i){super(),this.source=i,this.sinks=new Set}add(i){i.defer(()=>this.remove(i)),this.sinks.add(i).size===1&&(this.reset(),this.subscribe(this.source))}remove(i){this.sinks.delete(i),this.sinks.size===0&&this.dispose()}next(i){this.sinks.forEach(e=>e.next(i))}complete(){this.sinks.forEach(i=>i.complete()),this.sinks.clear()}error(i){this.sinks.forEach(e=>e.error(i)),this.sinks.clear()}};function rr(){return o=>{let i=new Uc(o);if(o instanceof Ht){let e=ae(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=o,Oe.pipe(e),e}return ae(i.add.bind(i),"share",arguments)}}function Ln(...o){return ae(i=>{let e=new j(i),t=o.length;e.complete=()=>{--t===0&&i.complete()},o.forEach(e.bindSubscribe)},"merge",arguments)}function xu(...o){return ae(i=>{let e=new Map;o.forEach(t=>{let r=new j(i);e.set(t,r),r.complete=()=>{e.delete(t),e.size===0?i.complete():r.dispose()},r.next=s=>{e.delete(t),e.forEach(n=>n.dispose()),r.resetNext(),r.resetComplete(),r.next(s)}}),o.forEach(t=>e.get(t).subscribe(t))},"race",arguments)}function oE(...o){return ae(i=>{let e=0,t=o.length,r=new j(i);r.complete=()=>{e<t&&!r.disposed?(r.doDefer(),r.subscribe(o[e++])):i.complete()},r.complete()},"concat",arguments)}function sE(o){return i=>{let e=new Uc(i),t=[];return e.next=function(r){t.push(r),t.length>o&&t.shift(),this.sinks.forEach(s=>s.next(r))},ae(r=>{r.defer(()=>e.remove(r)),t.forEach(s=>r.next(s)),e.add(r)},"shareReplay",arguments)}}function nE(o,i,e){return ae(t=>o()?i(t):e(t),"iif",arguments)}function lf(...o){return ae(i=>{let e=o.length,t=e,r=e,s=new Array(e),n=()=>{--r===0&&i.complete()},a=(c,l)=>{let u=new j(i);u.next=m=>{t--,u.next=h=>{s[l]=h,t===0&&i.next(s)},u.next(m)},u.complete=n,u.subscribe(c)};o.forEach(a)},"combineLatest",arguments)}function aE(...o){return ae(i=>{let e=o.length,t=e,r=new Array(e),s=()=>{--t===0&&i.complete()},n=(a,c)=>{let l=new j(i),u=[];r[c]=u,l.next=m=>{u.push(m),r.every(h=>h.length)&&i.next(r.map(h=>h.shift()))},l.complete=s,l.subscribe(a)};o.forEach(n)},"zip",arguments)}function xn(...o){return i=>ae((e,t=0,r=o.length)=>{for(;t<r&&!e.disposed;)e.next(o[t++]);e.disposed||e.subscribe(i)},"startWith",arguments)}var Pu=class extends j{constructor(i,...e){super(i);let t=new j(this.sink);t.next=r=>this.buffer=r,t.complete=pe,t.subscribe(lf(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},cE=X(Pu,"withLatestFrom"),wu=class extends j{constructor(i,e,t){super(i),this.bufferSize=e,this.startBufferEvery=t,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(i){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(i)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(i),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(i=>this.sink.next(i)),super.complete()}},dE=X(wu,"bufferCount"),Lu=class extends j{constructor(i,e){super(i),this.buffer=[];let t=new j(i);t.next=r=>{i.next(this.buffer),this.buffer=[]},t.complete=pe,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},lE=X(Lu,"buffer");var uE=function(o,i,e,t){function r(s){return s instanceof e?s:new e(function(n){n(s)})}return new(e||(e=Promise))(function(s,n){function a(u){try{l(t.next(u))}catch(m){n(m)}}function c(u){try{l(t.throw(u))}catch(m){n(m)}}function l(u){u.done?s(u.value):r(u.value).then(a,c)}l((t=t.apply(o,i||[])).next())})};function ot(o){let i=arguments,e=rr()(ae(t=>{e.next=r=>t.next(r),e.complete=()=>t.complete(),e.error=r=>t.error(r),o&&t.subscribe(o)},"subject",i));return e.next=pe,e.complete=pe,e.error=pe,e}function uf(o){return ae(i=>i.subscribe(o()),"defer",arguments)}var ms={promise:o=>{Promise.resolve().then(o)},setImmediate:typeof setImmediate!="undefined"?o=>setImmediate(o):null,setTimeout:o=>setTimeout(o,0)},hE=()=>typeof Promise!="undefined"?ms.promise:ms.setImmediate?ms.setImmediate:ms.setTimeout,Uu=hE(),hf=o=>i=>{Uu(()=>o(i))},mE=o=>{typeof o=="function"?Uu=o:ms[o]&&(Uu=ms[o])};var mf=o=>hf(i=>{for(let e=0;!i.disposed&&e<o.length;e++)i.next(o[e]);i.complete()});function pE(...o){return ae(mf(o),"of",arguments)}function fE(o){return ae(mf(o),"fromArray",arguments)}function Vu(o){return ae(i=>{let e=0,t=setInterval(()=>i.next(e++),o);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}function Un(o,i){return ae(e=>{let t=0,r=setTimeout(()=>{if(e.removeDefer(s),e.next(t++),i){let n=setInterval(()=>e.next(t++),i);e.defer(()=>{clearInterval(n)})}else e.complete()},o),s=()=>clearTimeout(r);e.defer(s)},"timer",arguments)}function Vc(o,i){return e=>{let t=r=>e.next(r);e.defer(()=>i(t)),o(t)}}function _E(o,i){return ae(Vc(o,i),"fromEventPattern",arguments)}function ce(o,i){if("on"in o&&"off"in o)return ae(Vc(e=>o.on(i,e),e=>o.off(i,e)),"fromEvent",arguments);if("addListener"in o&&"removeListener"in o)return ae(Vc(e=>o.addListener(i,e),e=>o.removeListener(i,e)),"fromEvent",arguments);if("addEventListener"in o)return ae(Vc(e=>o.addEventListener(i,e),e=>o.removeEventListener(i,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function pf(o){return ae(i=>{o.then(i.next.bind(i),i.error.bind(i))},"fromPromise",arguments)}function gE(o,i){return ae(uf(()=>pf(fetch(o,i))),"fromFetch",arguments)}function TE(o){return ae(hf(i=>{try{for(let e of o){if(i.disposed)return;i.next(e)}i.complete()}catch(e){i.error(e)}}),"fromIterable",arguments)}function EE(o){let i=e=>uE(this,void 0,void 0,function*(){if(e.disposed)return;let{done:t,value:r}=yield o.read();if(t){e.complete();return}else e.next(r),i(e)});return ae(e=>{i(e)},"fromReader",arguments)}function SE(o){return ae(i=>{let e=new AbortController,t=e.signal;i.defer(()=>e.abort("cancelled")),o.pipeTo(new WritableStream({write(r){i.next(r)},close(){i.complete()},abort(r){i.error(r)}}),{signal:t}).then(()=>i.complete(),r=>i.error(r))},"fromReadableStream",arguments)}function IE(){return ae(o=>{let i=requestAnimationFrame(function e(t){o.disposed||(o.next(t),i=requestAnimationFrame(e))});o.defer(()=>cancelAnimationFrame(i))},"fromAnimationFrame",arguments)}function AE(o,i){return ae((e,t=o,r=i+o)=>{for(;t<r&&!e.disposed;)e.next(t++);return e.complete(),"range"},"range",arguments)}function CE(o,i,...e){return ae(t=>{let r=e.concat(s=>(t.next(s),t.complete()));o.apply(i,r)},"bindCallback",arguments)}function RE(o,i,...e){return ae(t=>{let r=e.concat((s,n)=>s?t.error(s):(t.next(n),t.complete()));o.apply(i,r)},"bindNodeCallback",arguments)}function yE(){return ae(()=>{},"never",arguments)}function bE(o){return ae(i=>i.error(o),"throwError",arguments)}function Vn(){return ae(o=>o.complete(),"empty",arguments)}var lo=class extends j{constructor(i,e,t){super(i),this.f=e;let r=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=s=>{this.acc=s,this.complete=r,this.resetNext()}:(this.acc=t,this.complete=r)}next(i){this.acc=this.f(this.acc,i)}},Fu=X(lo,"reduce"),vE=o=>X(lo,"count")((i,e)=>o(e)?i+1:i,0),NE=()=>X(lo,"max")(Math.max),DE=()=>X(lo,"min")(Math.min),ME=()=>X(lo,"sum")((o,i)=>o+i,0);var Bu=class extends j{constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},$t=X(Bu,"filter"),Hu=class extends j{next(i){}},OE=X(Hu,"ignoreElements"),$u=class extends j{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&(this.doDefer(),this.complete())}},or=X($u,"take"),Wu=class extends j{constructor(i,e){super(i);let t=new j(i);t.next=()=>{t.doDefer(),i.complete()},t.complete=xc,t.subscribe(e)}},ke=X(Wu,"takeUntil"),Gu=class extends j{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):(this.doDefer(),this.complete())}},ff=X(Gu,"takeWhile"),kE=o=>Fu((i,e)=>(i.push(e),i.length>o&&i.shift(),i),[]),qu=class extends j{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},PE=X(qu,"skip"),Ju=class extends j{constructor(i,e){super(i),i.next=pe;let t=new j(i);t.next=()=>{t.doDefer(),i.resetNext()},t.complete=xc,t.subscribe(e)}},wE=X(Ju,"skipUntil"),ju=class extends j{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},Hc=X(ju,"skipWhile"),LE={leading:!0,trailing:!1},Xu=class extends j{constructor(i,e,t){super(i),this.durationSelector=e,this.trailing=t}cacheValue(i){this.last=i,this.disposed&&this.throttle(i)}send(i){this.sink.next(i),this.throttle(i)}throttle(i){this.reset(),this.subscribe(this.durationSelector(i))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},Fc=class extends j{constructor(i,e,t=LE){super(i),this.durationSelector=e,this.config=t,this._throttle=new Xu(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(i){this._throttle.disposed&&this.config.leading?this._throttle.send(i):this._throttle.cacheValue(i)}complete(){this._throttle.throttle=pe,this._throttle.complete(),super.complete()}},xE=X(Fc,"throttle"),UE={leading:!1,trailing:!0},VE=o=>X(Fc,"audit")(o,UE),zu=class extends j{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Bc=class extends j{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new zu(this.sink),this._debounce.dispose()}next(i){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=i,this._debounce.subscribe(this.durationSelector(i))}complete(){this._debounce.complete(),super.complete()}},FE=X(Bc,"debounce"),BE=o=>X(Bc,"debounceTime")(i=>Un(o)),Qu=class extends j{constructor(i,e,t){super(i),this.count=e,this.defaultValue=t}next(i){this.count--===0&&(this.defaultValue=i,this.doDefer(),this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("not enough elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},HE=X(Qu,"elementAt"),$E=o=>i=>or(1)(Hc(e=>!o(e))(i)),Yu=class extends j{constructor(i,e){super(i),this.f=e,this.i=0}next(i){this.f(i)?(this.sink.next(this.i++),this.doDefer(),this.complete()):++this.i}},WE=X(Yu,"findIndex"),Zu=class extends j{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i,this.doDefer(),this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},GE=X(Zu,"first"),Ku=class extends j{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i)}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},qE=X(Ku,"last"),eh=class extends j{constructor(i,e){super(i),this.predicate=e,this.index=0}next(i){this.predicate(i,this.index++)?this.result=!0:(this.result=!1,this.doDefer(),this.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},JE=X(eh,"every");var th=class extends j{constructor(i,e,t){super(i),this.f=e,typeof t=="undefined"?this.next=r=>{this.acc=r,this.resetNext(),this.sink.next(this.acc)}:this.acc=t}next(i){this.sink.next(this.acc=this.f(this.acc,i))}},mh=X(th,"scan"),ih=class extends j{constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},jE=X(ih,"pairwise"),$c=class extends j{constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},Fn=X($c,"map"),XE=o=>X($c,"mapTo")(i=>o),uo=class extends j{constructor(i,e,t){super(i),this.data=e,this.context=t}next(i){let e=this.context.combineResults;e?this.sink.next(e(this.data,i)):this.sink.next(i)}tryComplete(){this.context.resetComplete(),this.dispose()}},ho=class o extends j{constructor(i,e,t){super(i),this.makeSource=e,this.combineResults=t,this.index=0}subInner(i,e){let t=this.currentSink=new e(this.sink,i,this);this.complete===o.prototype.complete&&(this.complete=this.tryComplete),t.complete=t.tryComplete,t.subscribe(this.makeSource(i,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},Wc=class extends uo{},Gc=class extends ho{next(i){this.subInner(i,Wc),this.next=e=>{this.currentSink.dispose(),this.subInner(e,Wc)}}},Mr=X(Gc,"switchMap");function Xc(o){return(i,e)=>o(()=>i,e)}var mo=Xc(X(Gc,"switchMapTo")),rh=class extends uo{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},qc=class extends ho{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(i){this.next2(i),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),rh),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},zE=X(qc,"concatMap"),QE=Xc(X(qc,"concatMapTo")),oh=class extends uo{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Jc=class extends ho{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,oh),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},YE=X(Jc,"mergeMap"),ZE=Xc(X(Jc,"mergeMapTo")),sh=class extends uo{dispose(){this.context.resetNext(),super.dispose()}},jc=class extends ho{next(i){this.next=pe,this.subInner(i,sh)}},KE=X(jc,"exhaustMap"),eS=Xc(X(jc,"exhaustMapTo")),nh=class extends j{constructor(i,e){super(i),this.f=e,this.groups=new Map}next(i){let e=this.f(i),t=this.groups.get(e);typeof t=="undefined"&&(t=ot(),t.key=e,this.groups.set(e,t),super.next(t)),t.next(i)}complete(){this.groups.forEach(i=>i.complete()),super.complete()}error(i){this.groups.forEach(e=>e.error(i)),super.error(i)}},tS=X(nh,"groupBy"),ah=class extends j{constructor(){super(...arguments),this.start=new Date}next(i){this.sink.next({value:i,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},iS=X(ah,"timeInterval"),ch=class extends j{constructor(i,e){super(i),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(i){this.buffer.push(i)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},rS=X(ch,"bufferTime"),dh=class extends j{constructor(i,e){super(i),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(i){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:t,data:r}=e;super.next(r),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(t))}},i)}next(i){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:i})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},oS=X(dh,"delay"),lh=class extends j{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},ph=X(lh,"catchError"),uh=class extends uo{tryComplete(){let i=this.context.inners.delete(this);super.dispose(),i&&this.context.checkComplete()}next(i){this.sink.next(i),this.context.expandValue(i)}},hh=class extends ho{constructor(i,e){super(i,e),this.project=e,this.inners=new Set,this.sourceCompleted=!1}next(i){this.sink.next(i),this.expandValue(i)}expandValue(i){let e=new uh(this.sink,i,this);this.currentSink=e,this.complete=this.tryComplete,e.complete=e.tryComplete,this.inners.add(e),e.subscribe(this.makeSource(i,this.index++))}complete(){this.sourceCompleted=!0,this.checkComplete()}checkComplete(){this.sourceCompleted&&this.inners.size===0&&(this.resetComplete(),super.complete())}tryComplete(){this.sourceCompleted=!0,this.checkComplete()}},sS=X(hh,"expand");var nS=()=>o=>new Promise((i,e)=>{let t;new co(o,r=>t=r,e,()=>i(t))}),aS=()=>o=>{let i;return new ReadableStream({start(e){i=new co(o,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){i.dispose()}})},Te=(o=pe,i=pe,e=pe)=>t=>new co(t,o,i,e),fh=class extends j{constructor(i,e){super(i),e instanceof Function?this.next=t=>{e(t),i.next(t)}:(e.next&&(this.next=t=>{e.next(t),i.next(t)}),e.complete&&(this.complete=()=>{e.complete(),i.complete()}),e.error&&(this.error=t=>{e.error(t),i.error(t)}))}},Bn=X(fh,"tap"),_h=class extends j{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new wn(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},cS=X(_h,"timeout"),dS=(o=1/0)=>i=>{if(i instanceof Ht){let e=ae(t=>{let r=o,s=new j(t);s.error=n=>{r-- >0?s.subscribe(i):t.error(n)},s.sourceId=e.id,s.subscribe(i)},"retry",[o]);return e.source=i,Oe.pipe(e),e}else return e=>{let t=o,r=new j(e);r.error=s=>{t-- >0?i(r):e.error(s)},i(r)}};var ps=(e=>(e[e.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",e[e.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",e))(ps||{}),po=class po extends no{constructor(e,t){super({mediaType:e,PlayerClass:t});d(this,"isRemote",!1);d(this,"deviceId");d(this,"groupId","");d(this,"label","");d(this,"sourceTrack");d(this,"enableAutoSwitchWhenRecapturing",!0);d(this,"_isRecapturing",!1);d(this,"_lastRecaptureTime",0);d(this,"_onMuteTimeoutId",-1);d(this,"_encodeCheckTimeoutId",-1);d(this,"recaptureMode",0);d(this,"profile");d(this,"retryEncodeFailed")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}get isUseCustomSource(){return this.sourceTrack&&this.mediaTrack&&this.sourceTrack!==this.mediaTrack}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){e.addEventListener(f.MUTE,this.onTrackMuted),e.addEventListener(f.UNMUTE,this.onTrackUnmuted),e.addEventListener(f.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===f.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){e.removeEventListener(f.MUTE,this.onTrackMuted),e.removeEventListener(f.UNMUTE,this.onTrackUnmuted),e.removeEventListener(f.ENDED,this.onTrackEnded)}setStateToReady(){}capture(e,t=!1){return p(this,null,function*(){var s;let r=this.sourceTrack;try{let n=U();S.emit(C.LOCAL_TRACK_CAPTURE_START,{track:this});let a;e.customSource?(a=new MediaStream,a.addTrack(e.customSource)):(t||(s=this.sourceTrack)==null||s.stop(),a=yield nf(e));let c=a.getTracks()[0];return yield this.setInputMediaStreamTrack(c),e.customSource||(this.sourceTrack=c,this.updateDeviceIdInUse(),this.listenDeviceChange()),S.emit(C.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:U()-n}),a}catch(n){throw S.emit(C.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:n}),this.log.error(`getUserMedia error observed ${n}`),n}finally{t&&(r==null||r.stop())}})}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),this.isPublishing||this.isPublished)return(t=this.room)==null?void 0:t.replaceTrack(this)}get hasFlag(){var t,r;let e=Kt(((t=this.room)==null?void 0:t.localPublishFlag)||0,((r=this.room)==null?void 0:r.userId)||"");return this.mediaType===4&&e.hasVideo||this.mediaType===1&&e.hasAudio||this.mediaType===2&&e.hasAuxiliary}publish(e,t){return p(this,null,function*(){return this.room=e,this.room.localTracks.add(this),this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.bindParent(e.getLogger()),yield t,this._checkPublishFlag(e)})}_checkPublishFlag(e){return new Promise((t,r)=>p(this,null,function*(){var l,u,m,h;let s=()=>r(new D({code:I.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?t():((this.state===J.INIT||this.state==="ready")&&s(),de(ce(e,"local-publish-flag-changed"),$t(()=>this.hasFlag),ke(Ln(ce(this,J.INIT),ce(this,"ready"))),Te(t,r,s))),(((u=(l=this.room)==null?void 0:l.networkQuality)==null?void 0:u.uplinkNetworkQuality)||0)>3)return t();let a=e.heartbeatCount,c=((h=(m=this.mediaTrack)==null?void 0:m.stats)==null?void 0:h.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout(()=>p(this,null,function*(){var g,E,A,k,re,P,Qe;if((((E=(g=this.room)==null?void 0:g.networkQuality)==null?void 0:E.uplinkNetworkQuality)||0)>3||e.heartbeatCount-a<3)return t();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if((A=this.mediaTrack)!=null&&A.stats){let te=this.mediaTrack.stats.totalFrames||0;te-c===0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",te)}let N=this.kind===f.AUDIO,b=this.stat.bytesSent>0;if(v[b?"addSuccessEvent":"addFailedEvent"]({key:N?503700:513702}),!N){let te=((re=(k=this.room)==null?void 0:k.videoCodec)==null?void 0:re.toUpperCase())||"H264",ve={H264:513704,H265:513705,VP8:513706}[te];ve&&v[b?"addSuccessEvent":"addFailedEvent"]({key:ve})}if(!b){if(v.addEnum({key:N?503701:513703,value:Zr()}),se.uploadEvent({log:`stat-encode-failed-${this.kind}-${si()||ni()}`,userId:this.userId}),this.log.warn(N?"encode failed":`${(Qe=(P=this.room)==null?void 0:P.videoCodec)==null?void 0:Qe.toUpperCase()} encode failed`),this.retryEncodeFailed&&(this.log.warn("retry encode"),yield this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(yield Ke(5e3),this.stat.bytesSent>0||this.hasFlag)))return t();this.emit("6",this),r(new D({message:`${this.strMediaType} encode failed`,code:N?I.AUDIO_ENCODE_FAILED:I.VIDEO_ENCODE_FAILED}))}}}),1e4)}))}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),S.emit(C.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return p(this,null,function*(){if(this.sourceTrack&&yi){let{deviceId:e,groupId:t}=this.sourceTrack.getSettings(),{label:r}=this.sourceTrack;(yield of({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=r,t&&(this.groupId=t),ds().then(n=>{let a=n.find(c=>{let l=c.deviceId===e;return t&&(l=l&&c.groupId===t),l});a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.sourceTrack||this.kind===f.AUDIO&&!rf(this.sourceTrack)||this.kind===f.VIDEO&&!tf(this.sourceTrack)||this._isRecapturing||e&&ri&&Re)}onTrackMuted(){if(super.onTrackMuted(),af(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<ko){setTimeout(()=>this.onTrackMuted(),ko);return}this._onMuteTimeoutId=setTimeout(()=>p(this,null,function*(){var e;if((e=this.sourceTrack)!=null&&e.muted){if((ge||_e)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return p(this,null,function*(){if(Pe(po.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()&&this.recaptureMode===0){if(Date.now()-this._lastRecaptureTime<ko){setTimeout(()=>this.onTrackEnded(),ko);return}this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e,t=!1){return p(this,null,function*(){var n;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");let r=this.sourceTrack;t||(n=this.sourceTrack)==null||n.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let s={useExactDeviceId:!0};if(e==="user"||e==="environment")s.facingMode=e;else{let a;(this.kind==="audio"?yield It():yield At()).find(l=>l.deviceId===e)&&(a=e),s.deviceId=a}return this.capture(s,t).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),S.emit(C.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(a=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${a.message}`),this.emit("5",a),S.emit(C.LOCAL_TRACK_RECAPTURE,{track:this,error:a})}).finally(()=>{t&&(r==null||r.stop())})})}getRecoverCaptureDeviceId(){return p(this,null,function*(){let e=this instanceof je;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let r=(Hn.get(t)||0)+1;if(Hn.set(t,r),r>=3&&this.enableAutoSwitchWhenRecapturing){let s=e?(yield At()).find(n=>!Hn.has(n.deviceId)):(yield It()).find(n=>!Hn.has(n.deviceId));s&&(this.log.warn(`${t} capture fail ${r} times, change new ${s.deviceId}`),t=s.deviceId)}}return t})}stopCapture(){var e;this.sourceTrack&&(this.sourceTrack.stop(),this.uninstallTrackEvent(this.sourceTrack)),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack),(e=this.manager)==null||e.removeInput(this)}close(){super.close(),this.stopCapture()}};M([ye(J.INIT,"ready",{ignoreError:!0,sync:!0})],po.prototype,"setStateToReady",1),M([ir()],po.prototype,"capture",1),M([ye("ready","publish",{ignoreError:!0,success(){S.emit(C.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this.log.info("published")},fail(e){var n;(n=this.room)==null||n.localTracks.delete(this);let t="error",r=e instanceof D?e:e.cause instanceof D?e.cause:e,s=!1;r instanceof D&&(r.message.includes("timeout")?t="timeout":r.code===I.API_CALL_ABORTED&&(s=!0,t="api-call")),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:r}),this.log[s?"info":"error"]("publish failed",r)}}),Rt(521714,!1)],po.prototype,"publish",1),M([Q(e=>function(){return p(this,null,function*(){let t=this.state==="publish"?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),ye([],"ready",{sync:!0})],po.prototype,"unpublish",1);var pi=po,Hn=new Map;S.on(C.SWITCH_DEVICE_SUCCESS,o=>{o.track.deviceId&&Hn.delete(o.track.deviceId)});var kt=class o extends pi{constructor(e){super(1,Dc);d(this,"mediaType",1);d(this,"volume",0);d(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});d(this,"playerMuted",!0);d(this,"pipeline");d(this,"earMonitorGainNode",new xe);d(this,"_output",new xe);d(this,"codecPipeline",[]);d(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});d(this,"mixedAudioReferenceMap",new Map);d(this,"isAudioContextLongSuspended",!1);d(this,"after3aSilenceStartTime",0);this.manager=e,this.pipeline=new cs(e),this.pipeline.source.pipeTo(this.player.pipeline.volumeMeter),this.pipeline.gain.pipeTo(this.earMonitorGainNode).pipeTo(this._output),this.pipeline.gain.pipeTo(this.player.pipeline.volumeMeterAfter3A),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this),S.on(C.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this)}get dbVolume(){return so.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}getInternalAudioLevelAfter3A(){if(this.pipeline.aec.node||this.pipeline.denoiser.node)return this.player.getInternalAudioLevelAfter3A()}updateAfter3aSilenceStartTime(e){T(e)||(e===0&&!this.after3aSilenceStartTime?this.after3aSilenceStartTime=U():e>0&&(this.after3aSilenceStartTime=0))}setInputMediaStreamTrack(e){return p(this,null,function*(){let t=this.trackSettings||{};v.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),v.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),v.addEnum({key:502700,value:0});let{sampleRate:r,channelCount:s}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:r,channelCount:s})}`),this.pipeline.source.channelCount=s||1,this.pipeline.replaceSource(e),yield Pe(o.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture(a){return p(this,arguments,function*({deviceId:e,customSource:t,useExactDeviceId:r=!0,retryWhenExactFailed:s},n=!1){let c=yield Pe(o.prototype,this,"capture").call(this,{video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:r,retryWhenExactFailed:s,customSource:t},n);return vr(),c})}switchDevice(e){return p(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e&&!this.isUseCustomSource)if(e===Wr){if(yield Mu(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.sourceTrack&&this.sourceTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),S.emit(C.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(t){throw this.log.error(`switch microphone failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}}})}listenDeviceChange(){be&&!be.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&be.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return p(this,null,function*(){if(e.deviceId===this.deviceId){let t=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${ps[this.recaptureMode]}. Current microphone is lost: ${JSON.stringify(e)}`),this.recaptureMode===0){Ne(this.userId,{eventId:2003,param1:6,streamType:1});let r=yield It();r[0]?this.recapture(r[0].deviceId):t=!0}t&&be.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.recaptureMode===1&&e.deviceId!==this.deviceId||(be.off("audioInputAdded",this.handleMicrophoneAdded,this),this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId))}update3A(s){return p(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:r}){let n=this.sourceTrack||this.mediaTrack;if(!n)return;let a=n.getConstraints(),c=!1;!T(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,a.echoCancellation=e,c=!0),!T(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,a.noiseSuppression=t,c=!0),!T(r)&&r!==this.profile.autoGainControl&&(this.profile.autoGainControl=r,a.autoGainControl=r,c=!0),c&&(K||Re?yield n.applyConstraints(a).catch(l=>this._log.warn("update3A failed: ",l)):this.deviceId&&(yield this.recapture(this.deviceId,!0)))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&v.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),ge&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(Ee().createGain()),this._output.setNode(Ee().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this.sourceTrack&&!(Re||ge))return this.update3A({echoCancellation:e})}addDenoiser(e){var t;if(qe<=92&&((t=this.trackSettings)==null?void 0:t.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}v.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.enableTrackANS(!1)}mixAudioReference(e,t){if(this.mixedAudioReferenceMap.has(t))return;this.log.info(`mixAudioReference() => ${t}`);let r=On(e);if(!r)return;let s=new xe,n=Ee().createGain();n.gain.value=1;let a=new xe;s.pipeTo(a).pipeTo(this.pipeline.mixNode),s.setNode(r),a.setNode(n),this.mixedAudioReferenceMap.set(t,[s,a])}unMixAudioReference(e){let[t,r]=this.mixedAudioReferenceMap.get(e)||[];t&&(this.log.info(`unMixAudioReference() => ${e}`),t.deleteNode(),r==null||r.deleteNode(),this.mixedAudioReferenceMap.delete(e))}setAudioReferenceVolume(e,t){let[r,s]=this.mixedAudioReferenceMap.get(e)||[];s!=null&&s.node&&(s.node.gain.value=t/100,this.log.info(`setAudioReferenceVolume() => ${e} ${s.node.gain.value}`))}addAudioProcessor(e,t,r){this.pipeline.silentNode.setNode(r),this.pipeline.mixNode.setNode(t),this.pipeline.aec.setNode(e)}removeDenoiser(e){if(this.pipeline.denoiser.node===e)return this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0)}removeAudioProcessor(e){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode())}close(){this.mixedAudioReferenceMap.forEach(([e,t])=>{e.deleteNode(),t.deleteNode()}),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),be.off("audioInputAdded",this.handleMicrophoneAdded,this),be.off("audioInputRemoved",this.handleMicrophoneRemoved,this),S.off(C.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this),super.close()}recapture(e,t=!1){return p(this,null,function*(){try{yield Pe(o.prototype,this,"recapture").call(this,e,t)}catch(r){let s=(yield It()).find(n=>n.deviceId!==e);if(s)yield Pe(o.prototype,this,"recapture").call(this,s.deviceId);else throw r}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((t,r)=>r?r({frame:t,ntp:Fi()}):t,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}get enableEncryptFrame(){return this.manager&&!!this.manager.encodePipeline[0]}handleAudioContextLongSuspended({isSuspended:e}){if(this.pipeline.isProcessEnabled)if(e){this.isAudioContextLongSuspended=!0,this.log.warn(`context has suspended for ${vu/1e3} seconds, change to source audio${Ft?"":", non-Safari"}`);let t=this.sourceTrack||this.mediaTrack;t&&this.setOutputMediaStreamTrack(t)}else this.isAudioContextLongSuspended=!1,this.log.warn("context has resumed, change to processed audio"),this.pipeline.track&&this.setOutputMediaStreamTrack(this.pipeline.track)}setOutputMediaStreamTrack(e){if(this.isAudioContextLongSuspended){let t=this.sourceTrack||this.mediaTrack;t&&(e=t)}super.setOutputMediaStreamTrack(e)}};function zc(o,i=!1){let e=new DataView(o),t=[],r=0;for(;r<e.byteLength;){let s=0;if(r+4<=e.byteLength&&e.getUint8(r)===0&&e.getUint8(r+1)===0&&e.getUint8(r+2)===0&&e.getUint8(r+3)===1)s=4;else if(r+3<=e.byteLength&&e.getUint8(r)===0&&e.getUint8(r+1)===0&&e.getUint8(r+2)===1)s=3;else{r+=1;continue}let n=-1;for(let m=r+s;m<e.byteLength;m+=1){if(m+4<=e.byteLength&&e.getUint8(m)===0&&e.getUint8(m+1)===0&&e.getUint8(m+2)===0&&e.getUint8(m+3)===1){n=m;break}if(m+3<=e.byteLength&&e.getUint8(m)===0&&e.getUint8(m+1)===0&&e.getUint8(m+2)===1){n=m;break}}let a=n===-1?e.byteLength:n,c=a-r,l=new ArrayBuffer(c),u=new DataView(l);for(let m=0;m<c;m+=1)u.setUint8(m,e.getUint8(r+m));t.push(new sr(u,i)),r=a}return t}var sr=class{constructor(i,e=!1){this.dataView=i;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let{seiPayloadStartIndex:i}=this,e=this.dataView.byteLength-2,t=[],r=0;for(let n=i;n<=e;n++){let a=this.dataView.getInt8(n);switch(a){case 0:case 1:case 2:case 3:r===2&&(t.push(3),r=0),a===0?r+=1:r=0,t.push(a);break;default:r=0,t.push(a);break}}t.push(this.dataView.getInt8(this.dataView.byteLength-1));let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=s}removePreventionByte(){let{seiPayloadStartIndex:i}=this,e=this.dataView.byteLength-1,t=[],r=0;for(let n=i;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:r++,t.push(this.dataView.getInt8(n));break;case 3:r!==2&&t.push(this.dataView.getInt8(n)),r=0;break;default:t.push(this.dataView.getInt8(n)),r=0;break}let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=s}get seiPayloadStartIndex(){let i=6;for(let e=6;e<this.dataView.buffer.byteLength&&(i+=1,this.dataView.getUint8(e)===255);e+=1);return i}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let i=0,e=6;for(let n=6;n<this.dataView.buffer.byteLength;n+=1){let a=this.dataView.getUint8(n);if(e+=1,a===255)i+=255;else{i+=a;break}}let t=new ArrayBuffer(i),r=new DataView(t),s=e;for(let n=0;n<t.byteLength;n+=1)r.setInt8(n,this.dataView.getInt8(s+n));return r}get naluType(){let i=this.getStartCodeLength();return i>=this.dataView.byteLength?0:this.dataView.getUint8(i)&31}getStartCodeLength(){return this.dataView.byteLength>=4&&this.dataView.getUint8(0)===0&&this.dataView.getUint8(1)===0&&this.dataView.getUint8(2)===0&&this.dataView.getUint8(3)===1?4:this.dataView.byteLength>=3&&this.dataView.getUint8(0)===0&&this.dataView.getUint8(1)===0&&this.dataView.getUint8(2)===1?3:0}get isIDR(){return this.naluType===5}get isSPS(){return this.naluType===7}get isPPS(){return this.naluType===8}get isSEI(){return this.naluType===6}};var Qc=class{constructor(){d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_seiPayloadType",243)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,s=[];s.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)s.push(255);s.push(r);let n=new DataView(i);return s.push(...new Uint8Array(n.buffer)),s.push(128),new sr(new DataView(new Uint8Array(s).buffer),!0)}sendSEI(i,e){e!=null&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(i),e!=null&&e.small&&this._smallSeiMessageList.push(i)}isEmpty(){return!this._seiMessageList.length}getNaluCount(i){let e=0,t=0,r=new DataView(i);for(let s=0;s<i.byteLength;s++)switch(r.getUint8(s)){case 0:e++;break;case 1:(e===2||e===3)&&t++,e=0;break;default:e=0;break}return t}encode(i,e){let t=e?this._smallSeiMessageList:this._seiMessageList;if(t.length>0&&i.data.byteLength>0){let s=9-this.getNaluCount(i.data);if(s<=0)return 0;let n=t.splice(0,s).reverse().map(this.encodeSEINalu.bind(this)),a=n.reduce((h,_)=>h+_.dataView.byteLength,0),c=new ArrayBuffer(a+i.data.byteLength),l=new DataView(c),u=new DataView(i.data),m=0;for(let h=0;h<n.length;h++)for(let _=0;_<n[h].dataView.byteLength;_++)l.setInt8(m++,n[h].dataView.getInt8(_));for(let h=0;h<i.data.byteLength;h++)l.setInt8(m++,u.getInt8(h));return i.data=c,n.length}return 0}};var Or=class Or extends pi{constructor(e,t=4){super(t,it);d(this,"profile",O({},pr));d(this,"avoidCropping",!1);d(this,"_scaleResolutionDownBy");d(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0,framesCaptured:0});d(this,"small");d(this,"isNeedToSetBandwidth");d(this,"muteImage");d(this,"manager");d(this,"_seiCodec",new Qc);this.manager=e;let r=()=>{var s;if(this.isAllowed2k4k(this.profile))this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1});else{let n=Ut(((s=this.room)==null?void 0:s.sdkAppId)||0)?ha:ua;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${n}`),this.setProfile(L(O({},this.profile),{width:1920,height:1080})),this.applyProfile()}};this.on("input-media-track-changed",r),this.on("publish",r),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!yi||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get contentHint(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)||""}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}get hasSmall(){var e;return!!((e=this.manager)!=null&&e.hasSmall)}setMute(e){return p(this,null,function*(){var t,r,s;if(ie(e)){if(this.muteImage===e)return;yield(t=this.manager)==null?void 0:t.deleteWatermark("mute"),yield(r=this.manager)==null?void 0:r.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e,fillVideo:!0}),this.muteImage=e,Pe(Or.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield(s=this.manager)==null?void 0:s.deleteWatermark("mute"),this.muteImage=void 0),Pe(Or.prototype,this,"setMute").call(this,e)})}capture(a){return p(this,arguments,function*({deviceId:e,facingMode:t,useExactDeviceId:r=!0,customSource:s,retryWhenExactFailed:n=!0}){let c={audio:!1,video:!0,facingMode:t||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:r,retryWhenExactFailed:n,customSource:s};if(c.facingMode==="environment"){let l=yield this.getDeviceIdWhenUsingBackCamera();l&&(c.cameraId=l)}return Pe(Or.prototype,this,"capture").call(this,c)})}setProfile(e){var r;let t=this.fallbackProfile(e);if(t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile))super.setProfile(t);else{let s=Ut(((r=this.room)==null?void 0:r.sdkAppId)||0)?ha:ua;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${s}`),super.setProfile(L(O({},this.profile),{width:1920,height:1080}))}}applyProfile(){return p(this,null,function*(){var a;if(!this.mediaTrack)return;let{width:e=0,height:t=0}=(this.sourceTrack||this.mediaTrack).getSettings(),r=e*t,s=this.settings,n=s.height!==this.profile.height||s.width!==this.profile.width||s.frameRate!==this.profile.frameRate;if(n&&(et===16&&this.deviceId?yield this.recapture(this.deviceId):(yield(a=this.sourceTrack||this.mediaTrack)==null?void 0:a.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1})),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth){this.isNeedToSetBandwidth=!1;let{width:c=0,height:l=0}=(this.sourceTrack||this.mediaTrack).getSettings(),u=c*l;if(n&&u&&r&&u===r){this.log.warn("set bandwidth failed: resolution is not changed");return}return this.room.setBandWidth({bandwidth:this.profile.bitrate,type:f.VIDEO,videoType:f.BIG})}})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},t=this.sourceTrack||this.mediaTrack;return yi&&t&&Object.assign(e,t.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:Ho(this.settings,this.profile)}isAllowed2k4k(e){var t;return!this.room||!this.room.scheduleResult||this.isScreen||e.height*e.width<2560*1440?!0:((t=this.room.scheduleResult.trtcAutoConf)==null?void 0:t["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return p(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e)&&!this.isUseCustomSource)return;let t={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.sourceTrack&&this.sourceTrack.stop(),yield this.capture(t),S.emit(C.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(t){throw this.log.error(`switch camera failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}})}getDeviceIdWhenUsingBackCamera(){return p(this,null,function*(){let e;try{if(rn&&!Qo&&du){let r=(yield At(!0)).map(n=>{var a;return L(O({},n),{capabilities:(a=n.getCapabilities)==null?void 0:a.call(n)})}).filter(n=>{var a,c;return(c=(a=n.capabilities)==null?void 0:a.facingMode)==null?void 0:c.includes("environment")}),s=r[0];r.forEach(n=>{var u,m,h,_;let{capabilities:a}=n,c=(u=a.width)!=null&&u.max&&((m=a.height)!=null&&m.max)?a.width.max*a.height.max:0,l=(h=s.capabilities.width)!=null&&h.max&&((_=s.capabilities.height)!=null&&_.max)?s.capabilities.width.max*s.capabilities.height.max:0;c>l&&(s=n)}),s!=null&&s.capabilities&&(this._log.info("use max resolution back camera",s),e=s.deviceId)}}catch(t){this._log.warn("get max res camera failed",t)}return e})}updateSmallConfig(e){var r,s;this._log.info(`update small stream config: ${JSON.stringify(e)}`);let t=!this.small;this.small=this.fallbackProfile(e,!0),(r=this.manager)==null||r.update(),t&&((s=this.room)==null||s.enableSmall(!0)),this.log.info("update small stream config success")}fallbackProfile(e,t=!1){let r=e.width>e.height,s=O({},e);return e.width*e.height<=160*120&&_e&&$e&&(this.log.warn(`${t?"small ":""}resolution is ${e.width}*${e.height}, fallback to 240*180 for android chrome`),s.width=r?240:180,s.height=r?180:240,s.bitrate=Math.max(e.bitrate,150)),e.width*e.height>1280*720&&Ol&&(s.width=r?1280:720,s.height=r?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),nn(Tt,"14.3")&&Dl(Tt,"14.0",!0)&&this.on("7",()=>{let n=this.profile.width>this.profile.height;this.profile.width*this.profile.height>640*480?(this.profile.width=n?640:480,this.profile.height=n?480:640,this.log.warn("reduce the resolution to 480p on iOS 14.0 ~ 14.2")):this.profile.width*this.profile.height>640*360&&(this.profile.width=n?640:360,this.profile.height=n?360:640,this.log.warn("reduce the resolution to 360p on iOS 14.0 ~ 14.2"))}),!t&&this.avoidCropping&&($e||K)&&!an()&&e.width*e.height<=640*360&&e.width/e.height===16/9&&(this._scaleResolutionDownBy=1280/e.width,e.width=1280,e.height=720,this.log.warn(`capture 720p, scale: ${this._scaleResolutionDownBy}`)),s}stopSmall(){var e,t;this.small&&(delete this.small,(e=this.manager)==null||e.update(),(t=this.room)==null||t.enableSmall(!1))}listenDeviceChange(){be&&!be.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&be.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return p(this,null,function*(){if(e.deviceId===this.deviceId){let t=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${ps[this.recaptureMode]}. Current camera is lost: ${JSON.stringify(e)}`),this.recaptureMode===0){Ne(this.userId,{eventId:2003,param1:7,streamType:2});let r=yield At();r[0]?this.recapture(r[0].deviceId):t=!0}t&&be.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return p(this,null,function*(){this.recaptureMode===1&&e.deviceId!==this.deviceId||(be.off("videoInputAdded",this.handleCameraAdded,this),this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId))})}encodeFrame(e,t){if(!this.manager)return e;let r=t?8:this.mediaType;return this.manager.encodePipeline.reduceRight((s,n)=>n?n({frame:s,mediaType:r}):s,e)}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}play(e,t){return T(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){be.off("videoInputAdded",this.handleCameraAdded,this),be.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return p(this,null,function*(){try{yield Pe(Or.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield At()).find(s=>s.deviceId!==e);if(r)yield Pe(Or.prototype,this,"recapture").call(this,r.deviceId);else throw t}})}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info(`setContentHint ${e}`),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}setRotation(e){this.manager&&(this.isScreen||T(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};M([Ct(function(e){this.setContentHint(e.contentHint||"motion")})],Or.prototype,"capture",1);var je=Or;var Eh={};Vi(Eh,{REPORT_TYPE:()=>$o,buildSSOPackage:()=>Gi,bytes2ms:()=>Mm,calculateScaleResolutionDownNumber:()=>Ho,concatArrayBuffers:()=>ka,convertObjectNumberToInt:()=>Js,copyProperties:()=>Dm,deepClone:()=>Gr,deepCloneBasic:()=>ya,deepMerge:()=>ei,delay:()=>Ke,fibonacci:()=>Jr,formatedTime:()=>Fm,getConstructorName:()=>xo,getContainerFromElement:()=>Vm,getEnv:()=>bm,getFirst16Bits:()=>Hm,getInternalVersion:()=>xm,getLast16Bits:()=>Pa,getLoggerUrl:()=>Wi,getMediaStreamTrackInfo:()=>Oa,getMuteStateFromFlag:()=>Kt,getNetworkType:()=>ba,getNumNetworkType:()=>qr,getReconnectionTimeout:()=>Zt,getStringByteLength:()=>qs,getTurnServer:()=>Um,getUint32Version:()=>Na,getValueType:()=>Me,getViewListFromView:()=>Fo,glog:()=>_l,ipv4ToUint32:()=>Vo,isArray:()=>Ie,isAudioWorkletSupported:()=>wm,isBoolean:()=>he,isConstructor:()=>jr,isEmpty:()=>Uo,isFunction:()=>le,isLangChinese:()=>Yt,isMediaStreamTrack:()=>km,isNumber:()=>z,isObject:()=>yt,isOverseaSdkAppId:()=>Ut,isPlainObject:()=>dt,isPortrait:()=>gl,isPromise:()=>Tr,isRemoteTrack:()=>Pm,isRotate90Or270:()=>bt,isSetSinkIdSupported:()=>Lm,isString:()=>ie,isUndefined:()=>T,loadImage:()=>Bo,loadVideo:()=>Bm,ms2bytes:()=>Om,ms2samples:()=>fl,normalizeUrl:()=>Ma,performanceNow:()=>U,promiseAny:()=>Xr,samples2ms:()=>pl,setNetworkTypeFromWebRTC:()=>va,stringify:()=>_t,stringifyIncludeValue:()=>Gs,throttlePromise:()=>Da});var hS=[-1,-1,1,-1,-1,1,1,1],mS=[0,0,1,0,0,1,1,1];var kr=class kr extends J{constructor(e,t){super();this.context=e;d(this,"name");d(this,"input");d(this,"output");d(this,"texture");d(this,"ctx2d",null);d(this,"fbo");d(this,"width",0);d(this,"height",0);d(this,"x",0);d(this,"y",0);d(this,"program");d(this,"vertexShader");d(this,"fragmentShader");d(this,"totalFrames",0);d(this,"dropFrames",0);d(this,"matchInputSize",!0);d(this,"texCoordBuffer");d(this,"positionBuffer");d(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});d(this,"cost",0);d(this,"_canvas",null);d(this,"_image");d(this,"log");if(this.context.on("disconnect",this.close,this),this.name=t.name,this.log=t.logger,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof Xe){e.ctx&&t.create2d&&(typeof OffscreenCanvas=="function"&&et!==16?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);return}try{let r=e.ctx;this.texCoordBuffer=this.createBuffer(mS),this.positionBuffer=this.createBuffer(hS),t.createTexture!==!1&&(this.texture=r.createTexture(),this.useTexture(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.pixelStorei(r.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=r.createFramebuffer(),this.useBufferFrame(),this.useTexture(),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,this.width,this.height,0,r.RGBA,r.UNSIGNED_BYTE,null),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(r.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(r.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(r){this.context.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${r.message||r}`}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,r=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),r}connect(e,...t){return e.addInput(this,...t),this.output=e,e}addInput(e,...t){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();if(this.context instanceof Be&&this.render(e)||this.context instanceof Xe&&this.render2d(e))this.totalFrames++;else return!1;return this.cost=Date.now()-t,!0}render2d(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?this.draw2d(this.input.image,0,0,this.width,this.height):!1}update(e=0){var t;(t=this.output)==null||t.update(e)}disconnect(...e){var t;(t=this.output)==null||t.removeInput(this,...e),delete this.output}removeInput(e,...t){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),(e=this.output)==null||e.removeInput(this),delete this.output,(t=this.input)==null||t.disconnect(),this.context instanceof Be){let r=this.context.ctx;r.deleteBuffer(this.texCoordBuffer),r.deleteBuffer(this.positionBuffer),this.fbo&&r.deleteFramebuffer(this.fbo),this.texture&&r.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&r.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&r.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&r.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let t=this.context.ctx;e.forEach((r,s)=>{r&&(t.activeTexture(t.TEXTURE0+s),t.bindTexture(t.TEXTURE_2D,r))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,r=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,r),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),r}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,e),r.bufferData(r.ARRAY_BUFFER,new Float32Array(t),r.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((r,s)=>{t.enableVertexAttribArray(s),t.bindBuffer(t.ARRAY_BUFFER,r),t.vertexAttribPointer(s,2,t.FLOAT,!1,0,0)})}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(!(this.width===e&&this.height===t)){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let r=this.context.ctx;r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e,t,0,r.RGBA,r.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let r=this.context.ctx;r.drawArrays(r.TRIANGLE_STRIP,0,4)}draw2d(e,t,r,s,n,a,c,l,u){let m=!T(a)&&!T(c)&&!T(l)&&!T(u);return this.ctx2d&&e?(e instanceof ImageData?(m?this.ctx2d.putImageData(e,t,r,a,c,l,u):this.ctx2d.putImageData(e,t,r),this.emit(kr.RENDER,this.ctx2d.canvas)):(m?this.ctx2d.drawImage(e,a,c,l,u,t,r,s,n):this.ctx2d.drawImage(e,t,r,s,n),this.emit(kr.RENDER,e)),typeof VideoFrame!="undefined"&&e instanceof VideoFrame&&e.close(),!0):!1}drawBackGround2d(e){this.ctx2d&&(this.ctx2d.save(),this.ctx2d.fillStyle=e,this.ctx2d.fillRect(0,0,this.width,this.height),this.ctx2d.restore())}getInfo(){var m;let{totalFrames:e,x:t,y:r,width:s,height:n,name:a,cost:c}=this,l=Date.now(),u=(e-this.lastInfo.totalFrames)/((l-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:s,height:n,timestamp:l,fps:u,name:a,cost:c},O({parent:(m=this.input)==null?void 0:m.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,r=t.createTexture();return this.useTextures(r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),r}};d(kr,"RENDER","render"),M([ye(J.INIT,"connected",{sync:!0})],kr.prototype,"connect",1),M([ye("connected",J.INIT,{ignoreError:!0,sync:!0})],kr.prototype,"disconnect",1),M([ye([],"closed",{sync:!0})],kr.prototype,"close",1);var Ue=kr;var pS=de(Vu(250),Fn(()=>performance.now()),rr());var _f=o=>i=>{let e=performance.now();de(pS,Hc(t=>t-e<o),or(1))(i)};var _S=[0,1,1,1,0,0,1,0],fo=class extends Ue{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));d(this,"_intervalId",0);d(this,"_sequence",0);d(this,"checkGLError",!1);d(this,"checkVisibilityChange");e instanceof Xe?this.ctx2d=e.ctx||null:e.available&&(t!=null&&t.mirrorUpAndDown)&&this.setTexBuffer(_S)}start(e){this.log.info(`${this.name} start render ${e} fps`),oe.clearTask(this._intervalId),this._intervalId=oe.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(oe.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof Be){let r=this.context.ctx.getError();r&&this.context.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${r}`}))}},{fps:this.context.frameRate})}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),this.emit(Ue.RENDER,this.context._canvas),!0):!1}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}update(e=0){this.state!=="closed"&&(this._intervalId&&(oe.clearTask(this._intervalId),this._intervalId=0,e===1&&(this.log.info(`${this.name} use requestVideoFrameCallback`),this.checkVisibilityChange=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",this.checkVisibilityChange))},document.addEventListener("visibilitychange",this.checkVisibilityChange))),this.requestFrame(this._sequence++))}removeInput(e){super.removeInput(e),oe.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),oe.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},fs=class extends fo{constructor(e,t){super(e,t);d(this,"_videoTrack");d(this,"_muteOb");d(this,"_closedOb",ce(this,"closed"));d(this,"_subscription");d(this,"_canvasContainer");Number(Xi)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e.canvas.captureStream().getVideoTracks(),this._muteOb=ce(this._videoTrack,"mute"),de(ce(this._videoTrack,"ended"),ke(this._closedOb),Te(()=>{this.context.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=de(this._muteOb,ke(this._closedOb),mo(_f(5e3)),$t(()=>{var e;return!!((e=this._videoTrack)!=null&&e.muted)&&!document.hidden}),Te(()=>{this.context.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var e;(e=this._subscription)==null||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info(`${this.name} put canvas to body`),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,t;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack,(t=this._canvasContainer)==null||t.remove()}},Yc=class extends fs{render(i){var t;let e=!!((t=this.input)!=null&&t.requestFrame(i));if(this.context._canvas2d){let r=this.context._canvas2d.getContext("2d");r.clearRect(0,0,this.context._canvas2d.width,this.context._canvas2d.height),r.drawImage(this.context._canvas,0,0,this.context._canvas2d.width,this.context._canvas2d.height)}return e}};var Zc=class extends fs{constructor(e,t,r){super(e,{name:"smallDestination",logger:r});this.resolution=t}resize(e,t){let r,s=e*t,n=this.resolution.width*this.resolution.height;this.log.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),s>n?r=s/n:(this.log.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${t} small: ${this.resolution.width} * ${this.resolution.height}`),r=s/(160*120)),super.resize(e/Math.sqrt(r),t/Math.sqrt(r))}};var $n=class extends Ue{constructor(e,t){super(e,O({name:"imageSource"},t));d(this,"_lastImage");d(this,"_totalFrames",0);d(this,"_autoResize",!1);d(this,"_canvasRendered");d(this,"videoCallbackId",0);d(this,"waitingFirstFrame",!0);d(this,"shouldUpdate",!0);this._autoResize=(t==null?void 0:t.autoResize)!==!1,et===16&&(this._canvasRendered=ot(),de(this._canvasRendered,xn(this._image),Mr(r=>r instanceof HTMLCanvasElement?ce(r,"rendered"):Vn()),ke(ce(this,"closed")),Te(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let e=this.image;this.videoCallbackId&&e.cancelVideoFrameCallback(this.videoCallbackId),Ki()&&!document.hidden&&(this.videoCallbackId=e.requestVideoFrameCallback((t,r)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=r.presentedFrames,this.update(1))}))}_render(e,t){var a;let{width:r,height:s}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:r,videoHeight:s}=n,!r||!s)return!1;n.width=r,n.height=s}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if({width:r,height:s}=n,n!==this._lastImage)this._lastImage=n;else if(r===this.width&&s===this.height)return!0}else n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas?({width:r,height:s}=n,this._lastImage=n):typeof VideoFrame!="undefined"&&n instanceof VideoFrame&&({displayWidth:r,displayHeight:s}=n,(a=this._lastImage)==null||a.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===r&&this.height===s&&this.totalFrames){if(t){this.useTexture();let c=this.context.ctx;c.texSubImage2D(c.TEXTURE_2D,0,0,0,c.RGBA,c.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();let c=this.context.ctx;c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,n)}this.resize(r,s)}return!0}get image(){return this._image}set image(e){var t;(t=this._canvasRendered)==null||t.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},Wn=class extends $n{constructor(e,t,r){super(e,r);this._player=t;this.name="videoPlayerSource",de(ce(this._player,ue.PLAYER_STATE_CHANGED),ke(ce(this,"closed")),$t(({state:s})=>s==="PLAYING"),Te(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},Wt=class extends Wn{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(i,e,t){super(i,new it({id:t.name,track:e,muted:!0,container:null,objectFit:"contain",log:t.logger}),t),this.name="videoTrackSource",this._player.play()}replaceTrack(i){this.waitingFirstFrame=!0,this._player.setTrack(i),this._player.play()}close(){super.close(),this._player.stop()}},Kc=class extends Ue{constructor(e,t,r){super(e,L(O({name:"textSource"},r),{create2d:!0}));d(this,"hasChange",!0);d(this,"content","");this.ctx2d.textBaseline="top",this.content=t.content||"",t.font&&(this.font=t.font),t.color&&(this.color=t.color)}set font(e){this.ctx2d&&(this.ctx2d.font=e,this.hasChange=!0)}get font(){var e;return((e=this.ctx2d)==null?void 0:e.font)||""}set color(e){this.ctx2d&&(this.ctx2d.fillStyle=e,this.hasChange=!0)}get color(){var e;return((e=this.ctx2d)==null?void 0:e.fillStyle)||""}render2d(e){return this.ctx2d&&this.hasChange?(this.ctx2d.clearRect(0,0,this.width,this.height),this.drawMultilineText(0,0),this.hasChange=!1,!0):!1}render(e){return!1}resize(e,t){if(!this.ctx2d)return;let{color:r,font:s}=this;super.resize(e,t),this.color=r,this.font=s}drawMultilineText(e=0,t=0,r=1.2){if(!this.ctx2d)return;let s=this.ctx2d.measureText(this.content);t+=s.fontBoundingBoxAscent||s.actualBoundingBoxAscent||0;let n=this.font.match(/(\d+)px/),c=(n?parseInt(n[1],10):16)*r,l=this.content.split(`
|
|
34
34
|
`);for(let u=0;u<l.length;u++)this.ctx2d.fillText(l[u],e,t+u*c)}};var TS=`
|
|
35
35
|
// \u9876\u70B9\u7740\u8272\u5668
|
|
36
36
|
attribute vec4 a_position;
|
|
@@ -49,9 +49,9 @@ uniform sampler2D u_texture;
|
|
|
49
49
|
|
|
50
50
|
void main() {
|
|
51
51
|
gl_FragColor = texture2D(u_texture, v_texCoord);
|
|
52
|
-
} `;var _o=class extends J{constructor(e){super();d(this,"frameRate");d(this,"_canvas");d(this,"log");d(this,"hasAlpha",!1);d(this,"name");d(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}get canvas(){return this._canvas}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new Wt(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new fs(this,e)}createVideoImageSource(e,t){return new $n(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new Wn(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}createTextSource(e,t){return new Kc(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};d(_o,"_ids",0);var SS={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},_s=class _s extends _o{constructor(){super(...arguments);d(this,"defaultProgam");d(this,"defaultVShader");d(this,"defaultFShader");d(this,"ctx");d(this,"_canvas2d")}get canvas(){return this._canvas2d||this._canvas}create(e=!1){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${_o._ids++}`),e&&(this._canvas2d=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",SS),!this.ctx)throw new D({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,TS),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,ES),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let t="";return e&&(t=e.message,this.error=e,v.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info(`video context destroy${t}`?`: ${t}`:""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;(t=this.ctx)==null||t.viewport(0,0,e,this.height),super.width=e,this._canvas2d&&(this._canvas2d.width=e)}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e,this._canvas2d&&(this._canvas2d.height=e)}setSize(e,t){var r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t),this._canvas2d&&(this._canvas2d.width=e,this._canvas2d.height=t)}createShader(e,t){let r=this.ctx,s=r.createShader(e);return r.shaderSource(s,t),r.compileShader(s),s}createProgram(e,t){let r=this.ctx,s=r.createProgram();return r.attachShader(s,e),r.attachShader(s,t),r.linkProgram(s),r.getProgramParameter(s,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(s)),s}};d(_s,"UNAVAILABLE","unavailable"),M([ye(J.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),v.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),v.addSuccessEvent({key:512700})}})],_s.prototype,"create",1),M([ye("created",J.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(_s.UNAVAILABLE,e),this.removeAllListeners()}})],_s.prototype,"destroy",1);var Be=_s,Xe=class extends _o{constructor(){super(...arguments);d(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${_o._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha,willReadFrequently:e.willReadFrequently}),!this.ctx)throw new D({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",()=>{this.log.error("2d context lost")}),this._canvas.addEventListener("contextrestored",()=>{this.log.warn("2d context restored")})}destroy(e){let t="";e&&(t=e.message,this.error=e,v.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info(`video context destroy ${t?`: ${t}`:""}`),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),v.addSuccessEvent({key:512703})}};M([ye(J.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),v.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),v.addSuccessEvent({key:512701})}})],Xe.prototype,"create",1),M([ye("created",J.INIT,{ignoreError:!0,sync:!0})],Xe.prototype,"destroy",1);function IS(o,i,e,t,r,s=!1){s&&([e,t]=[t,e]);let n={sWidth:o,sHeight:i,dWidth:e,dHeight:t,sx:0,sy:0,dx:0,dy:0};if(o===0||i===0)return n;switch(r){case void 0:case"fill":break;case"contain":{let a=Math.min(e/o,t/i);n.dWidth=o*a,n.dHeight=i*a,n.dx=(e-n.dWidth)/2,n.dy=(t-n.dHeight)/2;break}case"cover":{let a=Math.max(e/o,t/i),c=e/a,l=t/a;n.sx=(o-c)/2,n.sy=(i-l)/2,n.sWidth=c,n.sHeight=l;break}}return n}var Ih=class{constructor(i,e){this.node=i;this.layout=e;d(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}get fillMode(){return this.layout.fillMode}get rotation(){return this.layout.rotation}get hidden(){return!!this.layout.hidden}},gs=class extends Ue{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t});d(this,"inputs",[]);d(this,"backgroundColor","black")}addInput(e,t){let r=0,s=this.inputs.length;for(;r<s;){let a=Math.floor((r+s)/2);if(this.inputs[a].layout.zIndex<t.zIndex)r=a+1;else if(this.inputs[a].layout.zIndex>t.zIndex)s=a;else throw new Error(`input already exists at zIndex ${t.zIndex}`)}let n=new Ih(e,t);this.inputs.splice(r,0,n)}changeInputLayout(e,t){let r=this.inputs.findIndex(g=>g.node===e);if(r<0)return;let{x:s,y:n,width:a,height:c,zIndex:l,fillMode:u,rotation:m,hidden:h}=t;if(!T(l)&&this.inputs.some(g=>g.layout.zIndex===l&&g.node!==e))throw new Error(`input already exists at zIndex ${t.zIndex}`);let _=this.inputs[r];T(s)||(_.layout.x=s),T(n)||(_.layout.y=n),T(a)||(_.layout.width=a),T(c)||(_.layout.height=c),T(m)||(_.layout.rotation=m),T(h)||(_.layout.hidden=h),u&&(_.layout.fillMode=u),!T(l)&&l!==_.layout.zIndex&&(_.layout.zIndex=l,this.inputs.sort((g,E)=>g.layout.zIndex-E.layout.zIndex))}hasInput(e){return this.inputs.some(t=>t.node===e)}hasNoInput(){return this.inputs.length===0}resize(e,t){if(!this.matchInputSize){super.resize(e,t);return}let r=this.inputs.reduce((s,n)=>n?Object.assign(s,{width:Math.max(s.width,n.right),height:Math.max(s.height,n.bottom)}):s,{width:0,height:0});super.resize(r.width,r.height),this.context instanceof Be&&this.inputs.forEach(s=>{if(s){let n=this.layout2texCoords(s);s.positionBuffer?this.changeBufferData(s.positionBuffer,n):s.positionBuffer=this.createBuffer(n)}})}connect(e,...t){return super.connect(e,...t),this.drawBackGround2d(this.backgroundColor),this.matchInputSize&&this.resize(0,0),e}removeInput(e){this.inputs=this.inputs.filter(t=>t.node!==e),this.inputs.length===0&&this.drawBackGround2d(this.backgroundColor)}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),this.inputs.reduce((s,n)=>n.node.requestFrame(e)||s,!1)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let s=0;s<this.inputs.length;s++){let n=this.inputs[s];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){if(this.inputs.forEach(t=>t.node.requestFrame(e)),this.ctx2d){this.drawBackGround2d(this.backgroundColor);for(let t=0;t<this.inputs.length;t++){let r=this.inputs[t];if(r.hidden)continue;let s=IS(r.node.width,r.node.height,r.width,r.height,r.fillMode,bt(r.rotation));this.draw2d(r.node.image,r.x+s.dx,r.y+s.dy,s.dWidth,s.dHeight,s.sx,s.sy,s.sWidth,s.sHeight)}return!0}return!1}debugLayout(e,t,r,s,n=!1){this.ctx2d&&(n&&([r,s]=[s,r]),this.ctx2d.save(),this.ctx2d.strokeStyle="red",this.ctx2d.lineWidth=2,this.ctx2d.strokeRect(e,t,r,s),this.ctx2d.restore())}getInfo(){let{totalFrames:e,x:t,y:r,width:s,height:n,name:a}=this,c=Date.now(),l=(e-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:s,height:n,timestamp:c,fps:l,name:a},O({parent:this.inputs.filter(u=>u).map(u=>u.node.getInfo())},this.lastInfo)}removeAllInputs(){this.inputs.forEach(e=>{var t;if(e.node.disconnect(),e.positionBuffer&&this.context instanceof Be)try{(t=this.context.ctx)==null||t.deleteBuffer(e.positionBuffer)}catch(r){}})}close(){super.close(),this.removeAllInputs()}};var AS=[1,0,0,0,1,1,0,1],Gt=class extends Ue{constructor(e,t,r,s){super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:t});d(this,"mirror",!1);d(this,"rotation",0);if(r&&(this.mirror=r),s&&(this.rotation=s),e instanceof Be)try{this.setTexBuffer(AS)}catch(n){e.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${n.message||n}`}))}}draw2d(e,t,r,s,n){if(this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height),this.ctx2d.save(),this.mirror&&(this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0)),this.rotation===90?(this.ctx2d.translate(s,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(n/s,s/n)):this.rotation===180?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):this.rotation===270&&(this.ctx2d.translate(0,n),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(n/s,s/n));let a=super.draw2d(e,t,r,s,n);return this.ctx2d.restore(),a}return!1}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}resize(e,t){bt(this.rotation)&&([e,t]=[t,e]),super.resize(e,t)}};var go=class extends pi{constructor(e,t=4){super(t,it);d(this,"inputLocalVideoTracks",new Map);d(this,"inputLocalScreenTracks",new Map);d(this,"cameraNodeMap",new Map);d(this,"screenNodeMap",new Map);d(this,"textNodeMap",new Map);d(this,"imageNodeMap",new Map);d(this,"videoNodeMap",new Map);d(this,"endedIds",new Set);d(this,"videoContext");d(this,"mixNode");d(this,"destination");d(this,"manager");d(this,"stat");d(this,"_checkId",0);d(this,"autoSetFps",!0);this.manager=e,this.log.id+="mix",this.create2dVideoContext(),this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(Ue.RENDER,r=>{this.emit("render",r)}),this.mixNode=new gs(this.videoContext,this.log),this.mixNode.matchInputSize=!1}listenDeviceChange(){throw new Error("Method not implemented.")}enablePrintDetail(e=2e3){this._checkId=oe.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new Xe({frameRate:15,logger:this.log,name:"mix-ctx"}),this.videoContext.create({alpha:!1})}setFps(e){this.autoSetFps=!1,this.videoContext.frameRate=e;for(let t of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])t.shouldUpdate=!1;setTimeout(()=>{var t;return(t=this.destination)==null?void 0:t.start(this.videoContext.frameRate)},500)}setFpsAuto(){var s;if(!this.autoSetFps)return;for(let n of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])n.shouldUpdate=!1;let e=null,t=0,r=!0;for(let[n,a]of this.inputLocalVideoTracks)if(a.profile.frameRate>t){if(this.endedIds.has(n)){let c=this.cameraNodeMap.get(n);c&&c.image.cancelVideoFrameCallback(c.videoCallbackId);continue}t=a.profile.frameRate,e=n}for(let[n,a]of this.inputLocalScreenTracks)if(a.profile.frameRate>t){if(this.endedIds.has(n)){let c=this.screenNodeMap.get(n);c&&c.image.cancelVideoFrameCallback(c.videoCallbackId);continue}t=a.profile.frameRate,e=n,r=!1}if(e!==null){let n=r?this.cameraNodeMap.get(e):this.screenNodeMap.get(e);n&&(n.shouldUpdate=!0,n.tryVideoFrameCallback()),this.log.info("set mix fps: ",t)}else(s=this.destination)==null||s.start(this.videoContext.frameRate),this.log.info("fallback to timer, fps: ",this.videoContext.frameRate)}setMixBackground(e){this.mixNode&&(this.mixNode.backgroundColor=e)}resizeMixCanvas(e,t){var r;(r=this.mixNode)==null||r.resize(e,t)}startMix(){return p(this,null,function*(){var e;if(!this.mixNode||!this.destination)throw new Error("can't mix without necessary conditions");this.mixNode.disconnect(),this.mixNode.connect(this.destination),Ft&&this.player.setCanvas(this.videoContext._canvas),this.setOutputMediaStreamTrack(this.destination.videoTrack),(e=this.manager)==null||e.changeInput(this)})}addCameraSource(e,t,r){if(this.inputLocalVideoTracks.has(e)||this.cameraNodeMap.has(e))throw new Error(`There is already a cameraSource with the same ID: ${e}`);let{mediaTrack:s}=t;if(!s)throw new Error("no mediaTrack, add cameraSource failed");t.recaptureMode=1,tt(this,be).add("videoInputRemoved",a=>{a.deviceId===t.deviceId&&(this.endedIds.add(e),this.setFpsAuto())}),t.on("output-media-track-changed",()=>{this.endedIds.delete(e),this.updateCameraSource(e,r,t.mediaTrack)});let n;et===16&&s instanceof CanvasCaptureMediaStreamTrack?n=this.videoContext.createVideoImageSource(s.canvas,{name:"cameraCanvasSource",logger:this.log}):n=this.videoContext.createVideoTrackSource(s,"cameraNodeSource"),n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r,"cover"),this.inputLocalVideoTracks.set(e,t),this.cameraNodeMap.set(e,n),this.setFpsAuto()}addScreenSource(e,t,r){if(this.inputLocalScreenTracks.has(e)||this.screenNodeMap.has(e))throw new Error(`There is already a screenSource with the same ID: ${e}`);let{mediaTrack:s}=t;if(!s)throw new Error("no mediaTrack, add cameraSource failed");let n=this.videoContext.createVideoTrackSource(s,"screenNodeSource");n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r),this.inputLocalScreenTracks.set(e,t),this.screenNodeMap.set(e,n),this.setFpsAuto()}addTextSource(e){let{id:t,content:r="",font:s,color:n,layout:a}=e;if(this.textNodeMap.has(t))throw new Error(`There is already a textSource with the same ID: ${t}`);let c=this.videoContext.createTextSource({content:r,font:s,color:n});c.resize(a.width,a.height),this._connectMix(c,a),this.textNodeMap.set(t,c)}addImageSource(e,t,r){if(this.imageNodeMap.has(e))throw new Error(`There is already a imageSource with the same ID: ${e}`);let s=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});s.resize(t.width,t.height),this._connectMix(s,r),this.imageNodeMap.set(e,s)}addVideoSource(e,t,r){if(this.videoNodeMap.has(e))throw new Error(`There is already a videoSource with the same ID: ${e}`);let s=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});s.resize(t.videoWidth,t.videoHeight),s.shouldUpdate=!1,this._connectMix(s,r),this.videoNodeMap.set(e,s)}updateCameraSource(e,t,r=null,s){let n=this.cameraNodeMap.get(e);if(n){if(r){if(et===16&&r instanceof CanvasCaptureMediaStreamTrack)if(n instanceof Wt){let l=n.output;n.close(),n=this.videoContext.createVideoImageSource(r.canvas,{name:"cameraCanvasSource",logger:this.log}),n.connect(l),this.cameraNodeMap.set(e,n)}else n.image=r.canvas;else if(n instanceof Wt)n.replaceTrack(r);else{let l=n.output;n.close(),n=this.videoContext.createVideoTrackSource(r,"cameraNodeSource"),n.connect(l),this.cameraNodeMap.set(e,n)}let{width:a,height:c}=r.getSettings();a&&c&&n.resize(a,c)}s&&n.resize(s.width,s.height),(s||r)&&this.setFpsAuto(),this._changeMixLayout(n,t)}}updateScreenSource(e,t){let r=this.screenNodeMap.get(e);r&&this._changeMixLayout(r,t)}updateTextSource(e){let{id:t,content:r,font:s,color:n,layout:a}=e,c=this.textNodeMap.get(t);c&&(T(r)||(c.content=r),T(s)||(c.font=s),T(n)||(c.color=n),c.resize(a.width,a.height),this._changeMixLayout(c,a))}updateImageSource(e,t,r){let s=this.imageNodeMap.get(e);s&&(r&&(s.image=r,s.resize(r.width,r.height)),this._changeMixLayout(s,t))}updateVideoSource(e,t,r){let s=this.videoNodeMap.get(e);if(s){if(r){let n=s.image;n instanceof HTMLVideoElement&&this.stopVideoElement(n),s.image=r,s.resize(r.videoWidth,r.videoHeight)}this._changeMixLayout(s,t)}}_connectMix(e,t,r="contain"){if(!this.mixNode)return;let{mirror:s,rotation:n}=t;e.disconnect();let a=new Gt(this.videoContext,this.log,s,n);a=e.connect(a),t.fillMode||(t.fillMode=r),a.connect(this.mixNode,t)}_changeMixLayout(e,t){if(!this.mixNode)return;let{mirror:r,rotation:s}=t,n=e.output||e;n instanceof Gt&&(T(r)||(n.mirror=r),T(s)||(n.rotation=s),n.resize(e.width,e.height)),this.mixNode.changeInputLayout(n,t)}removeCameraSource(e){let t=this.inputLocalVideoTracks.get(e);if(!t)return;t.close(),this.inputLocalVideoTracks.delete(e);let r=this.cameraNodeMap.get(e);r&&(r.output instanceof Gt&&r.output.close(),r.close(),this.cameraNodeMap.delete(e)),this.checkAfterRemove(!0)}removeScreenSource(e){let t=this.inputLocalScreenTracks.get(e);if(!t)return;t.close(),this.inputLocalScreenTracks.delete(e);let r=this.screenNodeMap.get(e);r&&(r.output instanceof Gt&&r.output.close(),r.close(),this.screenNodeMap.delete(e)),this.checkAfterRemove(!0)}removeTextSource(e){let t=this.textNodeMap.get(e);t&&(t.output instanceof Gt&&t.output.close(),t.close(),this.textNodeMap.delete(e)),this.checkAfterRemove()}removeImageSource(e){let t=this.imageNodeMap.get(e);t&&(t.output instanceof Gt&&t.output.close(),t.close(),this.imageNodeMap.delete(e)),this.checkAfterRemove()}removeVideoSource(e){let t=this.videoNodeMap.get(e);t&&(t.output instanceof Gt&&t.output.close(),t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image),t.close(),this.videoNodeMap.delete(e)),this.checkAfterRemove()}checkAfterRemove(e=!1){e&&this.setFpsAuto()}stopVideoElement(e){e.pause(),e.src="",e.srcObject=null,e.remove()}close(){var e;super.close(),oe.clearTask(this._checkId),(e=this.videoContext)==null||e.destroy(),delete this.mixNode,delete this.destination;for(let t of[...this.inputLocalVideoTracks.values(),...this.inputLocalScreenTracks.values()])t.close();this.inputLocalVideoTracks.clear(),this.inputLocalScreenTracks.clear(),this.cameraNodeMap.clear(),this.screenNodeMap.clear(),this.textNodeMap.clear(),this.imageNodeMap.clear(),Le(this);for(let t of this.videoNodeMap.values())t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image);this.videoNodeMap.clear(),this.log.info("localMixVideoTrack close, stop mix")}};var ed=cn();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:ed,exposeOrigin:!0,permittedOrigins:["*"]})}catch(o){}var CS=function(o){return p(this,null,function*(){let i=null,e=bS(o);R.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);o.systemAudio&&t.getAudioTracks().length===0&&(Zo&&qe<74||Re||K)&&R.warn("Your browser not support capture system audio");let r=t.getVideoTracks()[0];if(r){if(o.frameRate)try{yield r.applyConstraints({frameRate:{min:o.frameRate,ideal:o.frameRate},width:o.width,height:o.height})}catch(s){R.warn(`screen applyConstraints failed: ${s}`)}o.captureElement&&(yield RS(r,o.captureElement))}if(o.audio){let s=yS(o);R.info(`getUserMedia with constraints: ${JSON.stringify(s)}`),i=yield navigator.mediaDevices.getUserMedia(s),t.addTrack(i.getAudioTracks()[0])}return t})};function RS(o,i){return p(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&le(o.cropTo))try{if(!(((e=o.getCaptureHandle())==null?void 0:e.handle)===ed))return;let r=yield CropTarget.fromElement(i);yield o.cropTo(r)}catch(t){R.warn(`cropTo target failed ${t}`)}})}function yS(o){let i={echoCancellation:o.echoCancellation,autoGainControl:o.autoGainControl,noiseSuppression:o.noiseSuppression,sampleRate:o.sampleRate,channelCount:o.channelCount};return T(o.microphoneId)||(i.deviceId=o.microphoneId),{audio:i,video:!1}}function bS(o){let i={preferCurrentTab:o.preferDisplaySurface==="current-tab"||!!o.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Re?{max:o.width}:{ideal:o.width,max:o.width},height:Re?{max:o.height}:{ideal:o.height,max:o.height},frameRate:o.frameRate,displaySurface:o.preferDisplaySurface||"monitor"};if(i.video=e,o.systemAudio){let{echoCancellation:t=!0,noiseSuppression:r=!1,autoGainControl:s=!1}=o;i.audio={echoCancellation:t,noiseSuppression:r,autoGainControl:s,sampleRate:48e3}}return i}var gf=CS;var Pt=class extends je{constructor(e){super(e,2);d(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});d(this,"objectFit","contain");d(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}get isShareCurrentTab(){var e,t;try{return ed===((t=(e=this.mediaTrack)==null?void 0:e.getCaptureHandle())==null?void 0:t.handle)}catch(r){return}}capture(u){return p(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:r,noiseSuppression:s,audioTrack:n,videoTrack:a,captureElement:c,preferDisplaySurface:l}){try{let m;return a||n?(m=new MediaStream,a&&m.addTrack(a),n&&m.addTrack(n)):(m=yield gf({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:r,noiseSuppression:s,captureElement:c,preferDisplaySurface:l}),this.sourceTrack=m.getVideoTracks()[0]),yield this.setInputMediaStreamTrack(m.getVideoTracks()[0]),m}catch(m){throw this.log.error(`getDisplayMedia error observed ${m}`),m instanceof D?m:new D({code:I.INITIALIZE_FAILED,name:m.name,message:m.message})}})}switchDevice(e){return p(this,null,function*(){throw new Error("Method not implemented.")})}};M([Ct(function(e){this.setContentHint(e.contentHint||"detail")})],Pt.prototype,"capture",1);var To=class extends kt{constructor(i){super(i),this._log.id=`s-${this._log.id}`,this.isScreen=!0}addAudioProcessor(i,e,t){this.pipeline.silentNode.setNode(t),this.pipeline.mixNode.setNode(e),this.pipeline.aec.setNode(i),this.enableTrackAEC(!1)}removeAudioProcessor(i){this.pipeline.aec.node===i&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};var vS='registerProcessor("dumper",class extends AudioWorkletProcessor{constructor(e){super(),this.sourceSampleRate=e.processorOptions.sourceSampleRate||48e3,this.targetSampleRate=e.processorOptions.targetSampleRate||48e3,this.port.onmessage=e=>{this.port2=e.data.port}}process(e){return(this.port2||this.port).postMessage(this.resampleAll(e,this.sourceSampleRate,this.targetSampleRate)),!0}resampleAll(r,s,a){if(s===a)return r;var o=[];for(let t=0;t<r.length;t++){o[t]=[];for(let e=0;e<r[t].length;e++)o[t][e]=this.resample(r[t][e],s,a)}return o}resample(t,e,r){if(e===r)return t;var s=Math.round(t.length*(this.targetSampleRate/this.sourceSampleRate)),a=new Float32Array(s),o=(t.length-1)/(s-1);a[0]=t[0];for(let e=1;e<s-1;e++){var l=e*o,p=Math.floor(l),h=Math.ceil(l);a[e]=t[p]+(t[h]-t[p])*(l-p)}return a[s-1]=t[t.length-1],a}});',Ah;function Gn(o,i=48e3,e=1,t){return p(this,null,function*(){let r=Ee("dump");Ah||(Ah=tr(r,URL.createObjectURL(new Blob([vS],{type:"application/javascript"})))),yield Ah;let s=r.sampleRate,n=new AudioWorkletNode(r,"dumper",{numberOfInputs:o.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:s,targetSampleRate:i}});return n.channelCountMode="explicit",n.channelCount=e,t&&n.port.postMessage({port:t},[t]),o.forEach((a,c)=>a.connect(n,0,c)),new ReadableStream({start(a){n.port.onmessage=c=>{a.enqueue(c.data)}},cancel(){o.forEach(a=>a.disconnect(n)),n.port.close()}})})}var td=class extends bc{constructor(e){super();this.room=e;d(this,"_localAudioTrack");d(this,"_localScreenAudioTrack");d(this,"log");d(this,"denoiser");d(this,"voiceChanger");d(this,"mixChangedDebounce");d(this,"audioProcessor");d(this,"encodePipeline",[]);d(this,"decodePipeline",[]);d(this,"getPCMAbortCtrlMap",new Map);d(this,"audioFrameEventConfigMap",new Map);d(this,"audioReferenceMap",new Map);d(this,"isLocalAudioNeedAudioProcess",!1);d(this,"isScreenAudioNeedAudioProcess",!1);this.log=R.createLogger({parent:e==null?void 0:e.getLogger(),id:"am",userId:e==null?void 0:e.userId,sdkAppId:e==null?void 0:e.sdkAppId}),this.installEvent()}get localAudioTrack(){return this._localAudioTrack}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}get _localScreenAudioPipeline(){var e;return(e=this._localScreenAudioTrack)==null?void 0:e.pipeline}dump(e){var u,m;if(!this._localAudioTrack)return;let t=[],r=[];(u=this._localAudioPipline)!=null&&u.source.node&&(t.push(this._localAudioPipline.source.node),r.push("mic")),(m=this._localAudioPipline)!=null&&m.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),r.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),r.push("mix")),this.log.info(`dump audio track ${r}, duration: ${e}`);let s=new AbortController,n=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),s.abort("timeout")},e*1e3),c=()=>{for(let h=0;h<r.length;h++){let _=URL.createObjectURL(new Blob(n[h])),g=document.createElement("a");g.href=_,g.download=`${r[h]}.pcm`,g.style.display="none",document.body.appendChild(g),g.click(),URL.revokeObjectURL(_),g.remove()}clearTimeout(a),s.abort("download")},l=Gn(t).then(h=>h.pipeTo(new WritableStream({write(_){_.forEach((g,E)=>n[E]=n[E]?n[E].concat(g[0]):[g[0]])}}),s).catch(_=>c));return{then:l.then.bind(l),download:c}}getPCM(e,t){var k,re,P;if(typeof WritableStream=="undefined"){this.log.warn("getPCM failed: browser not support WritableStream");return}let{enable:r,sampleRate:s=48e3,channelCount:n=1,port:a}=(t===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!r)return;this.log.info(`getPCM ${t||"local"}`);let c=Math.floor(s*.04),l=new Float32Array(c),u=new Float32Array(c),m,h,_=0,g=new AbortController,E=t===""?(k=this._localAudioTrack)==null?void 0:k.mediaTrack:(P=(re=this.room)==null?void 0:re.remotePublishedUserMap.get(t))==null?void 0:P.remoteAudioTrack.mediaTrack;if(!E){this.log.info(`getPCM failed: ${t||"local"} has no audio track`);return}let A=Ee().createMediaStreamSource(new MediaStream([E]));return Gn([A],s,n,a).then(Qe=>Qe.pipeTo(new WritableStream({write(N){N[0][0]&&(_+N[0][0].length>c?(l.set(N[0][0].subarray(0,c-_),_),m=N[0][0].subarray(c-_),N[0][1]&&(u.set(N[0][1].subarray(0,c-_),_),h=N[0][1].subarray(c-_)),_+=c-_):(m&&(l.set(m,_),_+=m.length,m=void 0),h&&(u.set(h,_),h=void 0),l.set(N[0][0],_),N[0][1]&&u.set(N[0][1],_),_+=N[0][0].length),_>=c&&(_=0,e({userId:t,sampleRate:s,channelCount:n,data:n===1?l:[l,u]}),l=new Float32Array(c),u=new Float32Array(c)))}}),g).catch(N=>this.log.warn(`stop getPCM reason:${N}`))),g}get hasScreenAudioTrack(){return!T(this._localScreenAudioTrack)}get hasAudioTrack(){return!T(this._localAudioTrack)}changeInput(e){var t,r;if(e instanceof To)return this._localScreenAudioTrack=e,this.isScreenAudioNeedAudioProcess&&((t=this.audioProcessor)!=null&&t.screenAudioWorkletNode)&&(e.addAudioProcessor(this.audioProcessor.screenAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((s,n)=>{e.mixAudioReference(s,n)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof kt)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&((r=this.audioProcessor)!=null&&r.localAudioWorkletNode)&&(e.addAudioProcessor(this.audioProcessor.localAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((s,n)=>{e.mixAudioReference(s,n)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof gi)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixAudioReference(e,t){var r;(r=this._localAudioTrack)==null||r.mixAudioReference(e,t)}unMixAudioReference(e){var t;(t=this._localAudioTrack)==null||t.unMixAudioReference(e)}setAudioReferenceVolume(e,t){var r;(r=this._localAudioTrack)==null||r.setAudioReferenceVolume(e,t)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var e,t;return delete this.mixChangedDebounce,Promise.all([(e=this._localAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(e){e instanceof To?delete this._localScreenAudioTrack:e instanceof kt?delete this._localAudioTrack:e instanceof gi}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}addAudioProcessor(e,t,r,s){var n;this.audioProcessor={localAudioWorkletNode:r,mixNode:e,silentNode:t,screenAudioWorkletNode:s},this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&r&&(this._localAudioTrack.addAudioProcessor(r,e,t),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localAudioTrack)==null||l.mixAudioReference(a,c)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&s&&((n=this._localScreenAudioTrack)==null||n.addAudioProcessor(s,e,t),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localScreenAudioTrack)==null||l.mixAudioReference(a,c)}))}removeDenoiser(e){var t;return delete this.denoiser,(t=this._localAudioTrack)==null?void 0:t.removeDenoiser(e)}addVoiceChanger(e,t){var r;this.voiceChanger=[e,t],(r=this._localAudioTrack)==null||r.pipeline.voiceChanger.setNode(e,t)}removeVoiceChanger(){var e;delete this.voiceChanger,(e=this._localAudioTrack)==null||e.pipeline.voiceChanger.deleteNode()}removeAudioProcessor(e,t){var r,s;delete this.audioProcessor,(r=this._localAudioTrack)==null||r.removeAudioProcessor(e),(s=this._localScreenAudioTrack)==null||s.removeAudioProcessor(t)}destroy(){this.close(),this.audioReferenceMap.clear(),this.getPCMAbortCtrlMap.forEach(e=>e==null?void 0:e.abort("destroy")),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}handleLocalTrackStarted({room:e,userId:t}){var s;if(e!==this.room||this.getPCMAbortCtrlMap.get(t))return;let r=this.getPCM(n=>{var a;(a=this.room)==null||a.emit("audio-frame",n)},"");this.getPCMAbortCtrlMap.set(t,r),this.getPCMAbortCtrlMap.get(t)&&((s=this._localAudioTrack)==null||s.on("input-media-track-changed",()=>{let n=this.getPCMAbortCtrlMap.get(t);n&&(n.abort("inputMediaTrackChanged"),n=this.getPCM(a=>{var c;(c=this.room)==null||c.emit("audio-frame",a)},""),this.getPCMAbortCtrlMap.set(t,n))}))}handleLocalTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(t))}handleRemoteTrackStarted({room:e,userId:t}){if(e===this.room&&!this.getPCMAbortCtrlMap.get(t)){let r=this.room.audioManager.getPCM(s=>{var n;(n=this.room)==null||n.emit("audio-frame",s)},t);this.getPCMAbortCtrlMap.set(t,r)}}handleRemoteTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(t))}installEvent(){S.on("113",this.handleLocalTrackStarted,this),S.on("114",this.handleLocalTrackStopped,this),S.on("115",this.handleRemoteTrackStarted,this),S.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){S.off("113",this.handleLocalTrackStarted),S.off("114",this.handleLocalTrackStopped),S.off("115",this.handleRemoteTrackStarted),S.off("116",this.handleRemoteTrackStopped)}updateAudioReference({type:e,audioReference:t,refId:r,volume:s}){if(e==="add"){if(this.audioReferenceMap.get(r)||!t||(this.audioReferenceMap.set(r,t),!this.audioProcessor))return;this.mixAudioReference(t,r)}else if(e==="remove")this.audioReferenceMap.get(r)&&(this.audioReferenceMap.delete(r),this.unMixAudioReference(r));else if(e==="updateVolume"){if(!this.audioProcessor||T(s))return;this.setAudioReferenceVolume(r,s)}}};function Eo(o=30,i=2){return Q((e,t)=>function(...r){return new Promise((s,n)=>{let a=setTimeout(()=>{let c=new D({code:I.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${o}s`});(this.log||this._log||R).warn(c),i===2?n(c):i===1&&s()},o*1e3);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(a),e.apply(this,r).then(s,n).finally(()=>{clearTimeout(a),this._checkPendingPromiseSet&&a&&this._checkPendingPromiseSet.delete(a)})})})}function Tf(){return Q((o,i)=>function(...e){return this._checkPendingPromiseSet&&(this._checkPendingPromiseSet.forEach(t=>clearTimeout(t)),this._checkPendingPromiseSet.clear()),o.apply(this,e)})}var Mi=class Mi extends no{constructor(e,t,r){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:r,room:e});this.room=e;this.user=t;d(this,"tinyId");d(this,"isRemote",!0);d(this,"jitterBufferDelay",0);d(this,"availableState");d(this,"remotePublishState");d(this,"_triggerCheckDecodeSubject",ot(ce(this,Mi.STATE_SUBSCRIBE)));d(this,"ignoreUpdatePlayingState");this.tinyId=t.tinyId,this.availableState=new J(`${t.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new J(`${t.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),de(Ln(ce(this,J.STATECHANGED),ce(this.remotePublishState,J.STATECHANGED)),Fn(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),Te(c=>{this.availableState.state!==(c?J.ON:J.OFF)&&(this.availableState.state=c?J.ON:J.OFF),!(this.isRemotePublished&&this.ignoreUpdatePlayingState)&&this.updatePlayingState(c)}));let s=de(ce(this.player,ue.ERROR),$t(c=>c.code===MediaError.MEDIA_ERR_DECODE)),n=de(Un(5e3),$t(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived?!1:this.player.isPlaying||(this.kind===f.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)?(this.reportDecodeResult(!0),!1):!0)),a=de(xu(s,n),ke(ce(this,J.INIT)));de(this._triggerCheckDecodeSubject,$t(()=>!this.ignoreDecodeError),mo(a),Te(c=>{this.reportDecodeResult(!1,c)}))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get ignoreDecodeError(){var t,r;return(((r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===Mi.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===J.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){var s,n;let r=this.kind===f.AUDIO;if(v[e?"addSuccessEvent":"addFailedEvent"]({key:r?504700:514702}),!r){let a=((s=this.room)==null?void 0:s.downlinkVideoCodec.toUpperCase())||"H264";v[e?"addSuccessEvent":"addFailedEvent"]({key:rs[`DECODE_${a}_RESULT`]}),e||this.log.warn(`${(n=this.room)==null?void 0:n.downlinkVideoCodec} decode failed`)}e||(v.addEnum({key:r?504701:514703,value:Zr()}),se.uploadEvent({log:`stat-decode-failed-${this.kind}-${si()||ni()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===f.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.player.isPlayCalled&&this.player.setTrack(this.playerMediaTrack),this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isRemotePublished} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?J.ON:J.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};d(Mi,"STATE_SUBSCRIBE","subscribe"),M([Eo(5,1)],Mi.prototype,"waitHasMediaTrack",1),M([ye(J.INIT,Mi.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),S.emit(C.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),Rt(521716,!1)],Mi.prototype,"subscribe",1),M([ye(Mi.STATE_SUBSCRIBE,J.INIT,{sync:!0,success(){this.log.info("unsubscribed"),S.emit(C.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],Mi.prototype,"unsubscribe",1);var Ts=Mi;var gi=class extends Ts{constructor(e,t){super(e,t,1);d(this,"volume",0);d(this,"mediaType",1);d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}get dbVolume(){return so.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}onPlayerError(e){this.enableDecodeFrame&&(this._log.warn("use audio decoder"),this.room.enableInsertableStreams())}get enableDecodeFrame(){var e,t;return this.manager?this.manager.decodePipeline.some(r=>r)||((t=(e=this.player.element)==null?void 0:e.error)==null?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&Ec().AudioDecoder&&hi:!1}get enableDecryptFrame(){return this.manager&&!!this.manager.decodePipeline[0]}decodeFrame(e){if(!this.manager)return e;let t=e;for(let[r,s]of this.manager.decodePipeline.entries()){if(!s)continue;let n={frame:e,track:this};if(r===1&&this.isAvailable&&this.room.role==="audience"&&(n.onAudioFrameNTPTime=({ntp:a,frame:c,hasLeavingTag:l})=>{this.emit("audio-frame-with-ntp",{ntp:a,frame:c,hasLeavingTag:l})}),t=s(n),!t)return}return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}};var id=class extends Ue{constructor(e,t,r,s,n){super(e,{useDefaultProgram:!0,useFbo:!0,name:"alpha",create2d:!0,logger:t});this.setContainer=s;d(this,"initStat",{alphaStitchingType:1});d(this,"end",ot());d(this,"minSize",320);d(this,"maxSize",1280);d(this,"draggable",!1);d(this,"startDragX",0);d(this,"startDragY",0);d(this,"left",0);d(this,"top",0);d(this,"baseWidth",320);d(this,"baseRatio");d(this,"container");this.initStat=n,this.draggable=r,this.bindDragEvents()}bindDragEvents(){let e=this.context._canvas;if(e)if(this.draggable){let t=ke(this.end);de(ce(e,"mousedown"),Bn(this.startDrag.bind(this)),Mr(()=>de(ce(window,"mousemove"),ke(ce(window,"mouseup")))),t,Te(this.doDrag.bind(this))),de(ce(e,"dblclick"),t,Te(this.resetPosition.bind(this))),de(ce(e,"wheel"),t,Te(this.handleZoom.bind(this))),this.renderCanvas()}else{if(!this.container)return;this.container.style.removeProperty("left"),this.container.style.removeProperty("top"),this.end.next()}}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}startDrag(e){e.preventDefault(),e.button===0&&(this.startDragX=e.clientX-this.left,this.startDragY=e.clientY-this.top)}renderCanvas(){let{container:e}=this;e||this.setContainer(),!(!e||!this.baseRatio||!this.draggable)&&(e.style.setProperty("width",`${this.baseWidth}px`),e.style.setProperty("height",`${this.baseWidth/this.baseRatio}px`),e.style.setProperty("position","fixed"),e.style.setProperty("left",`${this.left}px`),e.style.setProperty("top",`${this.top}px`))}doDrag(e){e.preventDefault(),this.left=e.clientX-this.startDragX,this.top=e.clientY-this.startDragY,this.renderCanvas()}handleZoom(e){e.preventDefault();let t=.1,r=e.deltaY,s=this.context._canvas;s&&(this.baseWidth||(this.baseWidth=s.offsetWidth),r<0?this.baseWidth=Math.min(this.baseWidth*(1+t),this.maxSize):this.baseWidth=Math.max(this.baseWidth*(1-t),this.minSize),this.renderCanvas())}resetPosition(){this.left=0,this.top=0,this.renderCanvas()}onRatioReset(){this.renderCanvas()}draw2d(e,t,r,s,n){var _;let{ctx2d:a}=this,c=this.context._canvas;if(!a||!c)return!1;let l=super.draw2d(e,t,r,s,n),u=a.getImageData(0,0,s,n),{data:m}=u,h=!1;if(this.initStat.alphaStitchingType===1){let g=Math.floor(s/2);for(let E=0;E<n;E++)for(let A=0;A<g;A++){let k=(E*s+A)*4,re=A+g,P=(E*s+re)*4,Qe=m[P];m[P+3]=0;let N=Qe>=100;m[k+3]=N?255:0}h=super.draw2d(u,0,0,0,0,g,n),c.width=g}else if(this.initStat.alphaStitchingType===2){let g=Math.floor(n/2);for(let E=0;E<g;E++)for(let A=0;A<s;A++){let k=(E*s+A)*4,P=((E+g)*s+A)*4,Qe=m[P];m[P+3]=0;let N=Qe>=100;m[k+3]=N?255:0}h=super.draw2d(u,0,0,0,0,s,g),c.height=g}return(_=this.context.ctx)==null||_.clearRect(0,0,s,n),l&&h}close(){this.baseRatio=void 0,this.end.next(),this.end.complete()}};function MS(o){return[15,30,45,60].reduce((e,t)=>Math.abs(t-o)<Math.abs(e-o)?t:e)}var Oi=class extends Ts{constructor(e,t,r=4){super(e,t,r);d(this,"mediaType",4);d(this,"source");d(this,"shouldRenderAlpha",!1);d(this,"alphaNode");d(this,"shouldBeDraggable",!0);d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager,this.on("first-video-frame",s=>{this.room.emit("first-video-frame",s)})}isAlphaSei(e){if(this.userId!==e.userId||e.seiPayloadType!==50)return!1;let t=new Uint8Array(e.data);return t.length%3!==0||t[0]!==0||t[1]!==1?!1:t}play(e,t){return(he(t==null?void 0:t.canvasRender)?t.canvasRender:et===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat(),S.emit("156",{track:this,player:this.player})})}updateAlphaRenderInfo(e){let t=this.isAlphaSei(e);if(t)if(!this.alphaNode)this.shouldRenderAlpha=!0,this.player.shouldRenderAlpha=!0,this.useCanvasPlayer(t[2]);else{let r=t[2];if(this.alphaNode.baseRatio&&this.alphaNode.initStat.alphaStitchingType===r)return;this.alphaNode.initStat={alphaStitchingType:r};let s=this.player.getElement();if(s){let n=s.videoWidth/s.videoHeight;n&&(this.alphaNode.baseRatio=n*(r===1?.5:2),this.alphaNode.onRatioReset())}this.player.canvas&&(this.player.canvas.id=this.generateAlphaCanvasName(r))}}generateAlphaCanvasName(e){let t="alpha",r=hn[e];return`${t}_${r}_${this.userId}`}useCanvasPlayer(e){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let t=new Xe({frameRate:15,logger:this.log,name:this.shouldRenderAlpha&&e?this.generateAlphaCanvasName(e):this.userId});t.create({alpha:this.shouldRenderAlpha,willReadFrequently:this.shouldRenderAlpha});let r=new fo(t,{name:"remotePlayer",logger:this.log});if(this.source=t.createVideoPlayerSource(this.player),this.player.setCanvas(t._canvas),this.shouldRenderAlpha&&e){let s=()=>{!this.player.container||!this.alphaNode||(this.alphaNode.container=this.player.container,this.alphaNode.renderCanvas())},n=new id(t,this.log,this.shouldBeDraggable,s,{alphaStitchingType:e});this.source.connect(n),n.connect(r),this.alphaNode=n}else this.source.connect(r);Ki()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,t),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=MS(t);if(!z(t)||t<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${t} `);return}if(r===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${r} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${t}, closest: ${r}, current: ${e.frameRate}`),e.frameRate=r}get decodeFPS(){var n;let{msg_video_status:e}=((n=this.room.heartbeatReport)==null?void 0:n.msg_down_stream_info.find(a=>a.msg_user_info.str_identifier===this.userId))||{},t=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let r=e.find(a=>a.uint32_video_stream_type===t);return(r==null?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),S.emit("157",{track:this,player:this.player}),this.alphaNode&&this.alphaNode.close(),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&(e=t({frame:e,track:this}),!e))return;return e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}setDraggable(e){this.shouldBeDraggable=e,this.alphaNode&&(this.alphaNode.draggable=e,this.alphaNode.bindDragEvents())}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},Es=class extends Oi{constructor(e,t){super(e,t,2);d(this,"mediaType",2);d(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var Ss=new Map;S.on(C.JOIN_SUCCESS,({room:o})=>{Ne(o.userId,{eventId:32788})});S.on(C.LEAVE_START,({room:o})=>{Ne(o.userId,{eventId:32789})});S.on(C.LOCAL_TRACK_PUBLISHED,({track:o})=>{if(o.room){let i=32769;o.mediaType===4?i=32768:o.mediaType===2&&(i=32805),Ne(o.room.userId,{eventId:i})}});S.on(C.LOCAL_TRACK_UNPUBLISHED,({track:o})=>{if(o.room){let i=32771;o.mediaType===4?i=32770:o.mediaType===2&&(i=32806),Ne(o.room.userId,{eventId:i})}});S.on(C.TRACK_MUTED,({track:o})=>{o.room&&(o.kind===f.AUDIO?Ne(o.room.userId,{eventId:o.isRemote?32785:32772,remoteUserId:o.isRemote?o.userId:void 0}):Ne(o.room.userId,{eventId:o.isRemote?32784:32773,remoteUserId:o.isRemote?o.userId:void 0}))});S.on(C.TRACK_UNMUTED,({track:o})=>{o.room&&(o.kind===f.AUDIO?Ne(o.room.userId,{eventId:o.isRemote?32787:32774,remoteUserId:o.isRemote?o.userId:void 0}):Ne(o.room.userId,{eventId:o.isRemote?32786:32775,remoteUserId:o.isRemote?o.userId:void 0}))});S.on(C.REMOTE_TRACK_SUBSCRIBED,({track:o})=>{o.room&&(o.mediaType===1&&Ne(o.room.userId,{eventId:32777,remoteUserId:o.userId}),o.mediaType===4&&Ne(o.room.userId,{eventId:32776,remoteUserId:o.userId}),o.mediaType===8&&Ne(o.room.userId,{eventId:32803,remoteUserId:o.userId}))});S.on(C.REMOTE_TRACK_UNSUBSCRIBED,({track:o})=>{o.room&&(o.mediaType===1&&Ne(o.room.userId,{eventId:32779,remoteUserId:o.userId}),o.mediaType===4&&Ne(o.room.userId,{eventId:32778,remoteUserId:o.userId}),o.mediaType===8&&Ne(o.room.userId,{eventId:32804,remoteUserId:o.userId}))});S.on(C.SWITCH_DEVICE_SUCCESS,({track:o})=>{o.room&&Ne(o.room.userId,{eventId:o.kind===f.VIDEO?32780:32781})});S.on(C.LOCAL_TRACK_REPLACED,({track:o})=>{o.room&&Ne(o.room.userId,{eventId:o.kind===f.VIDEO?32782:32783})});S.on(C.SIGNAL_CONNECTION_STATE_CHANGED,({room:o,prevState:i,state:e})=>{let t;switch(e){case"CONNECTED":i==="RECONNECTING"?t=32795:t=32791;break;case"DISCONNECTED":i==="RECONNECTING"?t=32796:t=32790;break;case"RECONNECTING":t=32794;break}t&&Ne(o.userId,{eventId:t})});S.on(C.PEER_CONNECTION_STATE_CHANGED,({room:o,prevState:i,state:e,remoteUserId:t})=>{let r=!!t,s;switch(e){case"CONNECTED":i==="RECONNECTING"?s=r?32801:32798:s=r?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(s=r?32802:32799);break;case"RECONNECTING":s=r?32800:32797;break}s&&Ne(o.userId,{eventId:s,remoteUserId:t})});S.on(C.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:o,userId:i,remoteUserId:e,codec:t,isHWCodec:r,prevImplementation:s,streamType:n})=>{let a=r?1:0;s||(a=r?3:2);let c={H264:0,H265:1,VP8:2}[t.toUpperCase()],l={eventId:4004,param1:a,param2:c,streamType:n||2};e&&(l.remoteUserId=e,l.eventId=4005),Ne(i,l),v.addEnum({key:e?514701:513701,value:a}),v.addEnum({key:e?514700:513700,value:c})});S.on(C.LOCAL_TRACK_RECAPTURE,({track:o,error:i})=>{if(o.userId){let e={eventId:2003,param1:0};o.kind===f.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=o.streamType==="auxiliary"?7:2,i&&(e.param1=8)),Ne(o.userId,e)}});function Ne(o,i){let e=L(O({},i),{timestamp:Fi()});Ss.has(o)?Ss.get(o).push(e):Ss.set(o,[e])}function Ef(o){if(Ss.has(o)){let i=Ss.get(o).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType}));return Ss.delete(o),i}return[]}function Sf(...o){return Q((i,e)=>function(...t){return OS.call(this,o,t,e,this._name),i.apply(this,t)})}function OS(o,i,e,t){try{if(Ie(o))for(let r=0;r<o.length;r++)rd.call(this,{rule:o[r],value:i[r],key:o[r].name,fnName:e,className:t});else rd.call(this,{rule:o,value:i[0],key:o.name,fnName:e,className:t})}catch(r){throw R.error(r),r}}function rd({rule:o,value:i,key:e,fnName:t,className:r}){if(T(i)){if(o.required)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_REQUIRED,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(T(o.defaultValue))return;i=o.defaultValue}if(Array.isArray(o.type)){let a=!1;for(let c=0;c<o.type.length;c++)o.type[c]===null&&i===null&&(a=!0),le(o.type[c])&&i instanceof o.type[c]&&(a=!0),ie(o.type[c])&&Me(i)===o.type[c].toLowerCase()&&(a=!0);if(!a)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_TYPE,data:{key:e,rule:{type:o.type.map(c=>jr(c)?xo(c):ie(c)?c:Me(c))},fnName:t,value:i},link:{className:r,fnName:t}})})}else if(!T(o.type)&&Me(i)!==o.type)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_TYPE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(o.allowEmpty===!1){let a=z(i)&&(i===0||Number.isNaN(i)),c=ie(i)&&i.trim()==="";if(a||c)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_EMPTY,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})})}if(o.notLessThanZero&&z(i)&&i<0)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.CANNOT_LESS_THAN_ZERO,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(o.min)&&z(i)&&i<o.min)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_MIN,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(o.max)&&z(i)&&i>o.max)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_MAX,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(ie(o.instanceOf)){if(!i||i._name!==o.instanceOf)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})})}else if(le(o.instanceOf)&&!(i instanceof o.instanceOf))throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(o.values&&!o.values.includes(i))throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_RANGE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});let{properties:s}=o;dt(s)&&yt(i)&&Object.keys(s).forEach(a=>{rd.call(this,{rule:s[a],value:i&&i[a],key:`${e}.${a}`,fnName:t,className:r})});let{arrayItem:n}=o;dt(n)&&Ie(i)&&i.forEach((a,c)=>{rd.call(this,{rule:n,value:a,key:`${e}[${c}]`,fnName:t,className:r})}),le(o.validate)&&o.validate.call(this,i,e,t,r,this)}var If=Ge(at(),1);var od=class extends If.EventEmitter{constructor(e,t,r="userId"){super();this.mySelfId=e;this._log=t;this.key=r;d(this,"userMap",new Map);d(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(e=>e.isRobot)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:r,tinyId:s,role:n}=e;if(this.userMap.has(t))return;let a={userId:r,tinyId:s,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let r=this.userMap.get(e);if(!r)return;let s=`peer leave [${e}]`;T(t)||(s+=`:${rl[t]}`),this._log.info(s);let n=this.remotePublishedUserMap.get(e);if(n){let a=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",r.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(r=>r[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){this.remotePublishedUserMap.has(e)&&this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let r=t[this.key];if(e.findIndex(s=>s[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let s=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:s,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var u;let r=t[this.key];if(r===this.mySelfId){this.emit("7",t);return}let{flag:s,userId:n,tinyId:a}=t,c=Kt(s,n),l=(u=this.remotePublishedUserMap.get(r))==null?void 0:u.muteState;if(l){let m=this.remotePublishedUserMap.get(r);m&&m.flag!==s&&(m.flag=s,this._log.info(`remote publish updated: ${JSON.stringify(m.muteState)}`),this.emit("6",{prevMuteState:l,muteState:c,flag:s}))}else this._log.info(`remote publish. state: ${JSON.stringify(c)}`),this.addUser({userId:n,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:Kt(0,n),muteState:c,flag:s})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function Ch({timesInSecond:o,maxSizeInSecond:i,getSize:e}){return Q((t,r)=>{let s=new WeakMap;return S.on(C.ROOM_DESTROY,({room:n})=>s.delete(n)),function(...n){let a=s.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=o||a.totalSizeInSecond>i))throw new D({code:I.INVALID_OPERATION,message:H({key:F.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=o,isSize:a.totalSizeInSecond>i,name:r,timesInSecond:o,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var kS="2025-12-09 17:54:57",Af=!0,Cf=function(){var o;if(Af){Af=!1,R.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${ft}/en/index.html`),console.info(`* Changelog: ${ft}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),R.info("TRTC Web SDK Version:",He),oi||R.debug("Build Time:",kS);let i=`UA: ${navigator.userAgent}
|
|
52
|
+
} `;var _o=class extends J{constructor(e){super();d(this,"frameRate");d(this,"_canvas");d(this,"log");d(this,"hasAlpha",!1);d(this,"name");d(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}get canvas(){return this._canvas}set width(e){this._canvas&&(this._canvas.width=e)}get width(){var e;return((e=this._canvas)==null?void 0:e.width)||0}set height(e){this._canvas&&(this._canvas.height=e)}get height(){var e;return((e=this._canvas)==null?void 0:e.height)||0}setSize(e,t){this._canvas&&(this._canvas.width=e,this._canvas.height=t)}createVideoTrackSource(e,t){return new Wt(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new fs(this,e)}createVideoImageSource(e,t){return new $n(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new Wn(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}createTextSource(e,t){return new Kc(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};d(_o,"_ids",0);var SS={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},_s=class _s extends _o{constructor(){super(...arguments);d(this,"defaultProgam");d(this,"defaultVShader");d(this,"defaultFShader");d(this,"ctx");d(this,"_canvas2d")}get canvas(){return this._canvas2d||this._canvas}create(e=!1){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${_o._ids++}`),e&&(this._canvas2d=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",SS),!this.ctx)throw new D({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,TS),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,ES),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let t="";return e&&(t=e.message,this.error=e,v.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info(`video context destroy${t}`?`: ${t}`:""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;(t=this.ctx)==null||t.viewport(0,0,e,this.height),super.width=e,this._canvas2d&&(this._canvas2d.width=e)}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e,this._canvas2d&&(this._canvas2d.height=e)}setSize(e,t){var r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t),this._canvas2d&&(this._canvas2d.width=e,this._canvas2d.height=t)}createShader(e,t){let r=this.ctx,s=r.createShader(e);return r.shaderSource(s,t),r.compileShader(s),s}createProgram(e,t){let r=this.ctx,s=r.createProgram();return r.attachShader(s,e),r.attachShader(s,t),r.linkProgram(s),r.getProgramParameter(s,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(s)),s}};d(_s,"UNAVAILABLE","unavailable"),M([ye(J.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),v.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),v.addSuccessEvent({key:512700})}})],_s.prototype,"create",1),M([ye("created",J.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(_s.UNAVAILABLE,e),this.removeAllListeners()}})],_s.prototype,"destroy",1);var Be=_s,Xe=class extends _o{constructor(){super(...arguments);d(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${_o._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha,willReadFrequently:e.willReadFrequently}),!this.ctx)throw new D({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",()=>{this.log.error("2d context lost")}),this._canvas.addEventListener("contextrestored",()=>{this.log.warn("2d context restored")})}destroy(e){let t="";e&&(t=e.message,this.error=e,v.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info(`video context destroy ${t?`: ${t}`:""}`),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),v.addSuccessEvent({key:512703})}};M([ye(J.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),v.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),v.addSuccessEvent({key:512701})}})],Xe.prototype,"create",1),M([ye("created",J.INIT,{ignoreError:!0,sync:!0})],Xe.prototype,"destroy",1);function IS(o,i,e,t,r,s=!1){s&&([e,t]=[t,e]);let n={sWidth:o,sHeight:i,dWidth:e,dHeight:t,sx:0,sy:0,dx:0,dy:0};if(o===0||i===0)return n;switch(r){case void 0:case"fill":break;case"contain":{let a=Math.min(e/o,t/i);n.dWidth=o*a,n.dHeight=i*a,n.dx=(e-n.dWidth)/2,n.dy=(t-n.dHeight)/2;break}case"cover":{let a=Math.max(e/o,t/i),c=e/a,l=t/a;n.sx=(o-c)/2,n.sy=(i-l)/2,n.sWidth=c,n.sHeight=l;break}}return n}var Ih=class{constructor(i,e){this.node=i;this.layout=e;d(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}get fillMode(){return this.layout.fillMode}get rotation(){return this.layout.rotation}get hidden(){return!!this.layout.hidden}},gs=class extends Ue{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t});d(this,"inputs",[]);d(this,"backgroundColor","black")}addInput(e,t){let r=0,s=this.inputs.length;for(;r<s;){let a=Math.floor((r+s)/2);if(this.inputs[a].layout.zIndex<t.zIndex)r=a+1;else if(this.inputs[a].layout.zIndex>t.zIndex)s=a;else throw new Error(`input already exists at zIndex ${t.zIndex}`)}let n=new Ih(e,t);this.inputs.splice(r,0,n)}changeInputLayout(e,t){let r=this.inputs.findIndex(g=>g.node===e);if(r<0)return;let{x:s,y:n,width:a,height:c,zIndex:l,fillMode:u,rotation:m,hidden:h}=t;if(!T(l)&&this.inputs.some(g=>g.layout.zIndex===l&&g.node!==e))throw new Error(`input already exists at zIndex ${t.zIndex}`);let _=this.inputs[r];T(s)||(_.layout.x=s),T(n)||(_.layout.y=n),T(a)||(_.layout.width=a),T(c)||(_.layout.height=c),T(m)||(_.layout.rotation=m),T(h)||(_.layout.hidden=h),u&&(_.layout.fillMode=u),!T(l)&&l!==_.layout.zIndex&&(_.layout.zIndex=l,this.inputs.sort((g,E)=>g.layout.zIndex-E.layout.zIndex))}hasInput(e){return this.inputs.some(t=>t.node===e)}hasNoInput(){return this.inputs.length===0}resize(e,t){if(!this.matchInputSize){super.resize(e,t);return}let r=this.inputs.reduce((s,n)=>n?Object.assign(s,{width:Math.max(s.width,n.right),height:Math.max(s.height,n.bottom)}):s,{width:0,height:0});super.resize(r.width,r.height),this.context instanceof Be&&this.inputs.forEach(s=>{if(s){let n=this.layout2texCoords(s);s.positionBuffer?this.changeBufferData(s.positionBuffer,n):s.positionBuffer=this.createBuffer(n)}})}connect(e,...t){return super.connect(e,...t),this.drawBackGround2d(this.backgroundColor),this.matchInputSize&&this.resize(0,0),e}removeInput(e){this.inputs=this.inputs.filter(t=>t.node!==e),this.inputs.length===0&&this.drawBackGround2d(this.backgroundColor)}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),this.inputs.reduce((s,n)=>n.node.requestFrame(e)||s,!1)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let s=0;s<this.inputs.length;s++){let n=this.inputs[s];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){if(this.inputs.forEach(t=>t.node.requestFrame(e)),this.ctx2d){this.drawBackGround2d(this.backgroundColor);for(let t=0;t<this.inputs.length;t++){let r=this.inputs[t];if(r.hidden)continue;let s=IS(r.node.width,r.node.height,r.width,r.height,r.fillMode,bt(r.rotation));this.draw2d(r.node.image,r.x+s.dx,r.y+s.dy,s.dWidth,s.dHeight,s.sx,s.sy,s.sWidth,s.sHeight)}return!0}return!1}debugLayout(e,t,r,s,n=!1){this.ctx2d&&(n&&([r,s]=[s,r]),this.ctx2d.save(),this.ctx2d.strokeStyle="red",this.ctx2d.lineWidth=2,this.ctx2d.strokeRect(e,t,r,s),this.ctx2d.restore())}getInfo(){let{totalFrames:e,x:t,y:r,width:s,height:n,name:a}=this,c=Date.now(),l=(e-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:s,height:n,timestamp:c,fps:l,name:a},O({parent:this.inputs.filter(u=>u).map(u=>u.node.getInfo())},this.lastInfo)}removeAllInputs(){this.inputs.forEach(e=>{var t;if(e.node.disconnect(),e.positionBuffer&&this.context instanceof Be)try{(t=this.context.ctx)==null||t.deleteBuffer(e.positionBuffer)}catch(r){}})}close(){super.close(),this.removeAllInputs()}};var AS=[1,0,0,0,1,1,0,1],Gt=class extends Ue{constructor(e,t,r,s){super(e,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:t});d(this,"mirror",!1);d(this,"rotation",0);if(r&&(this.mirror=r),s&&(this.rotation=s),e instanceof Be)try{this.setTexBuffer(AS)}catch(n){e.destroy(new D({code:I.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${n.message||n}`}))}}draw2d(e,t,r,s,n){if(this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height),this.ctx2d.save(),this.mirror&&(this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0)),this.rotation===90?(this.ctx2d.translate(s,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(n/s,s/n)):this.rotation===180?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):this.rotation===270&&(this.ctx2d.translate(0,n),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(n/s,s/n));let a=super.draw2d(e,t,r,s,n);return this.ctx2d.restore(),a}return!1}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}resize(e,t){bt(this.rotation)&&([e,t]=[t,e]),super.resize(e,t)}};var go=class extends pi{constructor(e,t=4){super(t,it);d(this,"inputLocalVideoTracks",new Map);d(this,"inputLocalScreenTracks",new Map);d(this,"cameraNodeMap",new Map);d(this,"screenNodeMap",new Map);d(this,"textNodeMap",new Map);d(this,"imageNodeMap",new Map);d(this,"videoNodeMap",new Map);d(this,"endedIds",new Set);d(this,"videoContext");d(this,"mixNode");d(this,"destination");d(this,"manager");d(this,"stat");d(this,"_checkId",0);d(this,"autoSetFps",!0);this.manager=e,this.log.id+="mix",this.create2dVideoContext(),this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(Ue.RENDER,r=>{this.emit("render",r)}),this.mixNode=new gs(this.videoContext,this.log),this.mixNode.matchInputSize=!1}listenDeviceChange(){throw new Error("Method not implemented.")}enablePrintDetail(e=2e3){this._checkId=oe.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new Xe({frameRate:15,logger:this.log,name:"mix-ctx"}),this.videoContext.create({alpha:!1})}setFps(e){this.autoSetFps=!1,this.videoContext.frameRate=e;for(let t of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])t.shouldUpdate=!1;setTimeout(()=>{var t;return(t=this.destination)==null?void 0:t.start(this.videoContext.frameRate)},500)}setFpsAuto(){var s;if(!this.autoSetFps)return;for(let n of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])n.shouldUpdate=!1;let e=null,t=0,r=!0;for(let[n,a]of this.inputLocalVideoTracks)if(a.profile.frameRate>t){if(this.endedIds.has(n)){let c=this.cameraNodeMap.get(n);c&&c.image.cancelVideoFrameCallback(c.videoCallbackId);continue}t=a.profile.frameRate,e=n}for(let[n,a]of this.inputLocalScreenTracks)if(a.profile.frameRate>t){if(this.endedIds.has(n)){let c=this.screenNodeMap.get(n);c&&c.image.cancelVideoFrameCallback(c.videoCallbackId);continue}t=a.profile.frameRate,e=n,r=!1}if(e!==null){let n=r?this.cameraNodeMap.get(e):this.screenNodeMap.get(e);n&&(n.shouldUpdate=!0,n.tryVideoFrameCallback()),this.log.info("set mix fps: ",t)}else(s=this.destination)==null||s.start(this.videoContext.frameRate),this.log.info("fallback to timer, fps: ",this.videoContext.frameRate)}setMixBackground(e){this.mixNode&&(this.mixNode.backgroundColor=e)}resizeMixCanvas(e,t){var r;(r=this.mixNode)==null||r.resize(e,t)}startMix(){return p(this,null,function*(){var e;if(!this.mixNode||!this.destination)throw new Error("can't mix without necessary conditions");this.mixNode.disconnect(),this.mixNode.connect(this.destination),Ft&&this.player.setCanvas(this.videoContext._canvas),this.setOutputMediaStreamTrack(this.destination.videoTrack),(e=this.manager)==null||e.changeInput(this)})}addCameraSource(e,t,r){if(this.inputLocalVideoTracks.has(e)||this.cameraNodeMap.has(e))throw new Error(`There is already a cameraSource with the same ID: ${e}`);let{mediaTrack:s}=t;if(!s)throw new Error("no mediaTrack, add cameraSource failed");t.recaptureMode=1,tt(this,be).add("videoInputRemoved",a=>{a.deviceId===t.deviceId&&(this.endedIds.add(e),this.setFpsAuto())}),t.on("output-media-track-changed",()=>{this.endedIds.delete(e),this.updateCameraSource(e,r,t.mediaTrack)});let n;et===16&&s instanceof CanvasCaptureMediaStreamTrack?n=this.videoContext.createVideoImageSource(s.canvas,{name:"cameraCanvasSource",logger:this.log}):n=this.videoContext.createVideoTrackSource(s,"cameraNodeSource"),n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r,"cover"),this.inputLocalVideoTracks.set(e,t),this.cameraNodeMap.set(e,n),this.setFpsAuto()}addScreenSource(e,t,r){if(this.inputLocalScreenTracks.has(e)||this.screenNodeMap.has(e))throw new Error(`There is already a screenSource with the same ID: ${e}`);let{mediaTrack:s}=t;if(!s)throw new Error("no mediaTrack, add cameraSource failed");let n=this.videoContext.createVideoTrackSource(s,"screenNodeSource");n.resize(t.settings.width,t.settings.height),n.shouldUpdate=!1,this._connectMix(n,r),this.inputLocalScreenTracks.set(e,t),this.screenNodeMap.set(e,n),this.setFpsAuto()}addTextSource(e){let{id:t,content:r="",font:s,color:n,layout:a}=e;if(this.textNodeMap.has(t))throw new Error(`There is already a textSource with the same ID: ${t}`);let c=this.videoContext.createTextSource({content:r,font:s,color:n});c.resize(a.width,a.height),this._connectMix(c,a),this.textNodeMap.set(t,c)}addImageSource(e,t,r){if(this.imageNodeMap.has(e))throw new Error(`There is already a imageSource with the same ID: ${e}`);let s=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});s.resize(t.width,t.height),this._connectMix(s,r),this.imageNodeMap.set(e,s)}addVideoSource(e,t,r){if(this.videoNodeMap.has(e))throw new Error(`There is already a videoSource with the same ID: ${e}`);let s=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});s.resize(t.videoWidth,t.videoHeight),s.shouldUpdate=!1,this._connectMix(s,r),this.videoNodeMap.set(e,s)}updateCameraSource(e,t,r=null,s){let n=this.cameraNodeMap.get(e);if(n){if(r){if(et===16&&r instanceof CanvasCaptureMediaStreamTrack)if(n instanceof Wt){let l=n.output;n.close(),n=this.videoContext.createVideoImageSource(r.canvas,{name:"cameraCanvasSource",logger:this.log}),n.connect(l),this.cameraNodeMap.set(e,n)}else n.image=r.canvas;else if(n instanceof Wt)n.replaceTrack(r);else{let l=n.output;n.close(),n=this.videoContext.createVideoTrackSource(r,"cameraNodeSource"),n.connect(l),this.cameraNodeMap.set(e,n)}let{width:a,height:c}=r.getSettings();a&&c&&n.resize(a,c)}s&&n.resize(s.width,s.height),(s||r)&&this.setFpsAuto(),this._changeMixLayout(n,t)}}updateScreenSource(e,t){let r=this.screenNodeMap.get(e);r&&this._changeMixLayout(r,t)}updateTextSource(e){let{id:t,content:r,font:s,color:n,layout:a}=e,c=this.textNodeMap.get(t);c&&(T(r)||(c.content=r),T(s)||(c.font=s),T(n)||(c.color=n),c.resize(a.width,a.height),this._changeMixLayout(c,a))}updateImageSource(e,t,r){let s=this.imageNodeMap.get(e);s&&(r&&(s.image=r,s.resize(r.width,r.height)),this._changeMixLayout(s,t))}updateVideoSource(e,t,r){let s=this.videoNodeMap.get(e);if(s){if(r){let n=s.image;n instanceof HTMLVideoElement&&this.stopVideoElement(n),s.image=r,s.resize(r.videoWidth,r.videoHeight)}this._changeMixLayout(s,t)}}_connectMix(e,t,r="contain"){if(!this.mixNode)return;let{mirror:s,rotation:n}=t;e.disconnect();let a=new Gt(this.videoContext,this.log,s,n);a=e.connect(a),t.fillMode||(t.fillMode=r),a.connect(this.mixNode,t)}_changeMixLayout(e,t){if(!this.mixNode)return;let{mirror:r,rotation:s}=t,n=e.output||e;n instanceof Gt&&(T(r)||(n.mirror=r),T(s)||(n.rotation=s),n.resize(e.width,e.height)),this.mixNode.changeInputLayout(n,t)}removeCameraSource(e){let t=this.inputLocalVideoTracks.get(e);if(!t)return;t.close(),this.inputLocalVideoTracks.delete(e);let r=this.cameraNodeMap.get(e);r&&(r.output instanceof Gt&&r.output.close(),r.close(),this.cameraNodeMap.delete(e)),this.checkAfterRemove(!0)}removeScreenSource(e){let t=this.inputLocalScreenTracks.get(e);if(!t)return;t.close(),this.inputLocalScreenTracks.delete(e);let r=this.screenNodeMap.get(e);r&&(r.output instanceof Gt&&r.output.close(),r.close(),this.screenNodeMap.delete(e)),this.checkAfterRemove(!0)}removeTextSource(e){let t=this.textNodeMap.get(e);t&&(t.output instanceof Gt&&t.output.close(),t.close(),this.textNodeMap.delete(e)),this.checkAfterRemove()}removeImageSource(e){let t=this.imageNodeMap.get(e);t&&(t.output instanceof Gt&&t.output.close(),t.close(),this.imageNodeMap.delete(e)),this.checkAfterRemove()}removeVideoSource(e){let t=this.videoNodeMap.get(e);t&&(t.output instanceof Gt&&t.output.close(),t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image),t.close(),this.videoNodeMap.delete(e)),this.checkAfterRemove()}checkAfterRemove(e=!1){e&&this.setFpsAuto()}stopVideoElement(e){e.pause(),e.src="",e.srcObject=null,e.remove()}close(){var e;super.close(),oe.clearTask(this._checkId),(e=this.videoContext)==null||e.destroy(),delete this.mixNode,delete this.destination;for(let t of[...this.inputLocalVideoTracks.values(),...this.inputLocalScreenTracks.values()])t.close();this.inputLocalVideoTracks.clear(),this.inputLocalScreenTracks.clear(),this.cameraNodeMap.clear(),this.screenNodeMap.clear(),this.textNodeMap.clear(),this.imageNodeMap.clear(),Le(this);for(let t of this.videoNodeMap.values())t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image);this.videoNodeMap.clear(),this.log.info("localMixVideoTrack close, stop mix")}};var ed=cn();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:ed,exposeOrigin:!0,permittedOrigins:["*"]})}catch(o){}var CS=function(o){return p(this,null,function*(){let i=null,e=bS(o);R.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);o.systemAudio&&t.getAudioTracks().length===0&&(Zo&&qe<74||Re||K)&&R.warn("Your browser not support capture system audio");let r=t.getVideoTracks()[0];if(r){if(o.frameRate)try{yield r.applyConstraints({frameRate:{min:o.frameRate,ideal:o.frameRate},width:o.width,height:o.height})}catch(s){R.warn(`screen applyConstraints failed: ${s}`)}o.captureElement&&(yield RS(r,o.captureElement))}if(o.audio){let s=yS(o);R.info(`getUserMedia with constraints: ${JSON.stringify(s)}`),i=yield navigator.mediaDevices.getUserMedia(s),t.addTrack(i.getAudioTracks()[0])}return t})};function RS(o,i){return p(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&le(o.cropTo))try{if(!(((e=o.getCaptureHandle())==null?void 0:e.handle)===ed))return;let r=yield CropTarget.fromElement(i);yield o.cropTo(r)}catch(t){R.warn(`cropTo target failed ${t}`)}})}function yS(o){let i={echoCancellation:o.echoCancellation,autoGainControl:o.autoGainControl,noiseSuppression:o.noiseSuppression,sampleRate:o.sampleRate,channelCount:o.channelCount};return T(o.microphoneId)||(i.deviceId=o.microphoneId),{audio:i,video:!1}}function bS(o){let i={preferCurrentTab:o.preferDisplaySurface==="current-tab"||!!o.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Re?{max:o.width}:{ideal:o.width,max:o.width},height:Re?{max:o.height}:{ideal:o.height,max:o.height},frameRate:o.frameRate,displaySurface:o.preferDisplaySurface||"monitor"};if(i.video=e,o.systemAudio){let{echoCancellation:t=!0,noiseSuppression:r=!1,autoGainControl:s=!1}=o;i.audio={echoCancellation:t,noiseSuppression:r,autoGainControl:s,sampleRate:48e3}}return i}var gf=CS;var Pt=class extends je{constructor(e){super(e,2);d(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});d(this,"objectFit","contain");d(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}get isShareCurrentTab(){var e,t;try{return ed===((t=(e=this.mediaTrack)==null?void 0:e.getCaptureHandle())==null?void 0:t.handle)}catch(r){return}}capture(u){return p(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:r,noiseSuppression:s,audioTrack:n,videoTrack:a,captureElement:c,preferDisplaySurface:l}){try{let m;return a||n?(m=new MediaStream,a&&m.addTrack(a),n&&m.addTrack(n)):(m=yield gf({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:r,noiseSuppression:s,captureElement:c,preferDisplaySurface:l}),this.sourceTrack=m.getVideoTracks()[0]),yield this.setInputMediaStreamTrack(m.getVideoTracks()[0]),m}catch(m){throw this.log.error(`getDisplayMedia error observed ${m}`),m instanceof D?m:new D({code:I.INITIALIZE_FAILED,name:m.name,message:m.message})}})}switchDevice(e){return p(this,null,function*(){throw new Error("Method not implemented.")})}};M([Ct(function(e){this.setContentHint(e.contentHint||"detail")})],Pt.prototype,"capture",1);var To=class extends kt{constructor(i){super(i),this._log.id=`s-${this._log.id}`,this.isScreen=!0}addAudioProcessor(i,e,t){this.pipeline.silentNode.setNode(t),this.pipeline.mixNode.setNode(e),this.pipeline.aec.setNode(i),this.enableTrackAEC(!1)}removeAudioProcessor(i){this.pipeline.aec.node===i&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};var vS='registerProcessor("dumper",class extends AudioWorkletProcessor{constructor(e){super(),this.sourceSampleRate=e.processorOptions.sourceSampleRate||48e3,this.targetSampleRate=e.processorOptions.targetSampleRate||48e3,this.port.onmessage=e=>{this.port2=e.data.port}}process(e){return(this.port2||this.port).postMessage(this.resampleAll(e,this.sourceSampleRate,this.targetSampleRate)),!0}resampleAll(r,s,a){if(s===a)return r;var o=[];for(let t=0;t<r.length;t++){o[t]=[];for(let e=0;e<r[t].length;e++)o[t][e]=this.resample(r[t][e],s,a)}return o}resample(t,e,r){if(e===r)return t;var s=Math.round(t.length*(this.targetSampleRate/this.sourceSampleRate)),a=new Float32Array(s),o=(t.length-1)/(s-1);a[0]=t[0];for(let e=1;e<s-1;e++){var l=e*o,p=Math.floor(l),h=Math.ceil(l);a[e]=t[p]+(t[h]-t[p])*(l-p)}return a[s-1]=t[t.length-1],a}});',Ah;function Gn(o,i=48e3,e=1,t){return p(this,null,function*(){let r=Ee("dump");Ah||(Ah=tr(r,URL.createObjectURL(new Blob([vS],{type:"application/javascript"})))),yield Ah;let s=r.sampleRate,n=new AudioWorkletNode(r,"dumper",{numberOfInputs:o.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:s,targetSampleRate:i}});return n.channelCountMode="explicit",n.channelCount=e,t&&n.port.postMessage({port:t},[t]),o.forEach((a,c)=>a.connect(n,0,c)),new ReadableStream({start(a){n.port.onmessage=c=>{a.enqueue(c.data)}},cancel(){o.forEach(a=>a.disconnect(n)),n.port.close()}})})}var td=class extends bc{constructor(e){super();this.room=e;d(this,"_localAudioTrack");d(this,"_localScreenAudioTrack");d(this,"log");d(this,"denoiser");d(this,"voiceChanger");d(this,"mixChangedDebounce");d(this,"audioProcessor");d(this,"encodePipeline",[]);d(this,"decodePipeline",[]);d(this,"getPCMAbortCtrlMap",new Map);d(this,"audioFrameEventConfigMap",new Map);d(this,"audioReferenceMap",new Map);d(this,"isLocalAudioNeedAudioProcess",!1);d(this,"isScreenAudioNeedAudioProcess",!1);this.log=R.createLogger({parent:e==null?void 0:e.getLogger(),id:"am",userId:e==null?void 0:e.userId,sdkAppId:e==null?void 0:e.sdkAppId}),this.installEvent()}get localAudioTrack(){return this._localAudioTrack}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}get _localScreenAudioPipeline(){var e;return(e=this._localScreenAudioTrack)==null?void 0:e.pipeline}dump(e){var u,m;if(!this._localAudioTrack)return;let t=[],r=[];(u=this._localAudioPipline)!=null&&u.source.node&&(t.push(this._localAudioPipline.source.node),r.push("mic")),(m=this._localAudioPipline)!=null&&m.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),r.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),r.push("mix")),this.log.info(`dump audio track ${r}, duration: ${e}`);let s=new AbortController,n=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),s.abort("timeout")},e*1e3),c=()=>{for(let h=0;h<r.length;h++){let _=URL.createObjectURL(new Blob(n[h])),g=document.createElement("a");g.href=_,g.download=`${r[h]}.pcm`,g.style.display="none",document.body.appendChild(g),g.click(),URL.revokeObjectURL(_),g.remove()}clearTimeout(a),s.abort("download")},l=Gn(t).then(h=>h.pipeTo(new WritableStream({write(_){_.forEach((g,E)=>n[E]=n[E]?n[E].concat(g[0]):[g[0]])}}),s).catch(_=>c));return{then:l.then.bind(l),download:c}}getPCM(e,t){var k,re,P;if(typeof WritableStream=="undefined"){this.log.warn("getPCM failed: browser not support WritableStream");return}let{enable:r,sampleRate:s=48e3,channelCount:n=1,port:a}=(t===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!r)return;this.log.info(`getPCM ${t||"local"}`);let c=Math.floor(s*.04),l=new Float32Array(c),u=new Float32Array(c),m,h,_=0,g=new AbortController,E=t===""?(k=this._localAudioTrack)==null?void 0:k.mediaTrack:(P=(re=this.room)==null?void 0:re.remotePublishedUserMap.get(t))==null?void 0:P.remoteAudioTrack.mediaTrack;if(!E){this.log.info(`getPCM failed: ${t||"local"} has no audio track`);return}let A=Ee().createMediaStreamSource(new MediaStream([E]));return Gn([A],s,n,a).then(Qe=>Qe.pipeTo(new WritableStream({write(N){N[0][0]&&(_+N[0][0].length>c?(l.set(N[0][0].subarray(0,c-_),_),m=N[0][0].subarray(c-_),N[0][1]&&(u.set(N[0][1].subarray(0,c-_),_),h=N[0][1].subarray(c-_)),_+=c-_):(m&&(l.set(m,_),_+=m.length,m=void 0),h&&(u.set(h,_),h=void 0),l.set(N[0][0],_),N[0][1]&&u.set(N[0][1],_),_+=N[0][0].length),_>=c&&(_=0,e({userId:t,sampleRate:s,channelCount:n,data:n===1?l:[l,u]}),l=new Float32Array(c),u=new Float32Array(c)))}}),g).catch(N=>this.log.warn(`stop getPCM reason:${N}`))),g}get hasScreenAudioTrack(){return!T(this._localScreenAudioTrack)}get hasAudioTrack(){return!T(this._localAudioTrack)}changeInput(e){var t,r;if(e instanceof To)return this._localScreenAudioTrack=e,this.isScreenAudioNeedAudioProcess&&((t=this.audioProcessor)!=null&&t.screenAudioWorkletNode)&&(e.addAudioProcessor(this.audioProcessor.screenAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((s,n)=>{e.mixAudioReference(s,n)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof kt)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&((r=this.audioProcessor)!=null&&r.localAudioWorkletNode)&&(e.addAudioProcessor(this.audioProcessor.localAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((s,n)=>{e.mixAudioReference(s,n)})),e.pipeline.connect(),this.mixOnChange();if(e instanceof gi)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixAudioReference(e,t){var r;(r=this._localAudioTrack)==null||r.mixAudioReference(e,t)}unMixAudioReference(e){var t;(t=this._localAudioTrack)==null||t.unMixAudioReference(e)}setAudioReferenceVolume(e,t){var r;(r=this._localAudioTrack)==null||r.setAudioReferenceVolume(e,t)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var e,t;return delete this.mixChangedDebounce,Promise.all([(e=this._localAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(e){e instanceof To?delete this._localScreenAudioTrack:e instanceof kt?delete this._localAudioTrack:e instanceof gi}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}addAudioProcessor(e,t,r,s){var n;this.audioProcessor={localAudioWorkletNode:r,mixNode:e,silentNode:t,screenAudioWorkletNode:s},this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&r&&(this._localAudioTrack.addAudioProcessor(r,e,t),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localAudioTrack)==null||l.mixAudioReference(a,c)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&s&&((n=this._localScreenAudioTrack)==null||n.addAudioProcessor(s,e,t),this.audioReferenceMap.forEach((a,c)=>{var l;(l=this._localScreenAudioTrack)==null||l.mixAudioReference(a,c)}))}removeDenoiser(e){var t;return delete this.denoiser,(t=this._localAudioTrack)==null?void 0:t.removeDenoiser(e)}addVoiceChanger(e,t){var r;this.voiceChanger=[e,t],(r=this._localAudioTrack)==null||r.pipeline.voiceChanger.setNode(e,t)}removeVoiceChanger(){var e;delete this.voiceChanger,(e=this._localAudioTrack)==null||e.pipeline.voiceChanger.deleteNode()}removeAudioProcessor(e,t){var r,s;delete this.audioProcessor,(r=this._localAudioTrack)==null||r.removeAudioProcessor(e),(s=this._localScreenAudioTrack)==null||s.removeAudioProcessor(t)}destroy(){this.close(),this.audioReferenceMap.clear(),this.getPCMAbortCtrlMap.forEach(e=>e==null?void 0:e.abort("destroy")),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}handleLocalTrackStarted({room:e,userId:t}){var s;if(e!==this.room||this.getPCMAbortCtrlMap.get(t))return;let r=this.getPCM(n=>{var a;(a=this.room)==null||a.emit("audio-frame",n)},"");this.getPCMAbortCtrlMap.set(t,r),this.getPCMAbortCtrlMap.get(t)&&((s=this._localAudioTrack)==null||s.on("input-media-track-changed",()=>{let n=this.getPCMAbortCtrlMap.get(t);n&&(n.abort("inputMediaTrackChanged"),n=this.getPCM(a=>{var c;(c=this.room)==null||c.emit("audio-frame",a)},""),this.getPCMAbortCtrlMap.set(t,n))}))}handleLocalTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(t))}handleRemoteTrackStarted({room:e,userId:t}){if(e===this.room&&!this.getPCMAbortCtrlMap.get(t)){let r=this.room.audioManager.getPCM(s=>{var n;(n=this.room)==null||n.emit("audio-frame",s)},t);this.getPCMAbortCtrlMap.set(t,r)}}handleRemoteTrackStopped({room:e,userId:t}){if(e!==this.room)return;let r=this.getPCMAbortCtrlMap.get(t);r&&(r.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(t))}installEvent(){S.on("113",this.handleLocalTrackStarted,this),S.on("114",this.handleLocalTrackStopped,this),S.on("115",this.handleRemoteTrackStarted,this),S.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){S.off("113",this.handleLocalTrackStarted),S.off("114",this.handleLocalTrackStopped),S.off("115",this.handleRemoteTrackStarted),S.off("116",this.handleRemoteTrackStopped)}updateAudioReference({type:e,audioReference:t,refId:r,volume:s}){if(e==="add"){if(this.audioReferenceMap.get(r)||!t||(this.audioReferenceMap.set(r,t),!this.audioProcessor))return;this.mixAudioReference(t,r)}else if(e==="remove")this.audioReferenceMap.get(r)&&(this.audioReferenceMap.delete(r),this.unMixAudioReference(r));else if(e==="updateVolume"){if(!this.audioProcessor||T(s))return;this.setAudioReferenceVolume(r,s)}}};function Eo(o=30,i=2){return Q((e,t)=>function(...r){return new Promise((s,n)=>{let a=setTimeout(()=>{let c=new D({code:I.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${o}s`});(this.log||this._log||R).warn(c),i===2?n(c):i===1&&s()},o*1e3);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(a),e.apply(this,r).then(s,n).finally(()=>{clearTimeout(a),this._checkPendingPromiseSet&&a&&this._checkPendingPromiseSet.delete(a)})})})}function Tf(){return Q((o,i)=>function(...e){return this._checkPendingPromiseSet&&(this._checkPendingPromiseSet.forEach(t=>clearTimeout(t)),this._checkPendingPromiseSet.clear()),o.apply(this,e)})}var Mi=class Mi extends no{constructor(e,t,r){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:r,room:e});this.room=e;this.user=t;d(this,"tinyId");d(this,"isRemote",!0);d(this,"jitterBufferDelay",0);d(this,"availableState");d(this,"remotePublishState");d(this,"_triggerCheckDecodeSubject",ot(ce(this,Mi.STATE_SUBSCRIBE)));d(this,"ignoreUpdatePlayingState");this.tinyId=t.tinyId,this.availableState=new J(`${t.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new J(`${t.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),de(Ln(ce(this,J.STATECHANGED),ce(this.remotePublishState,J.STATECHANGED)),Fn(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),Te(c=>{this.availableState.state!==(c?J.ON:J.OFF)&&(this.availableState.state=c?J.ON:J.OFF),!(this.isRemotePublished&&this.ignoreUpdatePlayingState)&&this.updatePlayingState(c)}));let s=de(ce(this.player,ue.ERROR),$t(c=>c.code===MediaError.MEDIA_ERR_DECODE)),n=de(Un(5e3),$t(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived?!1:this.player.isPlaying||(this.kind===f.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)?(this.reportDecodeResult(!0),!1):!0)),a=de(xu(s,n),ke(ce(this,J.INIT)));de(this._triggerCheckDecodeSubject,$t(()=>!this.ignoreDecodeError),mo(a),Te(c=>{this.reportDecodeResult(!1,c)}))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get ignoreDecodeError(){var t,r;return(((r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===Mi.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===J.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){var s,n;let r=this.kind===f.AUDIO;if(v[e?"addSuccessEvent":"addFailedEvent"]({key:r?504700:514702}),!r){let a=((s=this.room)==null?void 0:s.downlinkVideoCodec.toUpperCase())||"H264";v[e?"addSuccessEvent":"addFailedEvent"]({key:rs[`DECODE_${a}_RESULT`]}),e||this.log.warn(`${(n=this.room)==null?void 0:n.downlinkVideoCodec} decode failed`)}e||(v.addEnum({key:r?504701:514703,value:Zr()}),se.uploadEvent({log:`stat-decode-failed-${this.kind}-${si()||ni()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===f.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.player.isPlayCalled&&this.player.setTrack(this.playerMediaTrack),this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isRemotePublished} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?J.ON:J.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};d(Mi,"STATE_SUBSCRIBE","subscribe"),M([Eo(5,1)],Mi.prototype,"waitHasMediaTrack",1),M([ye(J.INIT,Mi.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),S.emit(C.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),Rt(521716,!1)],Mi.prototype,"subscribe",1),M([ye(Mi.STATE_SUBSCRIBE,J.INIT,{sync:!0,success(){this.log.info("unsubscribed"),S.emit(C.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],Mi.prototype,"unsubscribe",1);var Ts=Mi;var gi=class extends Ts{constructor(e,t){super(e,t,1);d(this,"volume",0);d(this,"mediaType",1);d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}get dbVolume(){return so.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}onPlayerError(e){this.enableDecodeFrame&&(this._log.warn("use audio decoder"),this.room.enableInsertableStreams())}get enableDecodeFrame(){var e,t;return this.manager?this.manager.decodePipeline.some(r=>r)||((t=(e=this.player.element)==null?void 0:e.error)==null?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&Ec().AudioDecoder&&hi:!1}get enableDecryptFrame(){return this.manager&&!!this.manager.decodePipeline[0]}decodeFrame(e){if(!this.manager)return e;let t=e;for(let[r,s]of this.manager.decodePipeline.entries()){if(!s)continue;let n={frame:e,track:this};if(r===1&&this.isAvailable&&this.room.role==="audience"&&(n.onAudioFrameNTPTime=({ntp:a,frame:c,hasLeavingTag:l})=>{this.emit("audio-frame-with-ntp",{ntp:a,frame:c,hasLeavingTag:l})}),t=s(n),!t)return}return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}};var id=class extends Ue{constructor(e,t,r,s,n){super(e,{useDefaultProgram:!0,useFbo:!0,name:"alpha",create2d:!0,logger:t});this.setContainer=s;d(this,"initStat",{alphaStitchingType:1});d(this,"end",ot());d(this,"minSize",320);d(this,"maxSize",1280);d(this,"draggable",!1);d(this,"startDragX",0);d(this,"startDragY",0);d(this,"left",0);d(this,"top",0);d(this,"baseWidth",320);d(this,"baseRatio");d(this,"container");this.initStat=n,this.draggable=r,this.bindDragEvents()}bindDragEvents(){let e=this.context._canvas;if(e)if(this.draggable){let t=ke(this.end);de(ce(e,"mousedown"),Bn(this.startDrag.bind(this)),Mr(()=>de(ce(window,"mousemove"),ke(ce(window,"mouseup")))),t,Te(this.doDrag.bind(this))),de(ce(e,"dblclick"),t,Te(this.resetPosition.bind(this))),de(ce(e,"wheel"),t,Te(this.handleZoom.bind(this))),this.renderCanvas()}else{if(!this.container)return;this.container.style.removeProperty("left"),this.container.style.removeProperty("top"),this.end.next()}}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}startDrag(e){e.preventDefault(),e.button===0&&(this.startDragX=e.clientX-this.left,this.startDragY=e.clientY-this.top)}renderCanvas(){let{container:e}=this;e||this.setContainer(),!(!e||!this.baseRatio||!this.draggable)&&(e.style.setProperty("width",`${this.baseWidth}px`),e.style.setProperty("height",`${this.baseWidth/this.baseRatio}px`),e.style.setProperty("position","fixed"),e.style.setProperty("left",`${this.left}px`),e.style.setProperty("top",`${this.top}px`))}doDrag(e){e.preventDefault(),this.left=e.clientX-this.startDragX,this.top=e.clientY-this.startDragY,this.renderCanvas()}handleZoom(e){e.preventDefault();let t=.1,r=e.deltaY,s=this.context._canvas;s&&(this.baseWidth||(this.baseWidth=s.offsetWidth),r<0?this.baseWidth=Math.min(this.baseWidth*(1+t),this.maxSize):this.baseWidth=Math.max(this.baseWidth*(1-t),this.minSize),this.renderCanvas())}resetPosition(){this.left=0,this.top=0,this.renderCanvas()}onRatioReset(){this.renderCanvas()}draw2d(e,t,r,s,n){var _;let{ctx2d:a}=this,c=this.context._canvas;if(!a||!c)return!1;let l=super.draw2d(e,t,r,s,n),u=a.getImageData(0,0,s,n),{data:m}=u,h=!1;if(this.initStat.alphaStitchingType===1){let g=Math.floor(s/2);for(let E=0;E<n;E++)for(let A=0;A<g;A++){let k=(E*s+A)*4,re=A+g,P=(E*s+re)*4,Qe=m[P];m[P+3]=0;let N=Qe>=100;m[k+3]=N?255:0}h=super.draw2d(u,0,0,0,0,g,n),c.width=g}else if(this.initStat.alphaStitchingType===2){let g=Math.floor(n/2);for(let E=0;E<g;E++)for(let A=0;A<s;A++){let k=(E*s+A)*4,P=((E+g)*s+A)*4,Qe=m[P];m[P+3]=0;let N=Qe>=100;m[k+3]=N?255:0}h=super.draw2d(u,0,0,0,0,s,g),c.height=g}return(_=this.context.ctx)==null||_.clearRect(0,0,s,n),l&&h}close(){this.baseRatio=void 0,this.end.next(),this.end.complete()}};function MS(o){return[15,30,45,60].reduce((e,t)=>Math.abs(t-o)<Math.abs(e-o)?t:e)}var Oi=class extends Ts{constructor(e,t,r=4){super(e,t,r);d(this,"mediaType",4);d(this,"source");d(this,"shouldRenderAlpha",!1);d(this,"alphaNode");d(this,"shouldBeDraggable",!0);d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager,this.on("first-video-frame",s=>{this.room.emit("first-video-frame",s)})}isAlphaSei(e){if(this.userId!==e.userId||e.seiPayloadType!==50)return!1;let t=new Uint8Array(e.data);return t.length%3!==0||t[0]!==0||t[1]!==1?!1:t}play(e,t){return(he(t==null?void 0:t.canvasRender)?t.canvasRender:et===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat(),S.emit("156",{track:this,player:this.player})})}updateAlphaRenderInfo(e){let t=this.isAlphaSei(e);if(t)if(!this.alphaNode)this.shouldRenderAlpha=!0,this.player.shouldRenderAlpha=!0,this.useCanvasPlayer(t[2]);else{let r=t[2];if(this.alphaNode.baseRatio&&this.alphaNode.initStat.alphaStitchingType===r)return;this.alphaNode.initStat={alphaStitchingType:r};let s=this.player.getElement();if(s){let n=s.videoWidth/s.videoHeight;n&&(this.alphaNode.baseRatio=n*(r===1?.5:2),this.alphaNode.onRatioReset())}this.player.canvas&&(this.player.canvas.id=this.generateAlphaCanvasName(r))}}generateAlphaCanvasName(e){let t="alpha",r=hn[e];return`${t}_${r}_${this.userId}`}useCanvasPlayer(e){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let t=new Xe({frameRate:15,logger:this.log,name:this.shouldRenderAlpha&&e?this.generateAlphaCanvasName(e):this.userId});t.create({alpha:this.shouldRenderAlpha,willReadFrequently:this.shouldRenderAlpha});let r=new fo(t,{name:"remotePlayer",logger:this.log});if(this.source=t.createVideoPlayerSource(this.player),this.player.setCanvas(t._canvas),this.shouldRenderAlpha&&e){let s=()=>{!this.player.container||!this.alphaNode||(this.alphaNode.container=this.player.container,this.alphaNode.renderCanvas())},n=new id(t,this.log,this.shouldBeDraggable,s,{alphaStitchingType:e});this.source.connect(n),n.connect(r),this.alphaNode=n}else this.source.connect(r);Ki()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,t),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=MS(t);if(!z(t)||t<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${t} `);return}if(r===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${r} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${t}, closest: ${r}, current: ${e.frameRate}`),e.frameRate=r}get decodeFPS(){var n;let{msg_video_status:e}=((n=this.room.heartbeatReport)==null?void 0:n.msg_down_stream_info.find(a=>a.msg_user_info.str_identifier===this.userId))||{},t=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let r=e.find(a=>a.uint32_video_stream_type===t);return(r==null?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),S.emit("157",{track:this,player:this.player}),this.alphaNode&&this.alphaNode.close(),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&(e=t({frame:e,track:this}),!e))return;return e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}setDraggable(e){this.shouldBeDraggable=e,this.alphaNode&&(this.alphaNode.draggable=e,this.alphaNode.bindDragEvents())}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},Es=class extends Oi{constructor(e,t){super(e,t,2);d(this,"mediaType",2);d(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var Ss=new Map;S.on(C.JOIN_SUCCESS,({room:o})=>{Ne(o.userId,{eventId:32788})});S.on(C.LEAVE_START,({room:o})=>{Ne(o.userId,{eventId:32789})});S.on(C.LOCAL_TRACK_PUBLISHED,({track:o})=>{if(o.room){let i=32769;o.mediaType===4?i=32768:o.mediaType===2&&(i=32805),Ne(o.room.userId,{eventId:i})}});S.on(C.LOCAL_TRACK_UNPUBLISHED,({track:o})=>{if(o.room){let i=32771;o.mediaType===4?i=32770:o.mediaType===2&&(i=32806),Ne(o.room.userId,{eventId:i})}});S.on(C.TRACK_MUTED,({track:o})=>{o.room&&(o.kind===f.AUDIO?Ne(o.room.userId,{eventId:o.isRemote?32785:32772,remoteUserId:o.isRemote?o.userId:void 0}):Ne(o.room.userId,{eventId:o.isRemote?32784:32773,remoteUserId:o.isRemote?o.userId:void 0}))});S.on(C.TRACK_UNMUTED,({track:o})=>{o.room&&(o.kind===f.AUDIO?Ne(o.room.userId,{eventId:o.isRemote?32787:32774,remoteUserId:o.isRemote?o.userId:void 0}):Ne(o.room.userId,{eventId:o.isRemote?32786:32775,remoteUserId:o.isRemote?o.userId:void 0}))});S.on(C.REMOTE_TRACK_SUBSCRIBED,({track:o})=>{o.room&&(o.mediaType===1&&Ne(o.room.userId,{eventId:32777,remoteUserId:o.userId}),o.mediaType===4&&Ne(o.room.userId,{eventId:32776,remoteUserId:o.userId}),o.mediaType===8&&Ne(o.room.userId,{eventId:32803,remoteUserId:o.userId}))});S.on(C.REMOTE_TRACK_UNSUBSCRIBED,({track:o})=>{o.room&&(o.mediaType===1&&Ne(o.room.userId,{eventId:32779,remoteUserId:o.userId}),o.mediaType===4&&Ne(o.room.userId,{eventId:32778,remoteUserId:o.userId}),o.mediaType===8&&Ne(o.room.userId,{eventId:32804,remoteUserId:o.userId}))});S.on(C.SWITCH_DEVICE_SUCCESS,({track:o})=>{o.room&&Ne(o.room.userId,{eventId:o.kind===f.VIDEO?32780:32781})});S.on(C.LOCAL_TRACK_REPLACED,({track:o})=>{o.room&&Ne(o.room.userId,{eventId:o.kind===f.VIDEO?32782:32783})});S.on(C.SIGNAL_CONNECTION_STATE_CHANGED,({room:o,prevState:i,state:e})=>{let t;switch(e){case"CONNECTED":i==="RECONNECTING"?t=32795:t=32791;break;case"DISCONNECTED":i==="RECONNECTING"?t=32796:t=32790;break;case"RECONNECTING":t=32794;break}t&&Ne(o.userId,{eventId:t})});S.on(C.PEER_CONNECTION_STATE_CHANGED,({room:o,prevState:i,state:e,remoteUserId:t})=>{let r=!!t,s;switch(e){case"CONNECTED":i==="RECONNECTING"?s=r?32801:32798:s=r?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(s=r?32802:32799);break;case"RECONNECTING":s=r?32800:32797;break}s&&Ne(o.userId,{eventId:s,remoteUserId:t})});S.on(C.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:o,userId:i,remoteUserId:e,codec:t,isHWCodec:r,prevImplementation:s,streamType:n})=>{let a=r?1:0;s||(a=r?3:2);let c={H264:0,H265:1,VP8:2}[t.toUpperCase()],l={eventId:4004,param1:a,param2:c,streamType:n||2};e&&(l.remoteUserId=e,l.eventId=4005),Ne(i,l),v.addEnum({key:e?514701:513701,value:a}),v.addEnum({key:e?514700:513700,value:c})});S.on(C.LOCAL_TRACK_RECAPTURE,({track:o,error:i})=>{if(o.userId){let e={eventId:2003,param1:0};o.kind===f.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=o.streamType==="auxiliary"?7:2,i&&(e.param1=8)),Ne(o.userId,e)}});function Ne(o,i){let e=L(O({},i),{timestamp:Fi()});Ss.has(o)?Ss.get(o).push(e):Ss.set(o,[e])}function Ef(o){if(Ss.has(o)){let i=Ss.get(o).map(e=>({uint32_event_id:e.eventId,uint64_date:e.timestamp,str_userid:e.remoteUserId,uint32_param1:e.param1,uint32_param2:e.param2,uint32_video_stream_type:e.streamType}));return Ss.delete(o),i}return[]}function Sf(...o){return Q((i,e)=>function(...t){return OS.call(this,o,t,e,this._name),i.apply(this,t)})}function OS(o,i,e,t){try{if(Ie(o))for(let r=0;r<o.length;r++)rd.call(this,{rule:o[r],value:i[r],key:o[r].name,fnName:e,className:t});else rd.call(this,{rule:o,value:i[0],key:o.name,fnName:e,className:t})}catch(r){throw R.error(r),r}}function rd({rule:o,value:i,key:e,fnName:t,className:r}){if(T(i)){if(o.required)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_REQUIRED,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(T(o.defaultValue))return;i=o.defaultValue}if(Array.isArray(o.type)){let a=!1;for(let c=0;c<o.type.length;c++)o.type[c]===null&&i===null&&(a=!0),le(o.type[c])&&i instanceof o.type[c]&&(a=!0),ie(o.type[c])&&Me(i)===o.type[c].toLowerCase()&&(a=!0);if(!a)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_TYPE,data:{key:e,rule:{type:o.type.map(c=>jr(c)?xo(c):ie(c)?c:Me(c))},fnName:t,value:i},link:{className:r,fnName:t}})})}else if(!T(o.type)&&Me(i)!==o.type)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_TYPE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(o.allowEmpty===!1){let a=z(i)&&(i===0||Number.isNaN(i)),c=ie(i)&&i.trim()==="";if(a||c)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_EMPTY,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})})}if(o.notLessThanZero&&z(i)&&i<0)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.CANNOT_LESS_THAN_ZERO,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(o.min)&&z(i)&&i<o.min)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_MIN,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(!T(o.max)&&z(i)&&i>o.max)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_MAX,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(ie(o.instanceOf)){if(!i||i._name!==o.instanceOf)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})})}else if(le(o.instanceOf)&&!(i instanceof o.instanceOf))throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});if(o.values&&!o.values.includes(i))throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PARAMETER_RANGE,data:{key:e,rule:o,fnName:t,value:i},link:{className:r,fnName:t}})});let{properties:s}=o;dt(s)&&yt(i)&&Object.keys(s).forEach(a=>{rd.call(this,{rule:s[a],value:i&&i[a],key:`${e}.${a}`,fnName:t,className:r})});let{arrayItem:n}=o;dt(n)&&Ie(i)&&i.forEach((a,c)=>{rd.call(this,{rule:n,value:a,key:`${e}[${c}]`,fnName:t,className:r})}),le(o.validate)&&o.validate.call(this,i,e,t,r,this)}var If=Ge(at(),1);var od=class extends If.EventEmitter{constructor(e,t,r="userId"){super();this.mySelfId=e;this._log=t;this.key=r;d(this,"userMap",new Map);d(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(e=>e.isRobot)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:r,tinyId:s,role:n}=e;if(this.userMap.has(t))return;let a={userId:r,tinyId:s,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let r=this.userMap.get(e);if(!r)return;let s=`peer leave [${e}]`;T(t)||(s+=`:${rl[t]}`),this._log.info(s);let n=this.remotePublishedUserMap.get(e);if(n){let a=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",r.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(r=>r[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){this.remotePublishedUserMap.has(e)&&this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let r=t[this.key];if(e.findIndex(s=>s[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let s=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:s,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var u;let r=t[this.key];if(r===this.mySelfId){this.emit("7",t);return}let{flag:s,userId:n,tinyId:a}=t,c=Kt(s,n),l=(u=this.remotePublishedUserMap.get(r))==null?void 0:u.muteState;if(l){let m=this.remotePublishedUserMap.get(r);m&&m.flag!==s&&(m.flag=s,this._log.info(`remote publish updated: ${JSON.stringify(m.muteState)}`),this.emit("6",{prevMuteState:l,muteState:c,flag:s}))}else this._log.info(`remote publish. state: ${JSON.stringify(c)}`),this.addUser({userId:n,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:Kt(0,n),muteState:c,flag:s})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function Ch({timesInSecond:o,maxSizeInSecond:i,getSize:e}){return Q((t,r)=>{let s=new WeakMap;return S.on(C.ROOM_DESTROY,({room:n})=>s.delete(n)),function(...n){let a=s.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=o||a.totalSizeInSecond>i))throw new D({code:I.INVALID_OPERATION,message:H({key:F.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=o,isSize:a.totalSizeInSecond>i,name:r,timesInSecond:o,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var kS="2025-12-12 18:02:21",Af=!0,Cf=function(){var o;if(Af){Af=!1,R.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${ft}/en/index.html`),console.info(`* Changelog: ${ft}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),R.info("TRTC Web SDK Version:",He),oi||R.debug("Build Time:",kS);let i=`UA: ${navigator.userAgent}
|
|
53
53
|
CPU core: ${navigator.hardwareConcurrency}, GPU: ${Pl()}`,e=navigator.deviceMemory;e&&(i+=`, minRAM: ${e}GB`),R.info(i),R.info(`URL: ${location.href}${((o=self.frameElement)==null?void 0:o.tagName)==="IFRAME"?" in iframe":""}`),Yr().then(t=>{t&&R.info(ti)})}};var So={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"};var $={INVALID_PARAMETER:5e3,INVALID_OPERATION:5100,ENV_NOT_SUPPORTED:5200,DEVICE_ERROR:5300,SERVER_ERROR:5400,OPERATION_FAILED:5500,OPERATION_ABORT:5998,UNKNOWN_ERROR:5999},wt=(y=>(y[y.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",y[y.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",y[y.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",y[y.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",y[y.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",y[y.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",y[y.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",y[y.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",y[y.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",y[y.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",y[y.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",y[y.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",y[y.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",y[y.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",y[y.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",y[y.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",y[y.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",y[y.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",y[y.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",y[y.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",y[y.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",y[y.INVALID_OPERATION=5100]="INVALID_OPERATION",y[y.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",y[y.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",y[y.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",y[y.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",y[y.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",y[y.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",y[y.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",y[y.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",y[y.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",y[y.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",y[y.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",y[y.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",y[y.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",y[y.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",y[y.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",y[y.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",y[y.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",y[y.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",y[y.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",y[y.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",y[y.DEVICE_ERROR=5300]="DEVICE_ERROR",y[y.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",y[y.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",y[y.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",y[y.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",y[y.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",y[y.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",y[y.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",y[y.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",y[y.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",y[y.NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX=5310]="NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX",y[y.SERVER_ERROR=5400]="SERVER_ERROR",y[y.NEED_TO_BUY=5401]="NEED_TO_BUY",y[y.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",y[y.OPERATION_FAILED=5500]="OPERATION_FAILED",y[y.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",y[y.REJOIN_FAILED=5502]="REJOIN_FAILED",y[y.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",y[y.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",y[y.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",y[y.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",y[y.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",y[y.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",y[y.OPERATION_ABORT=5998]="OPERATION_ABORT",y[y.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",y))(wt||{});function yf({code:o,params:i,enableDocLink:e=!1}){let t="",r,s=wt[o];try{r=Rf[s]}catch(n){r=Rf.UNKNOWN_ERROR}return le(r)?t=r(i):ie(r)&&(t=r),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var Rf=L(O({},Je),{INVALID_PARAMETER({fnName:o}){return`the parameters of the '${o}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s="";return Array.isArray(i.type)?s=i.type.join("|"):s=i.type,`'${r}' must be type of ${s} when calling ${e}(), received type: ${Me(t)}.`},INVALID_PARAMETER_EMPTY({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:o,rule:i,fnName:e,value:t}){let r=`${o||i.name}`,s=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${s} when calling ${e}(), received type: ${Me(t)}.`},INVALID_PARAMETER_RANGE({key:o,rule:i,fnName:e,value:t}){return`'${o||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:o,rule:i,fnName:e}){return`'${o||i.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:o,rule:i,value:e}){return`the min value of ${o||i.name} is ${i.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:o,rule:i,value:e}){return`the max value of ${o||i.name} is ${i.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:o,fnName:i}){return`'${o}' is not found in the document object when calling ${i}().`},INVALID_ELEMENT_ID_TYPE({key:o,fnName:i,type:e}){return`the element corresponding to '${o}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`},INVALID_STREAM_ID({key:o}){return`'${o}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:o}){return`'${o}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:o}){return`'${o}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:o}){return`'${o}' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.`},INVALID_ROOM_ID_REQUIRED(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},INVALID_ROOM_ID_TYPE_MISMATCH({key:o}){return`The type of target roomId must match the current roomId. Current room is using '${o}', but received '${o==="strRoomId"?"roomId":"strRoomId"}'.`},INVALID_ROOM_ID_DUPLICATE({key:o}){return`the target '${o}' must not be the same as the current '${o}'.`},INVALID_STREAM_TYPE:({fnName:o})=>`'streamType' is required when 'userId' is not '*', calling ${o}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:o}){return`the API '${o}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:o}){return`cannot ${o} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:o,value:i}){return`cannot ${o} because remote user(userId: ${i.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:o,value:i}){return`cannot ${o} because remote user(userId: ${i.userId}) does not publishing ${i.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:o}){return`you are already ${o}(), cannot repeated call '${o}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:o}){return`cannot call '${o}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:o}){return`cannot call '${o}' because the microphone or screen share is not turned on.`},INVALID_BUFFER_EMPTY:({key:o})=>`the buffer size of paramerter '${o}' cannot be empty`,INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>"role: 'audience' cannot call this api.",INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:({fnName:o})=>`you need to call ${o}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:o}){return`the current browser does not support the capability of the function '${o}' you are calling, please check the API documentation.`},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION({fnName:o}){return`cannot call ${o} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:o,error:i}){return`'${o}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`NotFoundError, no ${i} detected, please check your device and the configuration on '${o}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`NotAllowedError, you have disabled ${i} access, please allow the current application to use the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_READABLE_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`NotReadableError, the ${i} maybe in use by another APP, please check if the device is pre-occupied by another APP.`},DEVICE_OVERCONSTRAINED_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct${e?`, error: ${e.toString()}.`:"."}`},DEVICE_INVALID_STATE_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`InvalidStateError, after the user clicks and interacts with the page, turn on the ${i}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_SECURITY_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`SecurityError, check whether the system security policy restricts the use of the ${i}, and it is recommended to turn on the ${i} after the user interacts with the page${e?`, error: ${e.toString()}.`:"."}`},DEVICE_ABORT_ERROR({fnName:o,deviceType:i=Io(o),error:e}){return`AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal${e?` error: ${e.toString()}.`:"."}`},CAMERA_RECOVER_FAILED({error:o}){return`camera recover capture failed ${(o==null?void 0:o.name)||""}: ${(o==null?void 0:o.originMessage)||(o==null?void 0:o.message)}`},MICROPHONE_RECOVER_FAILED({error:o}){return`microphone recover capture failed ${(o==null?void 0:o.name)||""}: ${(o==null?void 0:o.originMessage)||(o==null?void 0:o.message)}`},OPERATION_FAILED({fnName:o,error:i}){return`'${o}' failed, reason: ${i==null?void 0:i.toString()}`},FIREWALL_RESTRICTION(){return"media connection failure due to firewall restrictions, please try to change your network."},EVENT_HANDLER_ERROR({eventName:o}){return`an error was caught on trtc.on('${o}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:o,error:i}){return`video context error ${o} ${(i==null?void 0:i.name)||""} ${(i==null?void 0:i.message)||""}`},SERVER_ERROR({fnName:o,error:i}){return`'${o}' got server error: ${i==null?void 0:i.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:o,url:i}){return`You need to buy packages for ${o}. Refer to: ${i}`},ACCOUNT_NO_MONEY:({fnParams:o})=>`your TRTC account run out of credit, please recharge.${o.sdkAppId?` SDKAppId: ${o.sdkAppId}`:""}`,OPERATION_ABORT({fnName:o}){return`'${o}' abort`},UNKNOWN_ERROR({fnName:o,error:i}){return`'${o}' throw unknown exception${i?`, error: ${i.toString()}.`:"."}`}});function Io(o){if(!o)return"camera";let i=o.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var Rh=class o extends Error{constructor({code:e,extraCode:t,message:r="",messageParams:s,fnName:n="",originError:a,data:c}){var u;let l;r?l=r:l=yf({code:e===$.SERVER_ERROR?e:t||e,params:O({fnName:n,error:a},s)});super(l);d(this,"name","RtcError");d(this,"code");d(this,"extraCode");d(this,"functionName");d(this,"message");d(this,"data");d(this,"handler");d(this,"originError");this.name=wt[e],this.code=e,this.extraCode=t,this.functionName=n,this.originError=a,this.message=l,this.data=c,this.extraCode===5302&&((u=this.originError)!=null&&u.message.includes("system"))&&(this.handler=()=>{let m={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},h={startLocalVideo:"webcam",startLocalAudio:"microphone"},_=document.createElement("a");Qr?_.href=`ms-settings:privacy-${h[this.functionName]}`:ri&&(_.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${m[this.functionName]}`),_.href.length>0&&_.click()})}static convertFrom(e,t,r){let s=e;if(e instanceof D){let{stack:n}=e,a={code:$.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case I.INVALID_PARAMETER:a.code=$.INVALID_PARAMETER,a.message=e.message;break;case I.INVALID_OPERATION:a.code=$.INVALID_OPERATION;break;case I.NOT_SUPPORTED:case I.NOT_SUPPORTED_H264:a.code=$.ENV_NOT_SUPPORTED,e.getCode()===I.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(Je.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case I.JOIN_ROOM_FAILED:a.messageParams={fnParams:r};case I.SERVER_TIMEOUT:case I.SWITCH_ROLE_FAILED:case I.SWITCH_ROOM_FAILED:a.code=$.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case I.API_CALL_ABORTED:a.code=$.OPERATION_ABORT;break;case I.DEVICE_NOT_FOUND:case I.DEVICE_AUTO_RECOVER_FAILED:case I.INITIALIZE_FAILED:a.code=5300,e.name&&(a.extraCode=PS(e.name));break;case I.VIDEO_ENCODE_FAILED:a.extraCode=5505;case I.AUDIO_ENCODE_FAILED:a.extraCode=5506,a.code=$.OPERATION_FAILED;break;case I.UNKNOWN:break;default:a.code=$.OPERATION_FAILED}s=new o(a),n&&(s.stack+=n.substr(n.indexOf(`
|
|
54
|
-
`)))}else{if(e instanceof o)return e;s=new o({code:$.UNKNOWN_ERROR,fnName:t,originError:e})}return s}};function PS(o){let i;switch(o){case"NotFoundError":i=5301;break;case"NotAllowedError":i=5302;break;case"NotReadableError":i=5303;break;case"OverconstrainedError":i=5304;break;case"InvalidStateError":i=5305;break;case"SecurityError":i=5306;break;case"AbortError":i=5307;break;default:i=5300}return i}var V=Rh;function ki(o){return o==="sub"?"auxiliary":o==="auxiliary"?"sub":"main"}function qn(o){return o===So.QOS_PREFERENCE_CLEAR?"detail":o===So.QOS_PREFERENCE_SMOOTH?"motion":""}function Is(o,i){let e=i?zd:pr;return Il(o)?O(O({},e),o):zt[o]?zt[o]:e}var bf={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{type:["string","object","boolean"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},vf={type:"object",properties:{systemAudio:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},profile:{type:["string","object"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack},audioTrack:{instanceOf:MediaStreamTrack}}},As={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(o,i,e){if(ie(o)&&!document.getElementById(o))throw new V({code:$.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},Nf={name:"userId",required:!0,type:"string"},Df={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{type:["string","object"],properties:{bitrate:{type:"number"},channelCount:{type:"number"}}},echoCancellation:{values:[!0,!1,"remote-only","all"]},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function Cs(o,i){if(!o)throw new V({code:$.INVALID_OPERATION,extraCode:5101,fnName:i})}function Mf(o,i,e){if(!o)throw new V({code:$.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}function Of(o,i,e){if(!(/^[1-9]\d*$/.test(String(o))&&o<4294967295))throw new V({code:$.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:e}})}function kf(o,i,e){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(o))throw new V({code:$.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:e}})}var Hw={type:"number",notLessThanZero:!0},wS=(o,i)=>o.width*o.height>=i.width*i.height&&o.frameRate>=i.frameRate&&o.bitrate>=i.bitrate;function Pf(o){var t;if(!((t=o==null?void 0:o.option)!=null&&t.small))return;if(!Tc()){R.warn("small stream is not supported"),delete o.option.small;return}let i=Is(o.option.profile),e=Is(o.option.small,!0);if(!wS(i,e)){R.warn(`small stream profile must be less than big stream profile. Big: ${JSON.stringify(i)}, Small: ${JSON.stringify(e)}`),delete o.option.small;return}}var LS={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(o,i,e){if(this._room.isJoined)throw new V({code:$.INVALID_OPERATION,extraCode:5104,fnName:e});if(o.roomId){if(ie(o.roomId))throw new V({code:$.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});Of(o.roomId,e,i)}else if(o.strRoomId)kf(o.strRoomId,e,i);else throw new V({code:$.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"},playoutDelay:{type:"object",properties:{min:{type:"number",min:0,max:1e3},max:{type:"number",min:0,max:1e4}}}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:As,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:bf},validate(o){var i,e;if(!((i=o==null?void 0:o.option)!=null&&i.videoTrack)&&Zi())throw new V({code:$.ENV_NOT_SUPPORTED,extraCode:5201});(e=o==null?void 0:o.option)!=null&&e.small&&Pf(o)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:L(O({},As),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:bf},validate(o){var i;(i=o==null?void 0:o.option)!=null&&i.small&&Pf(o)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:Df},validate(o){var i;if(!((i=o==null?void 0:o.option)!=null&&i.audioTrack)&&Zi())throw new V({code:$.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:Df}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:As,publish:{type:"boolean"},option:vf},validate(o,i,e,t,r){var s;if(!((s=o==null?void 0:o.option)!=null&&s.videoTrack)){if(Zi())throw new V({code:$.ENV_NOT_SUPPORTED,extraCode:5201});if(!_n())throw new V({code:$.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:As,publish:{type:"boolean"},option:vf}},muteRemoteAudio:[Nf,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[Nf,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:As,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(o,i,e){Cs(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(o.userId);if(Mf(!!t,e,o),t&&(o.streamType==="main"&&!t.muteState.videoAvailable||o.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new V({code:$.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:o}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:L(O({},As),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(o,i,e){Cs(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(o.userId);if(Mf(!!t,e,o),t&&(o.streamType==="main"&&!t.muteState.videoAvailable||o.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new V({code:$.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:o}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(o,i,e){if(o.userId!=="*"&&T(o.streamType))throw new V({code:$.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(o,i,e){Cs(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(o,i,e,t){if(!En)throw new V({code:$.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new V({code:$.INVALID_OPERATION,fnName:e,extraCode:5108});if(o.byteLength>1e3)throw new V({code:$.INVALID_PARAMETER,extraCode:5018,fnName:e});if(o.byteLength===0)throw new V({code:$.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});Cs(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(o,i,e){if(!o&&!this._room.isMainStreamPublished||o&&!this._room.isAuxStreamPublished)throw new V({code:$.INVALID_OPERATION,extraCode:5109,messageParams:{key:i},fnName:e})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(o,i,e,t){if(o.byteLength>1e3)throw new V({code:$.INVALID_PARAMETER,extraCode:5018,fnName:e});if(o.byteLength===0)throw new V({code:$.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(o,i,e){if(Cs(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new V({code:$.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(o,i,e){if(Cs(this._room.isJoined,e),this._room.useStringRoomId&&o.strRoomId===this._room.roomId||!this._room.useStringRoomId&&o.roomId===Number(this._room.roomId))throw new V({code:$.INVALID_PARAMETER,extraCode:5020,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(o.roomId&&this._room.useStringRoomId||!o.roomId&&o.strRoomId&&!this._room.useStringRoomId)throw new V({code:$.INVALID_PARAMETER,extraCode:5019,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(o.roomId)Of(o.roomId,e,i);else if(o.strRoomId)kf(o.strRoomId,e,i);else throw new V({code:$.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{roomId:{type:"number"},strRoomId:{type:"string"},privateMapKey:{type:"string"},userSig:{type:"string",required:!0},autoSubscribeCount:{type:"number",min:0,max:50}}}},We={TRTC:LS};var ut=class extends Error{};function xS(o,i){let e=Gr(o);for(let t=0;t<i.length;t++)ei(e[t],i[t]);return e}function US(o){this._resolve=Promise.resolve(o)}function VS(o){this._reject=Promise.reject(o)}var Pr=class Pr{constructor(i,e){this.instance=i;this.group=e;d(this,"started",!1);d(this,"ops",[]);d(this,"startSame",()=>!0);d(this,"mergeUpdate",xS);let t=Pr.instances.get(i);t?t.set(e,this):Pr.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=Pr.instances.get(i);return t&&t.get(e)||new Pr(i,e)}static gets(i,e){let t=Pr.instances.get(i),r=[];return t&&t.forEach((s,n)=>{e.test(n)&&r.push(s)}),r}action(i,e,t){let r=a=>{var c;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),a},s=a=>{var c,l;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new ut("start failed")),(l=this.currentOp)==null||l.action(),a},n={type:i,action:()=>e(...n.args).then(r,s),args:t,resolve:US,reject:VS};try{switch(this.state){case 1:if(i===0)throw new ut("already started");break;case 4:if(i===2)throw new ut("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(r,s)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new ut("already start");break;case 3:switch(i.type){case 2:throw new ut("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new ut("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new ut("keep stop");if(this.ops.slice(1).forEach(r=>r.reject(t)),this.ops=this.ops.slice(0,1),this.state===3)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,i.args),this.lastOp.promise;case 3:throw new ut("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new ut("start not allowed after update");case 0:throw new ut("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new ut("keep start")),new ut("already start")}}i.promise=new Promise((t,r)=>{i._resolve?i._resolve.then(t):i.resolve=t,i._reject?i._reject.catch(r):i.reject=r});let{action:e}=i;return i.action=()=>e().then(i.resolve,i.reject),this.ops.push(i),i.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}};d(Pr,"instances",new WeakMap);var nr=Pr;var nd=new WeakMap,ad=(o,i)=>{if(i instanceof ut){let{stack:e}=i;i=new V({code:$.OPERATION_ABORT,message:`${o} abort: ${i.message}`,fnName:o}),e&&(i.stack+=e.substr(e.indexOf(`
|
|
54
|
+
`)))}else{if(e instanceof o)return e;s=new o({code:$.UNKNOWN_ERROR,fnName:t,originError:e})}return s}};function PS(o){let i;switch(o){case"NotFoundError":i=5301;break;case"NotAllowedError":i=5302;break;case"NotReadableError":i=5303;break;case"OverconstrainedError":i=5304;break;case"InvalidStateError":i=5305;break;case"SecurityError":i=5306;break;case"AbortError":i=5307;break;default:i=5300}return i}var V=Rh;function ki(o){return o==="sub"?"auxiliary":o==="auxiliary"?"sub":"main"}function qn(o){return o===So.QOS_PREFERENCE_CLEAR?"detail":o===So.QOS_PREFERENCE_SMOOTH?"motion":""}function Is(o,i){let e=i?zd:pr;return Il(o)?O(O({},e),o):zt[o]?zt[o]:e}var bf={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{type:["string","object","boolean"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},vf={type:"object",properties:{systemAudio:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},profile:{type:["string","object"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack},audioTrack:{instanceOf:MediaStreamTrack}}},As={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(o,i,e){if(ie(o)&&!document.getElementById(o))throw new V({code:$.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},Nf={name:"userId",required:!0,type:"string"},Df={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{type:["string","object"],properties:{bitrate:{type:"number"},channelCount:{type:"number"}}},echoCancellation:{values:[!0,!1,"remote-only","all"]},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function Cs(o,i){if(!o)throw new V({code:$.INVALID_OPERATION,extraCode:5101,fnName:i})}function Mf(o,i,e){if(!o)throw new V({code:$.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}function Of(o,i,e){if(!(/^[1-9]\d*$/.test(String(o))&&o<4294967295))throw new V({code:$.INVALID_PARAMETER,extraCode:5013,fnName:i,messageParams:{key:e}})}function kf(o,i,e){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(o))throw new V({code:$.INVALID_PARAMETER,extraCode:5012,fnName:i,messageParams:{key:e}})}var Ww={type:"number",notLessThanZero:!0},wS=(o,i)=>o.width*o.height>=i.width*i.height&&o.frameRate>=i.frameRate&&o.bitrate>=i.bitrate;function Pf(o){var t;if(!((t=o==null?void 0:o.option)!=null&&t.small))return;if(!Tc()){R.warn("small stream is not supported"),delete o.option.small;return}let i=Is(o.option.profile),e=Is(o.option.small,!0);if(!wS(i,e)){R.warn(`small stream profile must be less than big stream profile. Big: ${JSON.stringify(i)}, Small: ${JSON.stringify(e)}`),delete o.option.small;return}}var LS={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(o,i,e){if(this._room.isJoined)throw new V({code:$.INVALID_OPERATION,extraCode:5104,fnName:e});if(o.roomId){if(ie(o.roomId))throw new V({code:$.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});Of(o.roomId,e,i)}else if(o.strRoomId)kf(o.strRoomId,e,i);else throw new V({code:$.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"},playoutDelay:{type:"object",properties:{min:{type:"number",min:0,max:1e3},max:{type:"number",min:0,max:1e4}}}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:As,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:bf},validate(o){var i,e;if(!((i=o==null?void 0:o.option)!=null&&i.videoTrack)&&Zi())throw new V({code:$.ENV_NOT_SUPPORTED,extraCode:5201});(e=o==null?void 0:o.option)!=null&&e.small&&Pf(o)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:L(O({},As),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:bf},validate(o){var i;(i=o==null?void 0:o.option)!=null&&i.small&&Pf(o)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:Df},validate(o){var i;if(!((i=o==null?void 0:o.option)!=null&&i.audioTrack)&&Zi())throw new V({code:$.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:Df}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:As,publish:{type:"boolean"},option:vf},validate(o,i,e,t,r){var s;if(!((s=o==null?void 0:o.option)!=null&&s.videoTrack)){if(Zi())throw new V({code:$.ENV_NOT_SUPPORTED,extraCode:5201});if(!_n())throw new V({code:$.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:As,publish:{type:"boolean"},option:vf}},muteRemoteAudio:[Nf,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[Nf,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:As,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(o,i,e){Cs(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(o.userId);if(Mf(!!t,e,o),t&&(o.streamType==="main"&&!t.muteState.videoAvailable||o.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new V({code:$.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:o}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:L(O({},As),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(o,i,e){Cs(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(o.userId);if(Mf(!!t,e,o),t&&(o.streamType==="main"&&!t.muteState.videoAvailable||o.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new V({code:$.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:o}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(o,i,e){if(o.userId!=="*"&&T(o.streamType))throw new V({code:$.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(o,i,e){Cs(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(o,i,e,t){if(!En)throw new V({code:$.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new V({code:$.INVALID_OPERATION,fnName:e,extraCode:5108});if(o.byteLength>1e3)throw new V({code:$.INVALID_PARAMETER,extraCode:5018,fnName:e});if(o.byteLength===0)throw new V({code:$.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});Cs(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(o,i,e){if(!o&&!this._room.isMainStreamPublished||o&&!this._room.isAuxStreamPublished)throw new V({code:$.INVALID_OPERATION,extraCode:5109,messageParams:{key:i},fnName:e})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(o,i,e,t){if(o.byteLength>1e3)throw new V({code:$.INVALID_PARAMETER,extraCode:5018,fnName:e});if(o.byteLength===0)throw new V({code:$.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(o,i,e){if(Cs(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new V({code:$.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(o,i,e){if(Cs(this._room.isJoined,e),this._room.useStringRoomId&&o.strRoomId===this._room.roomId||!this._room.useStringRoomId&&o.roomId===Number(this._room.roomId))throw new V({code:$.INVALID_PARAMETER,extraCode:5020,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(o.roomId&&this._room.useStringRoomId||!o.roomId&&o.strRoomId&&!this._room.useStringRoomId)throw new V({code:$.INVALID_PARAMETER,extraCode:5019,fnName:e,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(o.roomId)Of(o.roomId,e,i);else if(o.strRoomId)kf(o.strRoomId,e,i);else throw new V({code:$.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{roomId:{type:"number"},strRoomId:{type:"string"},privateMapKey:{type:"string"},userSig:{type:"string",required:!0},autoSubscribeCount:{type:"number",min:0,max:50}}}},We={TRTC:LS};var ut=class extends Error{};function xS(o,i){let e=Gr(o);for(let t=0;t<i.length;t++)ei(e[t],i[t]);return e}function US(o){this._resolve=Promise.resolve(o)}function VS(o){this._reject=Promise.reject(o)}var Pr=class Pr{constructor(i,e){this.instance=i;this.group=e;d(this,"started",!1);d(this,"ops",[]);d(this,"startSame",()=>!0);d(this,"mergeUpdate",xS);let t=Pr.instances.get(i);t?t.set(e,this):Pr.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=Pr.instances.get(i);return t&&t.get(e)||new Pr(i,e)}static gets(i,e){let t=Pr.instances.get(i),r=[];return t&&t.forEach((s,n)=>{e.test(n)&&r.push(s)}),r}action(i,e,t){let r=a=>{var c;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),a},s=a=>{var c,l;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new ut("start failed")),(l=this.currentOp)==null||l.action(),a},n={type:i,action:()=>e(...n.args).then(r,s),args:t,resolve:US,reject:VS};try{switch(this.state){case 1:if(i===0)throw new ut("already started");break;case 4:if(i===2)throw new ut("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(r,s)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new ut("already start");break;case 3:switch(i.type){case 2:throw new ut("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new ut("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new ut("keep stop");if(this.ops.slice(1).forEach(r=>r.reject(t)),this.ops=this.ops.slice(0,1),this.state===3)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,i.args),this.lastOp.promise;case 3:throw new ut("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new ut("start not allowed after update");case 0:throw new ut("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new ut("keep start")),new ut("already start")}}i.promise=new Promise((t,r)=>{i._resolve?i._resolve.then(t):i.resolve=t,i._reject?i._reject.catch(r):i.reject=r});let{action:e}=i;return i.action=()=>e().then(i.resolve,i.reject),this.ops.push(i),i.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}};d(Pr,"instances",new WeakMap);var nr=Pr;var nd=new WeakMap,ad=(o,i)=>{if(i instanceof ut){let{stack:e}=i;i=new V({code:$.OPERATION_ABORT,message:`${o} abort: ${i.message}`,fnName:o}),e&&(i.stack+=e.substr(e.indexOf(`
|
|
55
55
|
`)))}throw i};function wr(o,i){return Q((e,t)=>function(...r){let s=nr.get(this,typeof o=="string"?o:o.call(this,...r));return s?(i&&(s.startSame=i.bind(this)),s.action(0,e.bind(this),r).catch(ad.bind(null,t))):e.apply(this,r)})}function Ao(o,i){let{merge:e,debounce:t}=i||{};return Q((r,s)=>function(...n){let a=nr.get(this,typeof o=="string"?o:o.call(this,...n));if(!a)return r.apply(this,n);if(e&&(a.mergeUpdate=e.bind(this)),t&&t.isNeedToDebounce.apply(this,n)){let{delay:c,getKey:l}=t;return new Promise((u,m)=>{var g,E;let h=(g=nd.get(this))==null?void 0:g.get(l(...n));if(h){let{timeoutId:A,resolve:k}=h;clearTimeout(A),k()}let _=setTimeout(()=>{if(a.state===3||a.state===4)return u();a.action(2,r.bind(this),n).catch(ad.bind(null,s)).then(u,m)},c);nd.has(this)?(E=nd.get(this))==null||E.set(l(...n),{timeoutId:_,resolve:u}):nd.set(this,new Map([[l(...n),{timeoutId:_,resolve:u}]]))})}return a.action(2,r.bind(this),n).catch(ad.bind(null,s))})}function Lr(o){return Q((i,e)=>function(...t){let r=typeof o=="function"?o.call(this,...t):o;if(r instanceof RegExp)return Promise.all(nr.gets(this,r).map(n=>n.action(3,()=>Promise.resolve(),t))).then(()=>i.call(this,...t));let s=nr.get(this,r);return s?s.action(3,i.bind(this),t).catch(ad.bind(null,e)):i.apply(this,t)})}function xr(){return function(o,i,e){return o.prototype[i]=function(){let t=this._log||console,r=`"${i}" is a static method. Use TRTC.${i}() instead. See: ${ft}/en/TRTC.html#.${i}`;t.warn(r)},e}}var x={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame",PERMISSION_STATE_CHANGE:"permission-state-change",VIDEO_SIZE_CHANGED:"video-size-changed"},wf=new Set([x.AUDIO_VOLUME,x.AUDIO_FRAME,x.NETWORK_QUALITY,x.STATISTICS,x.SEI_MESSAGE,x.CUSTOM_MESSAGE,x.LAYER_DATA]);var vh={};Vi(vh,{ScheduleRequestType:()=>Uf,getAbilityConfig:()=>HS,getScheduleDomain:()=>ld,isNeedToSchedule:()=>cd,scheduleProxy:()=>Pi,sendScheduleRequest:()=>bh,setIsNeedToSchedule:()=>Lt,setScheduleProxy:()=>dd});var yh=null,xf=0,FS=48*3600*1e3,cd=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values($i).map(o=>`<link rel="dns-prefetch" href="https://${o}">`).join(`\r
|
|
56
56
|
`));function Lt(o){he(o)&&o!==cd&&(cd=o,R.info(`setIsNeedToSchedule ${o}`),o||(xf=Date.now()+FS))}S.on("28",()=>Lt(!0));S.on("63",()=>Lt(!0));S.on("84",()=>Lt(!0));S.on("201",o=>{o.state==="RECONNECTING"&&Lt(!0)});S.on("202",o=>{o.state==="RECONNECTING"&&Lt(!0)});function BS(o,i,e){let t={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let r=performance.getEntriesByType("resource"),s=Ur(o,"config",f.MAIN),n=Ur(o,"config",f.BACKUP);for(let a of r)if(a.startTime>=e&&(a.name===s||a.name===n)&&a.transferSize>0){let c=a.name===s?f.MAIN:f.BACKUP,l=Math.round(a.duration),u=Math.round(a.domainLookupStart-a.startTime),m=a.redirectStart>0?Math.round(a.redirectEnd-a.redirectStart):0,h=a.fetchStart>0?Math.round(a.domainLookupStart-a.fetchStart):0,_=Math.round(a.domainLookupEnd-a.domainLookupStart),g=Math.round(a.requestStart-a.secureConnectionStart),E=Math.round(a.secureConnectionStart-a.connectStart),A=Math.round(a.responseStart-a.requestStart),k=Math.round(a.responseEnd-a.responseStart),re=[_,g,E,A,k];se.uploadEvent({log:`stat-schedule-net:${l}(${u}(${m}->${h})->${re.join("->")}) ${c}`,userId:i}),t=L(O({},t),{totalCost:l,local:u,dns:_,tcp:E,tls:g,request:A,response:k});break}}catch(r){R.error("getScheduleDetailCost error",r)}return t}function bh(l){return p(this,arguments,function*({userId:o,sdkAppId:i,useStringRoomId:e,roomId:t,userSig:r,version:s,frameWorkType:n,role:a,latencyLevel:c}){var m;if(!cd&&yh&&xf>Date.now())return{isCached:!0,result:yh};let u={delta:0,count:[1,1],msg:[],detail:[]};try{let h=new FormData;h.append("userId",String(o)),h.append("sdkAppId",String(i)),h.append("isStrGroupId",String(e)),h.append("groupId",String(t)),h.append("sdkVersion",s),h.append("userSig",String(r));let _=((m=yield Yr())==null?void 0:m.model)||ec();_&&h.append("model",_);let g=ni();g&&h.append("osString",g),a&&h.append("role",String(a)),c&&h.append("latencyLevel",String(c)),n&&h.append("frameWorkType",String(n));let E=U(),A=yield WS(h,u,i);A.config&&(A.config.loggerDomain&&Fr(A.config.loggerDomain),he(A.config.scheduleCache)&&Lt(!A.config.scheduleCache)),u.delta=U()-E;let k=BS(Number(i),o,E);return yh=A,{isCached:!1,result:A,detailCost:k}}catch(h){let _=Ie(h)?h[0]:h,g=z(_.code)?_.code:0,E=`schedule failed${_.message?`: ${_.message}`:""}`,A=new D({code:I.SCHEDULE_FAILED,extraCode:g,message:H({key:F.JOIN_ROOM_FAILED,data:{error:E,code:g}})});throw R.error(E,g),A}})}var Pi={main:"",backup:""};function dd(o){Ie(o)?(Pi.main=o[0],Pi.backup=o[1]):Pi.main=o}var Uf=(t=>(t.CONFIG="config",t.TRTC_AUTO_CONF="trtcAutoConf",t.AUDIO_AI_AUTH="audioAiAuth",t))(Uf||{});function Ur(o,i,e=f.MAIN,t=!1){return`https://${Pi[e]||ld(o,e,t)}/api/v1/${i}`}function HS(o,i,e){let t=Ur(o,i),r=Ur(o,i,f.BACKUP),s=new URLSearchParams(e).toString(),n=fetch(`${t}?${s}`).then(c=>c.json()),a=fetch(`${r}?${s}`).then(c=>c.json());return Xr([n,a])}function ld(o,i=f.MAIN,e=!1){let t;return Ut(o)?e?t=i===f.MAIN?$i.MAIN_OVERSEA_BACKUP:$i.BACKUP_OVERSEA:t=i===f.MAIN?$i.MAIN_OVERSEA:$i.BACKUP_OVERSEA:t=i===f.MAIN?$i.MAIN:$i.BACKUP,t}function $S(o,i,e){return new Promise((t,r)=>{qi({url:o,body:i,timeout:e.timeout,priority:"high"}).then(s=>{s.data.code===0?t(s.data.data):r({code:s.data.code,message:s.data.msg})}).catch(r)})}var Lf=(o,i)=>Ai({retryFunction:$S,settings:{retries:3,timeout:0},onError:i,onRetrying:o});function WS(o,i,e){return new Promise((t,r)=>{let s=null;Xr([Lf(n=>i.count[0]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:l})=>{i.msg[0]=n.message,s||(c>=1&&(l[0]=Ur(e,"config",f.MAIN,!0)),a())})(Ur(e,"config",f.MAIN),o,{get timeout(){return Jr(2+i.count[0])*1e3}}),Lf(n=>i.count[1]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:l})=>{i.msg[1]=n.message,s||(c>=2&&(l[0]=Ur(e,"config",f.BACKUP,!0)),a())})(Ur(e,"config",f.BACKUP),o,{get timeout(){return Jr(2+i.count[1])*1e3}})]).then(n=>{s=n,t(s)}).catch(r)})}var GS=o=>o.startsWith("data:application/octet-stream;base64,"),qS=o=>o.startsWith("file://"),Jn=class{constructor(){d(this,"_log");this._log=R.createLogger({id:"fd"})}download(i,e){return p(this,null,function*(){let{type:t="blob"}=e||{};i=Ma(i);try{let r=U(),s;if(le(fetch)?s=yield this.downloadWithFetch(i,t):s=yield this.downloadWithXHR(i,t),!s||!s.data)throw new Error("data is empty");let n=U()-r;return this._log.info(`downloaded: ${i}, return type: ${t}, cost: ${n}ms`),v.addSuccessEvent({key:522700,cost:U()-r}),s.data}catch(r){throw this._log.error(`failed to download: ${i}, error: ${r}`),v.addFailedEvent({key:522700,error:r}),r}})}downloadWithFetch(i,e){return p(this,null,function*(){this._log.info(`download with fetch: ${i}, return type: ${e}`);try{let t=yield fetch(i);if(!t.ok){let s=new Error(`network response was not ok: ${t.status}`);throw s.status=t.status,s}let r;return e==="arraybuffer"?r=yield t.arrayBuffer():r=yield t.blob(),{data:r}}catch(t){throw t}})}downloadWithXHR(i,e){return this._log.info(`download with xhr: ${i}, return type: ${e}`),new Promise((t,r)=>{let s=new XMLHttpRequest;s.open("GET",i,!0),s.responseType=e,s.onload=()=>{if(s.status===200||s.status===0&&s.response)t({data:s.response});else{let n=new Error(`XHR failed, status: ${s.status}`);n.status=s.status,r(n)}},s.onerror=r,s.send(null)})}loadWasm(i,e){return p(this,null,function*(){this._log.info(`loadWasm ${i}, importObject: ${JSON.stringify(e)}`);let t=U(),r=null,s=null;if(le(WebAssembly.instantiateStreaming)&&!GS(i)&&!qS(i)&&le(fetch))try{let n=fetch(i);r=(yield WebAssembly.instantiateStreaming(n,e)).instance}catch(n){s=n}if(!r)try{let n=yield this.download(i,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(n,e)).instance}catch(n){s=n}if(r){let n=U()-t;return this._log.info(`loadedWasm ${i}, cost: ${n}ms`),v.addSuccessEvent({key:522701,cost:n}),r}throw this._log.error(`failed to loadWasm ${i}, error: ${s}`),v.addFailedEvent({key:522701,error:s}),s})}loadScript(i){this._log.info(`loadScript ${i}`);let e=U();return new Promise((t,r)=>{let s=document.createElement("script");s.type="text/javascript",s.onload=()=>{this._log.info(`loadedScript ${i}, cost: ${U()-e}ms`),v.addSuccessEvent({key:522702,cost:U()-e,split:1e3}),t(s)},s.onerror=n=>{this._log.error(`failed to loadScript ${i}, error: ${(n==null?void 0:n.message)||JSON.stringify(n)}`),v.addFailedEvent({key:522702}),r(n)},s.crossOrigin="anonymous",s.src=i,document.head.append?document.head.append(s):document.getElementsByTagName("head")[0].appendChild(s)})}};M([Mt({settings:{timeout:0,retries:3},onError(i,e,t){var r;(i==null?void 0:i.status)===404||(r=i==null?void 0:i.message)!=null&&r.includes("404")?(this._log.warn("download 404, stop retry"),t(i)):e()},onRetrying(i){this._log.warn(`download retrying: ${i}`)}})],Jn.prototype,"download",1),M([Mt({settings:{timeout:3e3,retries:3},onRetrying(i){this._log.warn(`loadScript retrying: ${i}`)}})],Jn.prototype,"loadScript",1);var jn=new Jn;function Nh([o,i]){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,s=[];s.push(0,0,0,1,6,o);for(let a=0;a<t;a++)s.push(255);s.push(r);let n=new DataView(i);return s.push(...new Uint8Array(n.buffer)),s.push(128),new sr(new DataView(new Uint8Array(s).buffer),!0)}function Dh(o){return o.type==="empty"||o.data.byteLength===0}function Mh(o){let i=new DataView(o),e=0;for(;e<i.byteLength;){let t=0;if(e+4<=i.byteLength&&i.getUint8(e)===0&&i.getUint8(e+1)===0&&i.getUint8(e+2)===0&&i.getUint8(e+3)===1)t=4;else if(e+3<=i.byteLength&&i.getUint8(e)===0&&i.getUint8(e+1)===0&&i.getUint8(e+2)===1)t=3;else{e+=1;continue}let r=e+t;if(r<i.byteLength&&(i.getUint8(r)&31)===6)return!0;let s=-1;for(let n=e+t;n<i.byteLength;n+=1){if(n+4<=i.byteLength&&i.getUint8(n)===0&&i.getUint8(n+1)===0&&i.getUint8(n+2)===0&&i.getUint8(n+3)===1){s=n;break}if(n+3<=i.byteLength&&i.getUint8(n)===0&&i.getUint8(n+1)===0&&i.getUint8(n+2)===1){s=n;break}}e=s===-1?i.byteLength:s}return!1}function Oh(o){let i=0,e=0,t=new DataView(o);for(let r=0;r<o.byteLength;r++)switch(t.getUint8(r)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function kh({frame:o,seiMessageList:i}){if(!i||i.length===0||o.data.byteLength===0)return o;let t=9-Oh(o.data);if(t<=0)return o;let r=i.splice(0,t).reverse().map(Nh),s=r.reduce((u,m)=>u+m.dataView.byteLength,0),n=new ArrayBuffer(s+o.data.byteLength),a=new DataView(n),c=new DataView(o.data),l=0;for(let u=0;u<r.length;u++)for(let m=0;m<r[u].dataView.byteLength;m++)a.setInt8(l++,r[u].dataView.getInt8(m));for(let u=0;u<o.data.byteLength;u++)a.setInt8(l++,c.getInt8(u));return o.data=n,o}function Ph({frame:o,onSEI:i}){try{if(Dh(o)||!Mh(o.data))return o;let e=zc(o.data,!1).filter(t=>t.isSEI);i==null||i(e.reverse())}catch(e){}return o}function Vf({seiMessageList:o,isAudio:i,getNtpTime:e,isMain:t}){return new TransformStream({transform(r,s){let n=r;i?audioEncodePipeline.forEach(a=>{n=a({frame:n,ntp:e()})}):videoEncodePipeline.forEach(a=>{n=a({frame:n,seiMessageList:o,onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:n.data,userId:"",streamType:t?"main":"auxiliary"})}})}),s.enqueue(n)}})}function Ff({userId:o,streamType:i,isAudio:e}){return new TransformStream({transform(t,r){let s=t;e?(audioDecodePipeline.forEach(n=>{s=n({frame:s,onAudioFrameNTPTime:a=>{self.postMessage({type:"audio-ntp",data:a,userId:o,streamType:i})},onDump:()=>{self.postMessage({type:"dump",isAudio:e,data:s.data,userId:o,streamType:i})}})}),r.enqueue(s)):videoDecodePipeline.forEach(n=>{s=n({frame:s,onSEI:a=>{a.forEach(c=>{self.postMessage({type:"sei",seiPayloadType:c.seiPayloadType,data:c.seiPayload.buffer,userId:o,streamType:i})})}})}),r.enqueue(s)}})}function ud(o){let i=[sr],e=[Oh,Dh,zc,Mh,Nh,Vf,Ff,Pa,ka],t=()=>{let l=[],u=[],m=[],h=0;self.onmessage=_=>{switch(_.data.type){case"sei":_.data.isMain?(l.push(_.data.data),_.data.small&&m.push(_.data.data)):u.push(_.data.data);break;case"ntp-offset":h=_.data.data;break}},self.onrtctransform=_=>{let{options:g}=_.transformer,E=g.isReceiver?Ff({userId:g.userId,streamType:g.streamType,isAudio:g.isAudio}):Vf({getNtpTime:()=>Date.now()+h,isAudio:g.isAudio,isMain:g.isMain,seiMessageList:g.isMain?g.small?m:l:u});_.transformer.readable.pipeThrough(E).pipeTo(_.transformer.writable)}},r=`const videoEncodePipeline=[${o.videoEncodePipeline.toString()}];
|
|
57
57
|
const videoDecodePipeline=[${o.videoDecodePipeline.toString()}];
|
|
@@ -61,11 +61,11 @@ CPU core: ${navigator.hardwareConcurrency}, GPU: ${Pl()}`,e=navigator.deviceMemo
|
|
|
61
61
|
${e.map(l=>l.toString()).join(`
|
|
62
62
|
`)};(${t})();${r}})()`,n=new Blob([s],{type:"text/javascript"}),a=URL.createObjectURL(n),c=new Worker(a);return URL.revokeObjectURL(a),c}function Bf({TRTC:o,room:i,errorModule:e,assetsPath:t}){return{TRTC:o,LocalMixVideoTrack:go,LocalVideoTrack:je,LocalScreenTrack:Pt,room:i,assetsPath:t,fileDownloader:jn,innerEmitter:S,INNER_EVENT:C,constants:ol,environment:Ko,utils:Eh,eventLogger:se,log:this.room.getLogger(),loggerManager:R,errorModule:e,kvStatManager:v,rtcDectection:bi,trtc:this,rx:gh,enums:Yl,schedule:vh,getDevices:ds,initVisionTaskRegistry:(r,s="/mediapipe/vision.js")=>p(this,null,function*(){window.VisionTaskRegistry||(yield jn.loadScript(`${r}/${s}`.replace(/([^:]\/)\/+/g,"$1"))),yield(yield window.VisionTaskRegistry.getInstance(r)).preloadModels([window.VisionTaskType.ImageSegmenter])}),audioContext:Ee(),deviceDetector:be,AudioPlayer:us,RemoteAudioPlayer:hs,VideoPlayer:it,showAutoPlayDialog:ns,Timer:oe,clearStarted:(r,s)=>{let n=r.getAlias(),a=nr.instances.get(this);if(a)if(s){let c=a.get(n+s);if(!c)return;c.started=!1}else a.forEach((c,l)=>{l.startsWith(n)&&(c.started=!1)})},startGetPCM:Gn,createAudioNode:On,getNetworkTimeOffset:Em,validateSourceNode:()=>{var r;if(K&&!((r=this.room.audioManager._localAudioPipline)!=null&&r.source.node))throw new V({code:$.DEVICE_ERROR,extraCode:5310,message:"The audio processing plugin cannot be used due to the microphone's sampling rate is not 48KHz in Firefox. Please switch to another browser such as Chrome."})},createScriptTransformWorker:ud}}var Hf=(o,i)=>{let{emit:e}=o;return o.emit=(...t)=>{try{return e.apply(o,t)}catch(r){let s=H({key:F.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return R.warn(`${s}
|
|
63
63
|
|
|
64
|
-
${r.stack}`),!1}},o};var Rs=new WeakMap;function $f(o){let i=Rs.get(o);i&&(i.forEach(e=>clearTimeout(e)),Rs.delete(o))}function Wf(o,i){return Q((e,t)=>function(...r){let s=Rs.get(this);s||(s=new Map,Rs.set(this,s));let n=i(...r),a=s.get(n);if(!a||a<=0){e.apply(this,r);let c=setTimeout(()=>{var l;(l=Rs.get(this))==null||l.delete(n)},o);s.set(n,c)}else{clearTimeout(a);let c=window.setTimeout(()=>{var l;e.apply(this,r),(l=Rs.get(this))==null||l.delete(n)},o);s.set(n,c)}})}var qf="trtc-sdk-v5",wh="5.15.0-beta.4";function st(...o){return Q((i,e)=>function(...t){try{md.call(this,o,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function Lh(...o){return Q((i,e)=>function(...t){try{md.call(this,o,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function md(o,i,e,t){if(Ie(o))for(let r=0;r<o.length;r++)hd.call(this,{rule:o[r],value:i[r],key:o[r].name,fnName:e,className:t});else hd.call(this,{rule:o,value:i[0],key:o.name,fnName:e,className:t})}function hd({rule:o,value:i,key:e,fnName:t,className:r}){function s(c){return{code:$.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:o,value:i}}}if(T(i)){if(o.required)throw new V(s(5001));if(T(o.defaultValue)){le(o.validate)&&o.validate.call(this,i,e,t,r,this);return}i=o.defaultValue}if(Array.isArray(o.type)){let c=!1;for(let l=0;l<o.type.length;l++)o.type[l]===null&&i===null&&(c=!0),le(o.type[l])&&i instanceof o.type[l]&&(c=!0),ie(o.type[l])&&Me(i)===o.type[l].toLowerCase()&&(c=!0);if(!c)throw new V({code:$.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:o.type.map(l=>jr(l)?xo(l):ie(l)?l:Me(l))},value:i}})}else if(!T(o.type)&&Me(i)!==o.type)throw new V(s(5002));if(o.allowEmpty===!1){let c=z(i)&&(i===0||Number.isNaN(i)),l=ie(i)&&i.trim()==="";if(c||l)throw new V(s(5003))}if(o.notLessThanZero&&z(i)&&i<0)throw new V(s(5006));if(!T(o.min)&&z(i)&&i<o.min)throw new V(s(5007));if(!T(o.max)&&z(i)&&i>o.max)throw new V(s(5008));if(ie(o.instanceOf)){if(!i||i._name!==o.instanceOf)throw new V(s(5004))}else if(le(o.instanceOf)&&!(i instanceof o.instanceOf))throw new V(s(5004));if(Array.isArray(o.values)&&!o.values.includes(i))throw new V(s(5005));let{properties:n}=o;dt(n)&&yt(i)&&Object.keys(n).forEach(c=>{hd.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:r})});let{arrayItem:a}=o;dt(a)&&Ie(i)&&i.forEach((c,l)=>{hd.call(this,{rule:a,value:c,key:`${e}[${l}]`,fnName:t,className:r})}),le(o.validate)&&o.validate.call(this,i,e,t,r,this)}function Ae(o={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r,ignoreErrorLog:s}=o;return Q((n,a)=>function(...c){var _,g,E;function l(A,k,re){if(re&&re.includes(A))return"hided";if(e){let P=e(...c);if(c[P.argIndex]===k)return P.value}if(k===c||A in c)return k;try{return k instanceof HTMLElement?`id: ${k.id} type:${Me(k)}`:k instanceof MediaStreamTrack?Oa(k):(JSON.stringify(k),k)}catch(P){return`type:${Me(k)}`}}let u=this._log||R;if(r!=null&&r(...c))return n.apply(this,c);c.length>0?u.info(`${a}() ${JSON.stringify(c,(A,k)=>l(A,k,["userSig","privateMapKey"]))}`):u.info(`${a}()`);let m=t?t(...c):uc[a],h=(s==null?void 0:s(...c))||!1;try{let A=n.apply(this,c),k=U();if(Tr(A)){let re=`${a.includes("Plugin")?`${((g=(_=c[0]).getName)==null?void 0:g.call(_))||""} `:" "}`;return A.then(P=>(u.info(`${a}() success ${re}${i.call(this,...c)}`),v.addSuccessEvent({key:m,cost:U()-k}),P)).catch(P=>{var b;P=V.convertFrom.call(this,P,a,c.length===1?c[0]:c);let Qe=P.extraCode||P.code,N=(b=P.message)!=null&&b.includes(Qe)?"":` code:${Qe}`;throw h||u.error(`${a}() failed ${re}${i.call(this,...c)} ${P}${N} params: ${JSON.stringify(c,l)}`),v.addFailedEvent({key:m,error:P}),P})}return v.addSuccessEvent({key:m}),A}catch(A){A=V.convertFrom.call(this,A,a);let k=A.extraCode||A.code,re=(E=A.message)!=null&&E.includes(k)?"":` code:${k}`;throw h||u.error(`${a}() failed ${A}${re} params: ${JSON.stringify(c,l)}`),v.addFailedEvent({key:m,error:A}),A}})}var pd=o=>Q((i,e)=>function(t,r){return p(this,null,function*(){let s=this._plugins.get(t);if(!s)throw this._log.error(`plugin ${String(t)} is not found`),new V({code:$.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(le(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new V({code:$.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return md.call(this,s.getValidateRule(o),[r],e,"TRTC"),i.call(this,s,r)})});var fd=0,xh,ar=class ar{constructor(i){this.core=i;d(this,"log");d(this,"customAudioReferenceMap",new Map);d(this,"audioRefId",0);d(this,"audioContext",Ee());d(this,"localAudioWorkletNode");d(this,"screenAudioWorkletNode");d(this,"mixNode");d(this,"silentNode");fd=fd+1,this.log=i.log.createChild({id:`${this.getAlias()}${fd}`}),this.log.info(`created id=${this.getAlias()}${fd}`),this.installEvent()}static getStartValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,s){if(!i.room.audioManager.hasAudioTrack&&!i.room.audioManager.hasScreenAudioTrack)throw new V({code:$.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return xh||(xh=this.doPreload(i)),xh}doPreload(i){return p(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield tr(this.audioContext,t)}catch(r){this.log.error(`preload audioProcessor failed. ${r}`)}finally{URL.revokeObjectURL(t)}})}getName(){return ar.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(i){switch(i){case"start":return ar.getStartValidateRule(this.core);case"update":return ar.updateValidateRule;case"stop":return ar.stopValidateRule}}start(i){return p(this,null,function*(){var h,_,g,E;let{room:e}=this.core,{sdkAppId:t,userId:r,userSig:s,assetsPath:n=this.core.assetsPath,audioReference:a,processLevel:c,enableDump:l,isLocalAudioNeedAudioProcess:u=!0,isScreenAudioNeedAudioProcess:m=!1}=i;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=u,this.core.room.audioManager.isScreenAudioNeedAudioProcess=m,!n)throw new V({code:$.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${n}/audioProcessor-wasm.js`),u&&!this.localAudioWorkletNode){let{sign:A,status:k,timestamp:re}=yield this.getAuthData(t,r,s);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",t,r,re,A,k,e)}if(m&&!this.screenAudioWorkletNode){let{sign:A,status:k,timestamp:re}=yield this.getAuthData(t,r,s);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",t,r,re,A,k,e)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),(h=this.localAudioWorkletNode)==null||h.port.postMessage({type:"enable"}),(_=this.screenAudioWorkletNode)==null||_.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),T(a)||a.forEach(A=>{this.customAudioReferenceMap.set(A,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:A,refId:`o-${this.audioRefId++}`})}),T(c)||(g=this.localAudioWorkletNode)==null||g.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:c}}),T(l)||(E=this.localAudioWorkletNode)==null||E.port.postMessage({type:"dump",data:{enable:l}})})}update(i){return p(this,null,function*(){var s,n,a;let{audioReference:e,enableDump:t,processLevel:r}=i;T(e)||(this.customAudioReferenceMap.forEach((c,l)=>{this.customAudioReferenceMap.delete(l),this.core.room.audioManager.updateAudioReference({type:"remove",refId:c})}),e.forEach(c=>{this.customAudioReferenceMap.set(c,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:c,refId:`o-${this.audioRefId++}`})})),T(r)||(s=this.localAudioWorkletNode)==null||s.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:r}}),T(t)||((n=this.localAudioWorkletNode)==null||n.port.postMessage({type:"dump",data:{enable:t}}),(a=this.screenAudioWorkletNode)==null||a.port.postMessage({type:"dump",data:{enable:t}}))})}stop(){return p(this,null,function*(){var e,t;let{room:i}=this.core;(e=this.localAudioWorkletNode)==null||e.port.postMessage({type:"disable"}),(t=this.screenAudioWorkletNode)==null||t.port.postMessage({type:"disable"}),yield i.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null),this.uninstallEvent()}getAuthData(i,e,t){return p(this,null,function*(){let r=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:a,message:c}=yield jS({sdkAppId:i,userSig:t,userId:e,timestamp:r});if(!s)throw this.log.info(`audioProcessor: ${e} auth result: ${s}. Message: ${c}`),new V({code:$.INVALID_PARAMETER,message:c});return{sign:n,status:a,timestamp:r}})}initWorkletNode(i,e,t,r,s,n,a,c){i.port.postMessage({type:"init",data:{sdkAppId:String(t),userId:r,timestamp:s,sign:n,status:a}}),i.port.onmessage=l=>{var m;let{data:u}=l;switch(u.type){case"cost":let h=(u==null?void 0:u.value)>10?"info":"debug";this.log[h](`${e==="localAudio"?"":`[${e}] `}avg cost: ${u.value} max: ${u==null?void 0:u.max}(${No(new Date(u==null?void 0:u.maxCostTimestamp))}) hist: ${(m=u==null?void 0:u.hist)==null?void 0:m.join(" ")}`);return;case"log":this.log[u.logLevel](`${e==="localAudio"?"":`[${e}] `}${u.value}`);return;case"dump":S.emit("265",{room:c,data:u.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return}}}handleLocalAudioStarted(i){return p(this,null,function*(){var e;if(!(!this.hitTest(i.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0))try{yield this.core.trtc.startPlugin("AudioProcessor",{sdkAppId:this.core.room.sdkAppId,userId:this.core.room.userId,userSig:this.core.room.userSig}),this.log.warn("audio processor auto start success")}catch(t){this.log.warn(`audio processor auto start failed, error: ${t}`)}})}handleLocalAudioStopped(i){return p(this,null,function*(){var e;!this.hitTest(i.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0||(yield this.core.trtc.stopPlugin("AudioProcessor"))})}installEvent(){this.core.innerEmitter.on("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.on("114",this.handleLocalAudioStopped,this)}uninstallEvent(){this.core.innerEmitter.off("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.off("114",this.handleLocalAudioStopped,this)}hitTest(i){return i===this.core.room}};d(ar,"updateValidateRule",{type:"object"}),d(ar,"stopValidateRule",{type:"object"}),d(ar,"Name","AudioProcessor");var _d=ar;function JS(o,i=f.MAIN){return`https://${Pi[i]||ld(o,i)}/api/v1/audioAiAuth`}function jS(r){return p(this,arguments,function*({sdkAppId:o,userId:i,userSig:e,timestamp:t}){let n=`${JS(o)}?sdkAppId=${o}&userId=${i}&userSig=${e}×tamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:l,sign:u,status:m}}=yield a.json();if(m==="1")return{auth:!0,sign:u,status:m,message:l};let h=Ut(o)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",_="Init RTCAudioProcessor failed.",g="";switch(c){case 1:g="Please check your params.";break;case 2:g=`You need to buy packages. Refer to: ${h}`;break;case 3:g="Server is invalid. Please contact our engineer. ";break;case 4:g=`Your packages is not active. Refer to: ${h}`;break;case 5:g=`Your packages is expired. Refer to: ${h}`;break;case 6:g="Your version is not supported.";break}return{auth:!1,status:m,message:l?`${_} Reason: ${l}. ${g}`:`${_}, ${g}`}})}var gd=0,Uh=class{constructor(i,e){d(this,"audioObjectURL");d(this,"player");d(this,"publisher");d(this,"mixInput");this.mixInput=new cs(e),i.url?(this.player=new Audio(i.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(i.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(i.track),this.mixInput.connect()}updateSettings(i){this.player&&(T(i.volume)||(this.volume=i.volume),T(i.loop)||(this.loop=i.loop),T(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}reload(i){return p(this,null,function*(){if(i.url){let e=yield jn.download(i.url,{retries:3,type:"blob"});this.audioObjectURL&&URL.revokeObjectURL(this.audioObjectURL),this.audioObjectURL=URL.createObjectURL(e),this.player&&this.publisher?(this.player.src=this.audioObjectURL,this.publisher.src=this.audioObjectURL):(this.player=new Audio(this.audioObjectURL),this.player.crossOrigin="anonymous",this.publisher=new Audio(this.audioObjectURL),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher),this.updateListener(i),this.updateSettings(i))}else this.mixInput.replaceSource(i.track)})}reset(){this.seek(0),this.mixInput.connect()}seek(i){this.player&&(i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i))}play(){var i,e;return Promise.all([(i=this.player)==null?void 0:i.play(),(e=this.publisher)==null?void 0:e.play()])}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function ys(o,i){if(i&&typeof i!="function")throw new V({code:$.INVALID_PARAMETER,message:`start audioMixer plugin: param ${o} should be a function.`})}var wi=class wi{constructor(i){this.core=i;d(this,"log");d(this,"mixedMusicMap",new Map);d(this,"cacheMusicMap",new Map);gd=gd+1,this.log=i.log.createChild({id:`${this.getAlias()}${gd}`}),this.log.info(`created id=${this.getAlias()}${gd}`)}getName(){return wi.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return wi.startValidateRule;case"update":return wi.updateValidateRule;case"stop":return wi.stopValidateRule}}start(i){return p(this,null,function*(){let{room:e}=this.core;this.core.validateSourceNode(),this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:r}=i;if(this.mixedMusicMap.has(t))return;let s=this.cacheMusicMap.get(t);s?i.url?s.reset():(s.mixInput.replaceSource(i.track),s.mixInput.connect()):(s=new Uh(i,e.audioManager),this.cacheMusicMap.set(t,s)),s.updateListener(i),s.updateSettings(i);try{yield s.play()}catch(n){yield this.handleAutoPlayFailed(s,i,n)}this.mixedMusicMap.set(t,s),s.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:s.mixInput.source.node,refId:`ax-${t}`}),this.log.info(`start mix audio track ${t} success.`),v.addEnum({key:502700,value:3}),this.kvUpload(i)})}handleAutoPlayFailed(i,e,t){return p(this,null,function*(){if(t.name==="NotSupportedError")this.log.error(`play failed, try to reload source. error: ${t}`),yield i.reload(e),yield i.play();else if(t.name==="NotAllowedError")if(this.core.room.enableAutoPlayDialog){let r=()=>{var s;(s=i.play())==null||s.finally(()=>{S.off("154",r,this)})};S.on("154",r,this),ns()}else this.core.trtc.emit(x.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>p(this,null,function*(){return i.play()})});else throw t})}update(i){return p(this,null,function*(){let{id:e,operation:t,seekFrom:r,playbackRate:s}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),T(t)||n.setOperation(t),T(r)||n.seek(r),this.kvUpload(i)})}stop(e){return p(this,arguments,function*({id:i}){if(this.mixedMusicMap.has(i)){this.log.info(`remove music source, music id: ${i}`);let t=this.mixedMusicMap.get(i);t!=null&&t.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:t.mixInput.source.node,refId:`ax-${i}`}),t==null||t.stop(),this.mixedMusicMap.delete(i)}i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:r,playbackRate:s,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:l,onEnded:u}=i;e&&v.addCount({key:502009}),t&&v.addCount({key:502001}),r&&v.addCount({key:502002}),s&&v.addCount({key:502003}),n&&v.addCount({key:502004}),a&&v.addCount({key:502005}),typeof c!="function"&&v.addCount({key:502007}),typeof u!="function"&&v.addCount({key:502008}),typeof l!="function"&&v.addCount({key:502006})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>{i!=null&&i.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:i.mixInput.track,refId:e}),this.stop({id:e})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};d(wi,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let r=i.url.split("?")[0],s=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=s.indexOf(n)>=0,c=r.startsWith("blob"),l=r.startsWith("data");if(!(a||c||l))throw new V({code:$.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new V({code:$.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});ys("onTimeUpdate",i.onTimeUpdate),ys("onEnded",i.onEnded),ys("onDurationChange",i.onDurationChange)}}),d(wi,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(i,e,t){ys("onTimeUpdate",i.onTimeUpdate),ys("onEnded",i.onEnded),ys("onDurationChange",i.onDurationChange)}}),d(wi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),d(wi,"Name","AudioMixer");var Td=wi;var Ed=0,Vh,cr=class cr{constructor(i){this.core=i;d(this,"log");d(this,"audioContext",Ee("denoiser"));d(this,"workletNode");d(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5});Ed=Ed+1,this.log=i.log.createChild({id:`${this.getAlias()}${Ed}`}),this.log.info(`created id=${this.getAlias()}${Ed}`)}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0},mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}},validate(e,t,r,s){if(!i.room.audioManager.hasAudioTrack)throw new V({code:$.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return Vh||(Vh=this.doPreload(i)),Vh}doPreload(i){return p(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield tr(this.audioContext,t)}catch(r){throw this.log.error("load worklet failed",r),r}finally{URL.revokeObjectURL(t)}})}getName(){return cr.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(i){switch(i){case"start":return cr.startValidateRule(this.core);case"update":return cr.updateValidateRule;case"stop":return cr.stopValidateRule}}start(i){return p(this,null,function*(){let{room:e,schedule:t}=this.core,{assetsPath:r=this.core.assetsPath}=i;if(!r)throw new V({code:$.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${r}/denoiser-wasm${uu()?"":"-nosimd"}.js`),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:c,message:l}=yield zS(t,L(O({},i),{timestamp:s}));if(!n)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${n}. Message: ${l}`),new V({code:$.INVALID_PARAMETER,message:l});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:s,sign:a,status:c}}),this.workletNode.port.onmessage=u=>{var h;let{data:m}=u;if(m.type==="cost"){let _=(m==null?void 0:m.max)>20?"warn":(m==null?void 0:m.max)>10?"info":"debug";this.log[_](`avg cost: ${m.value} max: ${m==null?void 0:m.max}(${No(new Date(m==null?void 0:m.maxCostTimestamp))}) hist: ${(h=m==null?void 0:m.hist)==null?void 0:h.join(" ")}`)}else m.type==="log"&&this.log[m.logLevel](`${m.value}`)}}this.updateConfig(i),this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(i){return p(this,null,function*(){this.updateConfig(i)})}stop(){return p(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}updateConfig(i){if(!this.workletNode)return;let e=!1;T(i.mode)||(i.mode===0?this.config.enableFarFieldReduce=!1:i.mode===1&&(this.config.enableFarFieldReduce=!0),e=!0),T(i.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=i.farFieldReduceThreshold,e=!0),e&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};d(cr,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),d(cr,"stopValidateRule",{type:"object"}),d(cr,"Name","AIDenoiser");var Sd=cr;function zS(s,n){return p(this,arguments,function*(o,{sdkAppId:i,userId:e,userSig:t,timestamp:r}){try{let{data:{errCode:a,errMsg:c,sign:l,status:u}}=yield o.getAbilityConfig(i,o.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:e,userSig:t,timestamp:r});if(u==="1")return{auth:!0,sign:l,status:u,message:c};let m=Ut(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",h="Init RTCAIDenoiser failed.",_="";switch(a){case 1:_="Please check your params.";break;case 2:_=`You need to buy packages. Refer to: ${m}`;break;case 3:_="Server is invalid. Please contact our engineer. ";break;case 4:_=`Your packages is not active. Refer to: ${m}`;break;case 5:_=`Your packages is expired. Refer to: ${m}`;break;case 6:_="Your version is not supported.";break}return{auth:!1,status:u,message:c?`${h} Reason: ${c}. ${_}`:`${h}, ${_}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var jf=Ge(at(),1);var Fh=class extends jf.EventEmitter{constructor(){super();d(this,"observer");d(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return p(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!_e&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){se.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,r=e[e.length-1];this.state=r.state,(this.stateNum>3||t>3)&&R.info(`${r.source}: ${r.state}`),this.emit("state-changed",{type:r.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){se.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},QS=new Fh,Bh=QS;var Hh=0,Xn=class Xn{constructor(i){this.core=i;d(this,"log");d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_subStreamSeiMessageList",[]);Hh++,this.log=i.log.createChild({id:`${this.getAlias()}${Hh}`}),this.log.info(`[sei] created id=${this.getAlias()}${Hh}`),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode({frame:i,mediaType:e}){try{let t=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList;return kh({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return Ph({frame:i,onSEI:t=>{t.forEach(r=>{e!=null&&e.userId?this.core.trtc.emit(x.SEI_MESSAGE,{seiPayloadType:r.seiPayloadType,data:r.seiPayload.buffer,userId:(e==null?void 0:e.userId)||"",streamType:(e==null?void 0:e.mediaType)===2?"sub":"main"}):this.core.innerEmitter.emit(this.core.INNER_EVENT.SEI_MESSAGE,{room:this.core.room,nalu:r})})}})}destroy(){this.log.debug("destroy"),this.stop(),delete this.core}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:hi?this.encode:kh,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:hi?this.decode:Ph,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:i,options:e}){var s;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(s=this.core.room.scriptTransformWorker)==null||s.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return Xn.Name}getAlias(){return"sei"}getGroup(){return"sei"}};d(Xn,"autoStart",!0),d(Xn,"Name","SEI");var Id=Xn;function $h({frame:o,onDump:i}){return i==null||i(),o}function Wh({frame:o,onDump:i}){return i==null||i(),o}var Xf={"play() error: NotAllowedError:":{tips:o=>o.includes("main <video>")||o.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:o=>o.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:o=>o.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:`The remote stream audio playback is paused, which usually has two possibilities:
|
|
64
|
+
${r.stack}`),!1}},o};var Rs=new WeakMap;function $f(o){let i=Rs.get(o);i&&(i.forEach(e=>clearTimeout(e)),Rs.delete(o))}function Wf(o,i){return Q((e,t)=>function(...r){let s=Rs.get(this);s||(s=new Map,Rs.set(this,s));let n=i(...r),a=s.get(n);if(!a||a<=0){e.apply(this,r);let c=setTimeout(()=>{var l;(l=Rs.get(this))==null||l.delete(n)},o);s.set(n,c)}else{clearTimeout(a);let c=window.setTimeout(()=>{var l;e.apply(this,r),(l=Rs.get(this))==null||l.delete(n)},o);s.set(n,c)}})}var qf="trtc-sdk-v5",wh="5.15.0-beta.6";function st(...o){return Q((i,e)=>function(...t){try{md.call(this,o,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function Lh(...o){return Q((i,e)=>function(...t){try{md.call(this,o,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function md(o,i,e,t){if(Ie(o))for(let r=0;r<o.length;r++)hd.call(this,{rule:o[r],value:i[r],key:o[r].name,fnName:e,className:t});else hd.call(this,{rule:o,value:i[0],key:o.name,fnName:e,className:t})}function hd({rule:o,value:i,key:e,fnName:t,className:r}){function s(c){return{code:$.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:o,value:i}}}if(T(i)){if(o.required)throw new V(s(5001));if(T(o.defaultValue)){le(o.validate)&&o.validate.call(this,i,e,t,r,this);return}i=o.defaultValue}if(Array.isArray(o.type)){let c=!1;for(let l=0;l<o.type.length;l++)o.type[l]===null&&i===null&&(c=!0),le(o.type[l])&&i instanceof o.type[l]&&(c=!0),ie(o.type[l])&&Me(i)===o.type[l].toLowerCase()&&(c=!0);if(!c)throw new V({code:$.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:o.type.map(l=>jr(l)?xo(l):ie(l)?l:Me(l))},value:i}})}else if(!T(o.type)&&Me(i)!==o.type)throw new V(s(5002));if(o.allowEmpty===!1){let c=z(i)&&(i===0||Number.isNaN(i)),l=ie(i)&&i.trim()==="";if(c||l)throw new V(s(5003))}if(o.notLessThanZero&&z(i)&&i<0)throw new V(s(5006));if(!T(o.min)&&z(i)&&i<o.min)throw new V(s(5007));if(!T(o.max)&&z(i)&&i>o.max)throw new V(s(5008));if(ie(o.instanceOf)){if(!i||i._name!==o.instanceOf)throw new V(s(5004))}else if(le(o.instanceOf)&&!(i instanceof o.instanceOf))throw new V(s(5004));if(Array.isArray(o.values)&&!o.values.includes(i))throw new V(s(5005));let{properties:n}=o;dt(n)&&yt(i)&&Object.keys(n).forEach(c=>{hd.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:r})});let{arrayItem:a}=o;dt(a)&&Ie(i)&&i.forEach((c,l)=>{hd.call(this,{rule:a,value:c,key:`${e}[${l}]`,fnName:t,className:r})}),le(o.validate)&&o.validate.call(this,i,e,t,r,this)}function Ae(o={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r,ignoreErrorLog:s}=o;return Q((n,a)=>function(...c){var _,g,E;function l(A,k,re){if(re&&re.includes(A))return"hided";if(e){let P=e(...c);if(c[P.argIndex]===k)return P.value}if(k===c||A in c)return k;try{return k instanceof HTMLElement?`id: ${k.id} type:${Me(k)}`:k instanceof MediaStreamTrack?Oa(k):(JSON.stringify(k),k)}catch(P){return`type:${Me(k)}`}}let u=this._log||R;if(r!=null&&r(...c))return n.apply(this,c);c.length>0?u.info(`${a}() ${JSON.stringify(c,(A,k)=>l(A,k,["userSig","privateMapKey"]))}`):u.info(`${a}()`);let m=t?t(...c):uc[a],h=(s==null?void 0:s(...c))||!1;try{let A=n.apply(this,c),k=U();if(Tr(A)){let re=`${a.includes("Plugin")?`${((g=(_=c[0]).getName)==null?void 0:g.call(_))||""} `:" "}`;return A.then(P=>(u.info(`${a}() success ${re}${i.call(this,...c)}`),v.addSuccessEvent({key:m,cost:U()-k}),P)).catch(P=>{var b;P=V.convertFrom.call(this,P,a,c.length===1?c[0]:c);let Qe=P.extraCode||P.code,N=(b=P.message)!=null&&b.includes(Qe)?"":` code:${Qe}`;throw h||u.error(`${a}() failed ${re}${i.call(this,...c)} ${P}${N} params: ${JSON.stringify(c,l)}`),v.addFailedEvent({key:m,error:P}),P})}return v.addSuccessEvent({key:m}),A}catch(A){A=V.convertFrom.call(this,A,a);let k=A.extraCode||A.code,re=(E=A.message)!=null&&E.includes(k)?"":` code:${k}`;throw h||u.error(`${a}() failed ${A}${re} params: ${JSON.stringify(c,l)}`),v.addFailedEvent({key:m,error:A}),A}})}var pd=o=>Q((i,e)=>function(t,r){return p(this,null,function*(){let s=this._plugins.get(t);if(!s)throw this._log.error(`plugin ${String(t)} is not found`),new V({code:$.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(le(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new V({code:$.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return md.call(this,s.getValidateRule(o),[r],e,"TRTC"),i.call(this,s,r)})});var fd=0,xh,ar=class ar{constructor(i){this.core=i;d(this,"log");d(this,"customAudioReferenceMap",new Map);d(this,"audioRefId",0);d(this,"audioContext",Ee());d(this,"localAudioWorkletNode");d(this,"screenAudioWorkletNode");d(this,"mixNode");d(this,"silentNode");fd=fd+1,this.log=i.log.createChild({id:`${this.getAlias()}${fd}`}),this.log.info(`created id=${this.getAlias()}${fd}`),this.installEvent()}static getStartValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,r,s){if(!i.room.audioManager.hasAudioTrack&&!i.room.audioManager.hasScreenAudioTrack)throw new V({code:$.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return xh||(xh=this.doPreload(i)),xh}doPreload(i){return p(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield tr(this.audioContext,t)}catch(r){this.log.error(`preload audioProcessor failed. ${r}`)}finally{URL.revokeObjectURL(t)}})}getName(){return ar.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(i){switch(i){case"start":return ar.getStartValidateRule(this.core);case"update":return ar.updateValidateRule;case"stop":return ar.stopValidateRule}}start(i){return p(this,null,function*(){var h,_,g,E;let{room:e}=this.core,{sdkAppId:t,userId:r,userSig:s,assetsPath:n=this.core.assetsPath,audioReference:a,processLevel:c,enableDump:l,isLocalAudioNeedAudioProcess:u=!0,isScreenAudioNeedAudioProcess:m=!1}=i;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=u,this.core.room.audioManager.isScreenAudioNeedAudioProcess=m,!n)throw new V({code:$.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${n}/audioProcessor-wasm.js`),u&&!this.localAudioWorkletNode){let{sign:A,status:k,timestamp:re}=yield this.getAuthData(t,r,s);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",t,r,re,A,k,e)}if(m&&!this.screenAudioWorkletNode){let{sign:A,status:k,timestamp:re}=yield this.getAuthData(t,r,s);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",t,r,re,A,k,e)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),(h=this.localAudioWorkletNode)==null||h.port.postMessage({type:"enable"}),(_=this.screenAudioWorkletNode)==null||_.port.postMessage({type:"enable"}),e.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),T(a)||a.forEach(A=>{this.customAudioReferenceMap.set(A,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:A,refId:`o-${this.audioRefId++}`})}),T(c)||(g=this.localAudioWorkletNode)==null||g.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:c}}),T(l)||(E=this.localAudioWorkletNode)==null||E.port.postMessage({type:"dump",data:{enable:l}})})}update(i){return p(this,null,function*(){var s,n,a;let{audioReference:e,enableDump:t,processLevel:r}=i;T(e)||(this.customAudioReferenceMap.forEach((c,l)=>{this.customAudioReferenceMap.delete(l),this.core.room.audioManager.updateAudioReference({type:"remove",refId:c})}),e.forEach(c=>{this.customAudioReferenceMap.set(c,`o-${this.audioRefId++}`),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:c,refId:`o-${this.audioRefId++}`})})),T(r)||(s=this.localAudioWorkletNode)==null||s.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:r}}),T(t)||((n=this.localAudioWorkletNode)==null||n.port.postMessage({type:"dump",data:{enable:t}}),(a=this.screenAudioWorkletNode)==null||a.port.postMessage({type:"dump",data:{enable:t}}))})}stop(){return p(this,null,function*(){var e,t;let{room:i}=this.core;(e=this.localAudioWorkletNode)==null||e.port.postMessage({type:"disable"}),(t=this.screenAudioWorkletNode)==null||t.port.postMessage({type:"disable"}),yield i.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null),this.uninstallEvent()}getAuthData(i,e,t){return p(this,null,function*(){let r=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:a,message:c}=yield jS({sdkAppId:i,userSig:t,userId:e,timestamp:r});if(!s)throw this.log.info(`audioProcessor: ${e} auth result: ${s}. Message: ${c}`),new V({code:$.INVALID_PARAMETER,message:c});return{sign:n,status:a,timestamp:r}})}initWorkletNode(i,e,t,r,s,n,a,c){i.port.postMessage({type:"init",data:{sdkAppId:String(t),userId:r,timestamp:s,sign:n,status:a}}),i.port.onmessage=l=>{var m;let{data:u}=l;switch(u.type){case"cost":let h=(u==null?void 0:u.value)>10?"info":"debug";this.log[h](`${e==="localAudio"?"":`[${e}] `}avg cost: ${u.value} max: ${u==null?void 0:u.max}(${No(new Date(u==null?void 0:u.maxCostTimestamp))}) hist: ${(m=u==null?void 0:u.hist)==null?void 0:m.join(" ")}`);return;case"log":this.log[u.logLevel](`${e==="localAudio"?"":`[${e}] `}${u.value}`);return;case"dump":S.emit("265",{room:c,data:u.value,type:e==="localAudio"?"dump":"dump-screen-audio"});return}}}handleLocalAudioStarted(i){return p(this,null,function*(){var e;if(!(!this.hitTest(i.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0))try{yield this.core.trtc.startPlugin("AudioProcessor",{sdkAppId:this.core.room.sdkAppId,userId:this.core.room.userId,userSig:this.core.room.userSig}),this.log.warn("audio processor auto start success")}catch(t){this.log.warn(`audio processor auto start failed, error: ${t}`)}})}handleLocalAudioStopped(i){return p(this,null,function*(){var e;!this.hitTest(i.room)||((e=this.core.room.scheduleResult.config)==null?void 0:e.audioProcessor)!==!0||(yield this.core.trtc.stopPlugin("AudioProcessor"))})}installEvent(){this.core.innerEmitter.on("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.on("114",this.handleLocalAudioStopped,this)}uninstallEvent(){this.core.innerEmitter.off("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.off("114",this.handleLocalAudioStopped,this)}hitTest(i){return i===this.core.room}};d(ar,"updateValidateRule",{type:"object"}),d(ar,"stopValidateRule",{type:"object"}),d(ar,"Name","AudioProcessor");var _d=ar;function JS(o,i=f.MAIN){return`https://${Pi[i]||ld(o,i)}/api/v1/audioAiAuth`}function jS(r){return p(this,arguments,function*({sdkAppId:o,userId:i,userSig:e,timestamp:t}){let n=`${JS(o)}?sdkAppId=${o}&userId=${i}&userSig=${e}×tamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:l,sign:u,status:m}}=yield a.json();if(m==="1")return{auth:!0,sign:u,status:m,message:l};let h=Ut(o)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",_="Init RTCAudioProcessor failed.",g="";switch(c){case 1:g="Please check your params.";break;case 2:g=`You need to buy packages. Refer to: ${h}`;break;case 3:g="Server is invalid. Please contact our engineer. ";break;case 4:g=`Your packages is not active. Refer to: ${h}`;break;case 5:g=`Your packages is expired. Refer to: ${h}`;break;case 6:g="Your version is not supported.";break}return{auth:!1,status:m,message:l?`${_} Reason: ${l}. ${g}`:`${_}, ${g}`}})}var gd=0,Uh=class{constructor(i,e){d(this,"audioObjectURL");d(this,"player");d(this,"publisher");d(this,"mixInput");this.mixInput=new cs(e),i.url?(this.player=new Audio(i.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(i.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(i.track),this.mixInput.connect()}updateSettings(i){this.player&&(T(i.volume)||(this.volume=i.volume),T(i.loop)||(this.loop=i.loop),T(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}reload(i){return p(this,null,function*(){if(i.url){let e=yield jn.download(i.url,{retries:3,type:"blob"});this.audioObjectURL&&URL.revokeObjectURL(this.audioObjectURL),this.audioObjectURL=URL.createObjectURL(e),this.player&&this.publisher?(this.player.src=this.audioObjectURL,this.publisher.src=this.audioObjectURL):(this.player=new Audio(this.audioObjectURL),this.player.crossOrigin="anonymous",this.publisher=new Audio(this.audioObjectURL),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher),this.updateListener(i),this.updateSettings(i))}else this.mixInput.replaceSource(i.track)})}reset(){this.seek(0),this.mixInput.connect()}seek(i){this.player&&(i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i))}play(){var i,e;return Promise.all([(i=this.player)==null?void 0:i.play(),(e=this.publisher)==null?void 0:e.play()])}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function ys(o,i){if(i&&typeof i!="function")throw new V({code:$.INVALID_PARAMETER,message:`start audioMixer plugin: param ${o} should be a function.`})}var wi=class wi{constructor(i){this.core=i;d(this,"log");d(this,"mixedMusicMap",new Map);d(this,"cacheMusicMap",new Map);gd=gd+1,this.log=i.log.createChild({id:`${this.getAlias()}${gd}`}),this.log.info(`created id=${this.getAlias()}${gd}`)}getName(){return wi.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return wi.startValidateRule;case"update":return wi.updateValidateRule;case"stop":return wi.stopValidateRule}}start(i){return p(this,null,function*(){let{room:e}=this.core;this.core.validateSourceNode(),this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:r}=i;if(this.mixedMusicMap.has(t))return;let s=this.cacheMusicMap.get(t);s?i.url?s.reset():(s.mixInput.replaceSource(i.track),s.mixInput.connect()):(s=new Uh(i,e.audioManager),this.cacheMusicMap.set(t,s)),s.updateListener(i),s.updateSettings(i);try{yield s.play()}catch(n){yield this.handleAutoPlayFailed(s,i,n)}this.mixedMusicMap.set(t,s),s.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:s.mixInput.source.node,refId:`ax-${t}`}),this.log.info(`start mix audio track ${t} success.`),v.addEnum({key:502700,value:3}),this.kvUpload(i)})}handleAutoPlayFailed(i,e,t){return p(this,null,function*(){if(t.name==="NotSupportedError")this.log.error(`play failed, try to reload source. error: ${t}`),yield i.reload(e),yield i.play();else if(t.name==="NotAllowedError")if(this.core.room.enableAutoPlayDialog){let r=()=>{var s;(s=i.play())==null||s.finally(()=>{S.off("154",r,this)})};S.on("154",r,this),ns()}else this.core.trtc.emit(x.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>p(this,null,function*(){return i.play()})});else throw t})}update(i){return p(this,null,function*(){let{id:e,operation:t,seekFrom:r,playbackRate:s}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),T(t)||n.setOperation(t),T(r)||n.seek(r),this.kvUpload(i)})}stop(e){return p(this,arguments,function*({id:i}){if(this.mixedMusicMap.has(i)){this.log.info(`remove music source, music id: ${i}`);let t=this.mixedMusicMap.get(i);t!=null&&t.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:t.mixInput.source.node,refId:`ax-${i}`}),t==null||t.stop(),this.mixedMusicMap.delete(i)}i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:r,playbackRate:s,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:l,onEnded:u}=i;e&&v.addCount({key:502009}),t&&v.addCount({key:502001}),r&&v.addCount({key:502002}),s&&v.addCount({key:502003}),n&&v.addCount({key:502004}),a&&v.addCount({key:502005}),typeof c!="function"&&v.addCount({key:502007}),typeof u!="function"&&v.addCount({key:502008}),typeof l!="function"&&v.addCount({key:502006})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>{i!=null&&i.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:i.mixInput.track,refId:e}),this.stop({id:e})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};d(wi,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let r=i.url.split("?")[0],s=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=s.indexOf(n)>=0,c=r.startsWith("blob"),l=r.startsWith("data");if(!(a||c||l))throw new V({code:$.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new V({code:$.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});ys("onTimeUpdate",i.onTimeUpdate),ys("onEnded",i.onEnded),ys("onDurationChange",i.onDurationChange)}}),d(wi,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(i,e,t){ys("onTimeUpdate",i.onTimeUpdate),ys("onEnded",i.onEnded),ys("onDurationChange",i.onDurationChange)}}),d(wi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),d(wi,"Name","AudioMixer");var Td=wi;var Ed=0,Vh,cr=class cr{constructor(i){this.core=i;d(this,"log");d(this,"audioContext",Ee("denoiser"));d(this,"workletNode");d(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5});Ed=Ed+1,this.log=i.log.createChild({id:`${this.getAlias()}${Ed}`}),this.log.info(`created id=${this.getAlias()}${Ed}`)}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0},mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}},validate(e,t,r,s){if(!i.room.audioManager.hasAudioTrack)throw new V({code:$.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return Vh||(Vh=this.doPreload(i)),Vh}doPreload(i){return p(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield tr(this.audioContext,t)}catch(r){throw this.log.error("load worklet failed",r),r}finally{URL.revokeObjectURL(t)}})}getName(){return cr.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(i){switch(i){case"start":return cr.startValidateRule(this.core);case"update":return cr.updateValidateRule;case"stop":return cr.stopValidateRule}}start(i){return p(this,null,function*(){let{room:e,schedule:t}=this.core,{assetsPath:r=this.core.assetsPath}=i;if(!r)throw new V({code:$.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload(`${r}/denoiser-wasm${uu()?"":"-nosimd"}.js`),!this.workletNode){let s=String(Date.now()).slice(0,-3),{auth:n,sign:a,status:c,message:l}=yield zS(t,L(O({},i),{timestamp:s}));if(!n)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${n}. Message: ${l}`),new V({code:$.INVALID_PARAMETER,message:l});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:s,sign:a,status:c}}),this.workletNode.port.onmessage=u=>{var h;let{data:m}=u;if(m.type==="cost"){let _=(m==null?void 0:m.max)>20?"warn":(m==null?void 0:m.max)>10?"info":"debug";this.log[_](`avg cost: ${m.value} max: ${m==null?void 0:m.max}(${No(new Date(m==null?void 0:m.maxCostTimestamp))}) hist: ${(h=m==null?void 0:m.hist)==null?void 0:h.join(" ")}`)}else m.type==="log"&&this.log[m.logLevel](`${m.value}`)}}this.updateConfig(i),this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(i){return p(this,null,function*(){this.updateConfig(i)})}stop(){return p(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}updateConfig(i){if(!this.workletNode)return;let e=!1;T(i.mode)||(i.mode===0?this.config.enableFarFieldReduce=!1:i.mode===1&&(this.config.enableFarFieldReduce=!0),e=!0),T(i.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=i.farFieldReduceThreshold,e=!0),e&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};d(cr,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),d(cr,"stopValidateRule",{type:"object"}),d(cr,"Name","AIDenoiser");var Sd=cr;function zS(s,n){return p(this,arguments,function*(o,{sdkAppId:i,userId:e,userSig:t,timestamp:r}){try{let{data:{errCode:a,errMsg:c,sign:l,status:u}}=yield o.getAbilityConfig(i,o.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:e,userSig:t,timestamp:r});if(u==="1")return{auth:!0,sign:l,status:u,message:c};let m=Ut(i)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",h="Init RTCAIDenoiser failed.",_="";switch(a){case 1:_="Please check your params.";break;case 2:_=`You need to buy packages. Refer to: ${m}`;break;case 3:_="Server is invalid. Please contact our engineer. ";break;case 4:_=`Your packages is not active. Refer to: ${m}`;break;case 5:_=`Your packages is expired. Refer to: ${m}`;break;case 6:_="Your version is not supported.";break}return{auth:!1,status:u,message:c?`${h} Reason: ${c}. ${_}`:`${h}, ${_}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var jf=Ge(at(),1);var Fh=class extends jf.EventEmitter{constructor(){super();d(this,"observer");d(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return p(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!_e&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){se.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,r=e[e.length-1];this.state=r.state,(this.stateNum>3||t>3)&&R.info(`${r.source}: ${r.state}`),this.emit("state-changed",{type:r.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){se.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},QS=new Fh,Bh=QS;var Hh=0,Xn=class Xn{constructor(i){this.core=i;d(this,"log");d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_subStreamSeiMessageList",[]);Hh++,this.log=i.log.createChild({id:`${this.getAlias()}${Hh}`}),this.log.info(`[sei] created id=${this.getAlias()}${Hh}`),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode({frame:i,mediaType:e}){try{let t=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList;return kh({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return Ph({frame:i,onSEI:t=>{t.forEach(r=>{e!=null&&e.userId?this.core.trtc.emit(x.SEI_MESSAGE,{seiPayloadType:r.seiPayloadType,data:r.seiPayload.buffer,userId:(e==null?void 0:e.userId)||"",streamType:(e==null?void 0:e.mediaType)===2?"sub":"main"}):this.core.innerEmitter.emit(this.core.INNER_EVENT.SEI_MESSAGE,{room:this.core.room,nalu:r})})}})}destroy(){this.log.debug("destroy"),this.stop(),delete this.core}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:hi?this.encode:kh,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:hi?this.decode:Ph,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:i,options:e}){var s;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(s=this.core.room.scriptTransformWorker)==null||s.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return Xn.Name}getAlias(){return"sei"}getGroup(){return"sei"}};d(Xn,"autoStart",!0),d(Xn,"Name","SEI");var Id=Xn;function $h({frame:o,onDump:i}){return i==null||i(),o}function Wh({frame:o,onDump:i}){return i==null||i(),o}var Xf={"play() error: NotAllowedError:":{tips:o=>o.includes("main <video>")||o.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:o=>o.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:o=>o.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:`The remote stream audio playback is paused, which usually has two possibilities:
|
|
65
65
|
1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.
|
|
66
66
|
2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},"main stream - video player is paused":{tips:`The remote stream video playback is paused, which usually has two possibilities:
|
|
67
67
|
1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.
|
|
68
|
-
2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},'"displaySurface":"window"':{tips:"Screen sharing captures the application window",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"monitor"':{tips:"Screen sharing captures the entire screen",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"browser"':{tips:"Screen sharing captures a certain tab page",color:"blue",class:"blue",textColor:"#fff"},updateMediaSettings:{tips:"The resolution and frame rate below are the actual resolution and frame rate captured",color:"blue",class:"blue",textColor:"#fff"},"main stream start to play with":{tips:"Call remoteStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"stream start to play with":{tips:"Call localStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"main setAudioVolume to 0":{tips:"Business side calls remoteStream.setAudioVolume(0) interface to set the playback volume to 0, which will cause the playback to be silent",color:"orange",class:"orange",textColor:"#fff"},"screen sharing was stopped because the video track is ended":{tips:"Screen sharing capture stopped, possible reasons: user clicks the stop button, the window/page shared by the user is closed, etc.",color:"orange",class:"orange",textColor:"#fff"},"Join() => joining room":{tips:"Call client.join interface",color:"blue",class:"blue",textColor:"#fff"},"publish() => publishing local stream":{tips:"Call client.publish interface",color:"blue",class:"blue",textColor:"#fff"},"subscribe() => subscribe to":{tips:"Call client.subscribe interface",color:"blue",class:"blue",textColor:"#fff"},"switchRole() => switch role":{tips:"Call client.switchRole interface",color:"blue",class:"blue",textColor:"#fff"}};["enterRoom","exitRoom","switchRole","destroy","startLocalAudio","updateLocalAudio","stopLocalAudio","startLocalVideo","updateLocalVideo","stopLocalVideo","startScreenShare","updateScreenShare","stopScreenShare","startRemoteVideo","updateRemoteVideo","stopRemoteVideo","muteRemoteAudio","setRemoteAudioVolume"].forEach(o=>{Xf[`${o}()`]={tips:`Call trtc.${o}`,color:"blue",class:"blue",textColor:"#fff"}});var $x=Object.keys(Xf);var YS=0,Ad,zn=class zn{constructor(i){this.core=i;d(this,"_core");d(this,"log");d(this,"dumpLocalVideoMap",{});d(this,"dumpRemoteVideoMap",{});d(this,"dialog");this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${++YS}`}),this.log.info("created")}getName(){return zn.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(i){switch(i){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return p(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog(),this.addVideoProcessor())})}update(e){return p(this,arguments,function*({visible:i}){i?(yield this.openDebugDiaLog(),this.addVideoProcessor()):(this.closeDebugDiaLog(),this.removeVideoProcessor())})}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return p(this,null,function*(){var i;if(!this.dialog)try{if(Ad)yield Ad;else{let e=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((i=window.sessionStorage)==null?void 0:i.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${qf}@${He}/assets/debug-dialog.js`;Ad=this._core.fileDownloader.loadScript(e),yield Ad}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(e){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(e))}})}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):$h,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):Wh,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo({frame:i,mediaType:e}){return $h({frame:i,onDump:()=>{if(!e)return;let t=e===2?"sub":"main",r=this.dumpLocalVideoMap[t];r&&(r.data.push(i.data.slice(0)),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}})}decodeVideo({frame:i,track:e}){return Wh({frame:i,onDump:()=>{if(!e)return;let t=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];t&&(t.data.push(i.data.slice(0)),t.duration>0&&Date.now()-t.startTimestamp>t.duration*1e3&&t.onDumpEnd())}})}};d(zn,"Name","Debug"),d(zn,"autoStart",!0);var Cd=zn;var zf=o=>{switch(o){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},Rd=class{constructor(i,e,t){d(this,"trackDoneOB");d(this,"startOB");d(this,"stopOB");d(this,"inputFrameCount",0);d(this,"decodedFrameCount",0);d(this,"type","auto");d(this,"config");d(this,"decoder");d(this,"_decodeSink");let{kvStatManager:r,trtc:s}=i;this.config=t.config,this.trackDoneOB=ce(e,J.INIT),this.stopOB=ot(),this.startOB=ot(),t.type==="auto"?this.type="webCodecs":this.type=t.type;let n=ot(),a=c=>{let l=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),de(l,ke(this.stopOB),Te(()=>{},u=>{e.log.error(u),r.addFailedEvent({key:zf(this.type),error:u}),c>4?this.startOB.error(u):this.startOB.next(c+1)})),de(l,or(1),ph(Vn))};de(this.startOB,xn(0),Mr(a),ke(this.stopOB),Te(()=>{e.player.setOutput(),n.next("STARTED")},c=>{n.next("FAILED")},()=>{r.addSuccessEvent({key:zf(this.type)}),r.addSuccessEvent({key:504702})}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.startOB.next(0)}close(i){this.stopOB.next(i)}pipe(i){return rr()(e=>p(this,null,function*(){this._decodeSink=e,e.defer(()=>{var r;(r=this.decoder)==null||r.close()});let{type:t}=this;try{switch(t){case"webCodecs":this.decoder=new AudioDecoder({error:r=>{i.log.error(r),e.error(4)},output:r=>{this.decodedFrameCount++,e.next(r),i.player.write(r)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(r){i.log.error(r),e.error(t==="webCodecs"?2:6)}}))}decodeFrame(i){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:i.data,timestamp:i.timestamp,type:"key"}))}},ZS={type:"object"},Qn=class Qn{constructor(i){this.core=i;d(this,"log");d(this,"contextMap",new Map);d(this,"decodeProcessorMap",new WeakMap);this.log=i.log.createChild({id:`${this.getAlias()}`})}getAlias(){return Qn.Name}getGroup(i){return i.track.userId+i.track.streamType}getName(){return Qn.Name}getValidateRule(i){return ZS}start(i){let{track:e}=i;this.decodeProcessorMap.set(e,this.decode(i)),this.core.room.audioManager.addDecodeProcessor({processor:({frame:t,track:r})=>this.decodeProcessorMap.has(r)?this.decodeProcessorMap.get(r)({frame:t,track:r}):t,type:3})}decode(i){return({frame:e,track:t})=>{if(t!==i.track)return e;if(this.contextMap.has(t))return this.contextMap.get(t).decodeFrame(e);let r=new Rd(this.core,t,i);return de(r.trackDoneOB,or(1),Te(()=>{this.core.clearStarted(this,this.getGroup(i)),this.stop({track:t})})),this.contextMap.set(t,r),r.decodeFrame(e)}}stop({track:i}){let e=this.contextMap.get(i);e&&(e.close("stop"),this.contextMap.delete(i),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(i){let e=this.contextMap.get(i.track);if(e){if(i.type==="mock"){e.mock(10);return}e.close("update"),this.contextMap.set(i.track,new Rd(this.core,i.track,i))}}};d(Qn,"Name","TRTCAudioDecoder");var Yn=Qn;var yd=class{constructor(){d(this,"log");this.log=R.createLogger({id:"exp"})}call(i,e){return p(this,null,function*(){return le(this[i])?this[i](e):Promise.reject(new D({code:I.INVALID_PARAMETER,message:H({key:F.API_NOT_EXIST,data:{name:i}})}))})}enableAudioFrameEvent(i){return p(this,null,function*(){let{trtcInstance:e,enable:t,userId:r,sampleRate:s=48e3,channelCount:n=1,port:a}=i,{audioManager:c}=e.room,{getPCMAbortCtrlMap:l,audioFrameEventConfigMap:u}=c;if(u.set(r,{enable:t,sampleRate:s,channelCount:n,port:a}),t)if(r==="*")e.room.remotePublishedUserMap.forEach(m=>{if(m.remoteAudioTrack.isAvailable){if(l.get(m.userId))return;let h=c.getPCM(_=>{e.emit(x.AUDIO_FRAME,_)},m.userId);l.set(m.userId,h)}});else{if(l.get(r))return;let m=c.getPCM(h=>{e.emit(x.AUDIO_FRAME,h)},r);l.set(r,m)}else if(r==="*")e.room.remotePublishedUserMap.forEach(m=>{if(m.remoteAudioTrack.isSubscribed){let{userId:h}=m,_=l.get(h);_==null||_.abort("disable"),l.delete(h)}});else{let m=l.get(r);m==null||m.abort("disable"),l.delete(r)}})}resumeRemotePlayer(i){return p(this,null,function*(){if(i.userId==="*"){let t=[];return i.trtcInstance.room.remotePublishedUserMap.forEach(r=>{let{remoteAudioTrack:s,remoteVideoTrack:n,remoteAuxiliaryTrack:a}=r;i.streamType?i.streamType==="main"?(s.isAvailable&&t.push(s.player.resume()),n.isAvailable&&t.push(n.player.resume())):a.isAvailable&&t.push(a.player.resume()):(s.isAvailable&&t.push(s.player.resume()),n.isAvailable&&t.push(n.player.resume()),a.isAvailable&&t.push(a.player.resume()))}),Promise.all(t)}let e=i.trtcInstance.room.remotePublishedUserMap.get(i.userId);if(e)return i.streamType==="main"?Promise.all([e.remoteAudioTrack.player.resume(),e.remoteVideoTrack.player.resume()]):e.remoteAuxiliaryTrack.player.resume()})}pauseRemotePlayer(i){if(i.userId==="*")i.trtcInstance.room.remotePublishedUserMap.forEach(e=>{let{remoteAudioTrack:t,remoteVideoTrack:r,remoteAuxiliaryTrack:s}=e;i.streamType?i.streamType==="main"?(t.isAvailable&&t.player.pause(),r.isAvailable&&r.player.pause(!1)):s.isAvailable&&s.player.pause(!1):(t.isAvailable&&t.player.pause(),r.isAvailable&&r.player.pause(!1),s.isAvailable&&s.player.pause(!1))});else{let e=i.trtcInstance.room.remotePublishedUserMap.get(i.userId);e&&(i.streamType==="main"?(e.remoteAudioTrack.player.pause(),e.remoteVideoTrack.player.pause(!1)):e.remoteAuxiliaryTrack.player.pause(!1))}}};M([Sf({name:"options",type:"object",required:!0,properties:{enable:{required:!0,type:"boolean"},userId:{required:!0,type:"string"},sampleRate:{type:"number",values:[8e3,16e3,32e3,44100,48e3]},channelCount:{type:"number",values:[1,2]},port:{type:"messageport"}}})],yd.prototype,"enableAudioFrameEvent",1);var Qf=new yd;var Yf=Ge(at(),1);var Gh=class extends Yf.EventEmitter{constructor(){super();d(this,"states",{});d(this,"permissionChangeHandler");d(this,"log");this.log=R.createLogger({id:"pm"}),this.permissionChangeHandler=()=>{var e,t;this.emit("permission-state-change",{camera:(e=this.states.camera)==null?void 0:e.state,microphone:(t=this.states.microphone)==null?void 0:t.state})}}request(e){return p(this,null,function*(){if(this.log.info(`request ${e.join(", ")}`),e.length===0)return Promise.resolve();(yield navigator.mediaDevices.getUserMedia({video:e.includes("camera"),audio:e.includes("microphone")})).getTracks().forEach(r=>r.stop())})}get(e){return p(this,null,function*(){try{return this.states[e]||(this.states[e]=yield navigator.permissions.query({name:e}),this.states[e].addEventListener("change",this.permissionChangeHandler)),this.log.info(`get ${e} permission state: ${this.states[e].state}`),this.states[e].state}catch(t){return this.log.error(`get ${e} permission failed, error: ${t instanceof Error?t.message:t}`),null}})}destroy(){Object.values(this.states).forEach(e=>{e==null||e.removeEventListener("change",this.permissionChangeHandler)}),this.states={}}},Zn=new Gh;var Zf=0,Kn=new Set,ze=null;qd(wh);es.checkStorage();var q=class q extends Kf.EventEmitter{constructor(e,t){super();d(this,"_room");d(this,"_eventListened",new Set);d(this,"_localVideoTrack",null);d(this,"_localAudioTrack",null);d(this,"_localScreenTrack",null);d(this,"_localScreenAudioTrack",null);d(this,"_localVideoConfig",null);d(this,"_localScreenConfig",null);d(this,"_localAudioConfig",null);d(this,"_remoteVideoConfigMap",new Map);d(this,"_remoteAudioConfigMap",new Map);d(this,"_remoteAudioVolumeMap",new Map);d(this,"_remoteAudioMuteMap",new Map);d(this,"_mediaTrackMap",new WeakMap);d(this,"_log",R.createLogger({id:`t${++Zf}`}));d(this,"_plugins",new Map);d(this,"_networkQuality",null);d(this,"_speakerId");d(this,"enterRoomParams");d(this,"_enableAutoSwitchWhenRecapturing",!0);this._room=new e(O({logger:this._log,frameWorkType:q.frameWorkType},t)),this._room.videoDecodeFallbackType=t.videoDecodeFallback,he(t.enableAutoSwitchWhenRecapturing)&&(this._enableAutoSwitchWhenRecapturing=t.enableAutoSwitchWhenRecapturing),this._log.info(`create() ${JSON.stringify(t,(r,s)=>r==="plugins"?s.map(n=>n.Name):s)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(r){return this._room.audioManager.dump(r)}}}),t.plugins&&t.plugins.forEach(r=>{this._use(r,t.assetsPath)}),this._use(Td,t.assetsPath),this._use(_d,t.assetsPath),this._use(Sd,t.assetsPath),this._use(Yn,t.assetsPath),this._use(Cd),t.enableSEI&&En&&this._use(Id),this._room.on("audio-volume",r=>{var s,n;!r.find(a=>a.userId==="")&&this._localAudioTrack&&r.push({userId:"",volume:Math.floor(((s=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?s:this._localAudioTrack.getAudioLevel())*100),floatVolume:(n=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?n:this._localAudioTrack.getInternalAudioLevel()}),t.volumeType===1&&r.forEach(a=>{var l;let c=a.userId===""?this._localAudioTrack:(l=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:l.remoteAudioTrack;c&&(a.volume=c.dbVolume)}),t.enableDbVolume&&r.forEach(a=>{var l;let c=a.userId===""?this._localAudioTrack:(l=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:l.remoteAudioTrack;c&&(a.volume=c.dbVolume)}),this.emit(x.AUDIO_VOLUME,{result:r.sort((a,c)=>c.volume-a.volume)})}),this._room.videoManager.on("error",r=>{this._log.error(new V({code:$.OPERATION_FAILED,extraCode:5504,message:r.message,originError:r}))}),this._listenEvents(),this._initActiveSpeaker(),Hf(this,"trtc")}static create(e){}static _create(e,t){Cf();let r=new q(e,t||{});return Kn.add(r),r.__v_skip=!0,r}get room(){return this._room}_listenEvents(){tt(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(x.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit(x.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{Lt(!0),this._exitRoom().finally(()=>{this.emit(x.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(x.ERROR,V.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(x.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let t=L(O({},e),{uplinkRTT:Math.min(e.uplinkRTT,$s),downlinkRTT:Math.min(e.downlinkRTT,$s)});this.emit(x.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{tt(r,r).add("player-state-changed",s=>{let n=L(O({},s),{userId:e.userId});r.kind===f.VIDEO&&(n.streamType=ki(r.streamType)),this.emit(r.kind===f.AUDIO?x.AUDIO_PLAY_STATE_CHANGED:x.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",s=>{s.getCode()===I.PLAY_NOT_ALLOWED&&this.emit(x.AUTOPLAY_FAILED,{userId:r.userId,mediaType:r.strMediaType,resume:()=>r.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{Le(r)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:r}=t,s=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:c}=t;a||this._remoteAudioConfigMap.delete(r),c||this._removeRemoteVideoConfig(r,"main"),t.hasAuxiliary||this._removeRemoteVideoConfig(r,"sub"),n!==c&&(c?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"}),this.emit(c?x.REMOTE_VIDEO_AVAILABLE:x.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),s!==a&&(a?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:t}),this.emit(a?x.REMOTE_AUDIO_AVAILABLE:x.REMOTE_AUDIO_UNAVAILABLE,{userId:r})),e.hasAuxiliary!==t.hasAuxiliary&&(t.hasAuxiliary?this._onVideoAvailable({userId:r,streamType:"sub"}):this._onVideoUnavailable({userId:r,streamType:"sub"}),this.emit(t.hasAuxiliary?x.REMOTE_VIDEO_AVAILABLE:x.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}))}).add("sei-message",e=>{this.emit(x.SEI_MESSAGE,L(O({},e),{streamType:ki(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(x.ERROR,new V({code:$.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var s,n,a,c,l,u,m;let t={2:"big",3:"small",7:"sub"},r={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((s=e.msg_down_stream_info[0])==null?void 0:s.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,$s),upLoss:((c=this._networkQuality)==null?void 0:c.uplinkLoss)||0,downLoss:((l=this._networkQuality)==null?void 0:l.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((u=e.msg_up_stream_info.msg_audio_status)==null?void 0:u.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((m=e.msg_up_stream_info.msg_audio_status)==null?void 0:m.uint32_audio_level)||0)/Dt},video:e.msg_up_stream_info.msg_video_status.filter(h=>t[h.uint32_video_stream_type]).map(h=>({bitrate:(h.uint32_video_codec_bitrate||0)/1e3,width:h.uint32_video_width,height:h.uint32_video_height,frameRate:h.uint32_video_enc_fps,videoType:t[h.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(h=>({userId:h.msg_user_info.str_identifier,audio:{bitrate:(h.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(h.msg_audio_status.uint32_audio_level||0)/Dt,point2pointDelay:(h.msg_audio_status.uint32_audio_p2p_delay||0)+(h.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:h.msg_audio_status.uint32_audio_cache_ms||0},video:h.msg_video_status.map(_=>({bitrate:(_.uint32_video_codec_bitrate||0)/1e3,width:_.uint32_video_width,height:_.uint32_video_height,frameRate:_.uint32_video_dec_fps,videoType:t[_.uint32_video_stream_type],point2pointDelay:(_.uint32_video_p2p_delay||0)+(_.uint32_video_cache_ms||0),jitterBufferDelay:_.uint32_video_cache_ms||0,codec:_.uint32_video_codec}))}))};this.emit(x.STATISTICS,r)}).add("custom-message",e=>{this.emit(x.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(x.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(x.FIRST_VIDEO_FRAME,L(O({},e),{streamType:ki(e.streamType)}))}).add("audio-frame",e=>{this.emit(x.AUDIO_FRAME,e)}),tt(this,be).add("audioInputAdded",e=>{this.emit(x.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(x.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(x.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(x.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>p(this,null,function*(){if(this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),ze&&ze.deviceId===Hs){let t=(yield Nr()).find(r=>r.deviceId===Hs);t&&ze.groupId!==t.groupId&&(ze=t,this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>p(this,null,function*(){this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield Nr())[0];if(!t||!ze||ze.groupId===t.groupId)return;let r=ze.deviceId===e.deviceId,s=ze.deviceId===Hs&&ze.deviceId===t.deviceId;(r||s)&&(ze=t,this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))})),tt(this,Zn).add("permission-state-change",e=>{this.emit(x.PERMISSION_STATE_CHANGE,e)}),this.room.enableSEI&&this.on(x.SEI_MESSAGE,e=>{var r;let t=(r=this.room.remotePublishedUserMap.get(e.userId))==null?void 0:r.remoteVideoTrack;t&&t.updateAlphaRenderInfo(e)})}getNetworkTime(){return Fi()}use(e){let t,r;return"plugin"in e?(t=e.plugin,r=e.assetsPath):t=e,t.Name==="Chorus"&&(this.room.enableChorus=!0),this._use(t,r)}_use(e,t){let r=this._plugins.get(e.Name);if(r)return this._log.warn("duplicate install plugin",e.Name),r;let s=new e(Bf.call(this,{TRTC:q,room:this._room,assetsPath:t,errorModule:{RtcError:V,ErrorCode:$,CoreErrorCode:I,ErrorCodeDictionary:wt}}));return this._plugins.set(e.Name,s),s.__v_skip=!0,e.autoStart&&this.startPlugin(e.Name),s}enterRoom(e){return p(this,null,function*(){var c,l;this.enterRoomParams=e;let{scene:t="rtc",enableAutoPlayDialog:r=!0,autoReceiveAudio:s=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!ie(e.proxy)&&e.proxy.turnServer&&((l=(c=this._room).setTurnServer)==null||l.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=r,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=n,he(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,useH265:e.useH265||!1,keepAlive:e.keepAlive};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,q.frameWorkType),this._checkTrackToPublish(),Bh.start()})}exitRoom(){return p(this,null,function*(){return yield this._exitRoom()})}switchRoom(e){return p(this,null,function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(e)}catch(t){if(t instanceof ws&&(t.code===I.API_CALL_TIMEOUT||t.code===I.SWITCH_ROOM_FAILED))this._log.warn(`switchRoom ${t.code===I.API_CALL_TIMEOUT?"timeout":"failed"}, fallback to exitRoom() and enterRoom()`),yield this._rejoinRoom(e);else throw t}else yield this._rejoinRoom(e)})}_rejoinRoom(e){return p(this,null,function*(){yield this.exitRoom();let t=O(O({},this.enterRoomParams),e);yield this.enterRoom(t)})}_clearRemoteTracks(){new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch(()=>{})}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let t=e.includes("main")?"main":"sub",r=e.split(`_${t}`)[0];r&&this._stopRemoteVideo({userId:r,streamType:t}).catch(()=>{})}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),$f(this),this._room.remotePublishedUserMap.forEach(e=>{Le(e.remoteAudioTrack),Le(e.remoteVideoTrack),Le(e.remoteAuxiliaryTrack)})}switchRole(e,t){return p(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),t!=null&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)}),this._plugins.clear(),Le(this),this.removeAllListeners(),this._room.destroy(),Kn.delete(this),Kn.size===0&&Bh.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),S.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return p(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,mute:r,option:s}=e,n=new kt(this._room.audioManager),a={},c={muted:!0};s&&(T(s.microphoneId)?T(s.audioTrack)||(a.customSource=s.audioTrack):a.deviceId=s.microphoneId,s&&z(s.captureVolume)&&n.setCaptureVolume(s.captureVolume),T(s.profile)||(ie(s.profile)?fa[s.profile]&&n.setProfile(fa[s.profile]):n.setProfile(s.profile)),z(s.earMonitorVolume)&&(c.muted=!(s.earMonitorVolume>0),c.volume=s.earMonitorVolume),T(s.echoCancellation)||(n.profile.echoCancellation=s.echoCancellation),T(s.noiseSuppression)||(n.profile.noiseSuppression=s.noiseSuppression),T(s.autoGainControl)||(n.profile.autoGainControl=s.autoGainControl),he(this._enableAutoSwitchWhenRecapturing)&&(n.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),n.on("5",l=>{this.emit(x.ERROR,new V({code:$.DEVICE_ERROR,extraCode:5309,messageParams:{error:l}}))}),n.on("2",l=>{this.emit(x.DEVICE_CHANGED,{type:"microphone",action:"active",device:l})}),n.on("4",l=>{let u;l.error&&(u=V.convertFrom(l.error)),this.emit(x.PUBLISH_STATE_CHANGED,L(O({},l),{error:u}))}),n.on("6",()=>{}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),T(r)||n.setMute(r),tt(n,n).add("player-state-changed",l=>{this.emit(x.AUDIO_PLAY_STATE_CHANGED,L(O({},l),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=L(O({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:n}),S.emit("113",{userId:"",room:this.room})})}updateLocalAudio(e){return p(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:r,option:s}=e,n={};s&&(s.microphoneId?yield this._localAudioTrack.switchDevice(s.microphoneId):T(s.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(s.audioTrack)),T(s.captureVolume)||this._localAudioTrack.setCaptureVolume(s.captureVolume),T(s.earMonitorVolume)||(n.muted=!(s.earMonitorVolume>0),n.volume=s.earMonitorVolume),yield this._localAudioTrack.update3A(s)),this._room.isJoined&&!T(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),T(r)||this._localAudioTrack.setMute(r),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),ei(this._localAudioConfig,e)})}stopLocalAudio(){return p(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),S.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),Le(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return p(this,arguments,function*(e={publish:!0,view:null,capture:!0}){var m;if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:t,publish:r=!0,capture:s=!0,mute:n,option:a}=e,c=new je(this._room.videoManager),l={},u={};a&&(he(a.avoidCropping)&&(c.avoidCropping=a.avoidCropping),a.cameraId?l.deviceId=a.cameraId:T(a.useFrontCamera)?T(a.videoTrack)||(l.customSource=a.videoTrack):l.facingMode=a.useFrontCamera?f.FACING_MODE_USER:f.FACING_MODE_ENVIRONMENT,T(a.retryWhenExactFailed)||(l.retryWhenExactFailed=a.retryWhenExactFailed),a.qosPreference&&(l.contentHint=qn(a.qosPreference)),T(a.profile)||(ie(a.profile)?zt[a.profile]&&c.setProfile(zt[a.profile]):c.setProfile(a.profile)),T(a.fillMode)||(u.objectFit=a.fillMode),T(a.mirror)||(u.mirror=a.mirror),T(a.small)||(T(a.smallMode)||(this._room.smallMode=a.smallMode),he(a.small)&&a.small===!1?c.stopSmall():c.updateSmallConfig(Is(a.small,!0))),T(a.rotation)||c.setRotation(a.rotation),he(this._enableAutoSwitchWhenRecapturing)&&(c.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),c.once("first-video-frame",h=>{this.emit(x.FIRST_VIDEO_FRAME,L(O({},h),{streamType:ki(h.streamType)}))}),c.on("5",h=>{this.emit(x.ERROR,new V({code:$.DEVICE_ERROR,extraCode:5308,messageParams:{error:h}}))}),c.on("2",h=>{this.emit(x.DEVICE_CHANGED,{type:"camera",action:"active",device:h})}),c.on("4",h=>{let _;h.error&&(_=V.convertFrom(h.error)),this.emit(x.PUBLISH_STATE_CHANGED,L(O({},h),{error:_}))}),c.on("6",()=>{}),this._listenOutputTrackChanged(c),s?yield c.capture(l):(m=c.manager)==null||m.changeInput(c),T(n)||(yield c.setMute(n)),tt(c,c).add("player-state-changed",h=>{this.emit(x.VIDEO_PLAY_STATE_CHANGED,L(O({},h),{userId:"",streamType:"main"}))}).add("video-size-changed",h=>{this.emit(x.VIDEO_SIZE_CHANGED,L(O({},h),{streamType:ki(h.streamType)}))}),r&&this._room.isJoined&&this._room.publish(c).catch(()=>{}),this._localVideoTrack=c,this._localVideoConfig=L(O({},e),{view:t,publish:r,capture:s}),yield this._updateVideoPlayOption({view:t,playOption:u,track:c})})}updateLocalVideo(e){return p(this,null,function*(){var l,u,m;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:r,mute:s,capture:n,option:a}=e,c={};if(this._localVideoConfig.capture)n!==!1?a!=null&&a.cameraId?yield this._localVideoTrack.switchDevice(a==null?void 0:a.cameraId):T(a==null?void 0:a.useFrontCamera)?T(a==null?void 0:a.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(a==null?void 0:a.videoTrack)):yield this._localVideoTrack.switchDevice(a!=null&&a.useFrontCamera?f.FACING_MODE_USER:f.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(n){let h={};h.deviceId=(a==null?void 0:a.cameraId)||((l=this._localVideoConfig.option)==null?void 0:l.cameraId),h.facingMode=a!=null&&a.useFrontCamera||(u=this._localVideoConfig.option)!=null&&u.useFrontCamera?f.FACING_MODE_USER:f.FACING_MODE_ENVIRONMENT,h.customSource=(a==null?void 0:a.videoTrack)||((m=this._localVideoConfig.option)==null?void 0:m.videoTrack),yield this._localVideoTrack.capture(h)}a&&(T(a.profile)||(ie(a.profile)?zt[a.profile]&&this._localVideoTrack.setProfile(zt[a.profile]):this._localVideoTrack.setProfile(a.profile),(!a.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(a.cameraId))&&T(a.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),T(a.fillMode)||(c.objectFit=a.fillMode),T(a.mirror)||(c.mirror=a.mirror),T(a.rotation)||this._localVideoTrack.setRotation(a.rotation),a.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(qn(a.qosPreference)),T(a.small)||(he(a.small)&&!a.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(Is(a.small,!0)))),this._room.isJoined&&T(r)&&this._localVideoConfig.publish&&n&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&((r!=null?r:this._localVideoConfig.publish)?this._room.publish(this._localVideoTrack).catch(()=>{}):this._room.unpublish(this._localVideoTrack).catch(()=>{})),T(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:t,playOption:c,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),ei(this._localVideoConfig,e)})}stopLocalVideo(){return p(this,null,function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),Le(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return p(this,arguments,function*(e={publish:!0,view:null}){var h,_;if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:t=null,publish:r=!0,muteSystemAudio:s,option:n}=e,a=new Pt(this._room.videoManager);a.on("4",g=>{let E;g.error&&(E=V.convertFrom(g.error)),this.emit(x.PUBLISH_STATE_CHANGED,L(O({},g),{error:E}))}),a.once("first-video-frame",g=>{this.emit(x.FIRST_VIDEO_FRAME,L(O({},g),{streamType:ki(g.streamType)}))}),this._listenOutputTrackChanged(a),e.streamType==="main"&&(a.mediaType=4);let c=null,l={},u={};n&&(T(n.profile)||(ie(n.profile)?_a[n.profile]&&a.setProfile(_a[n.profile]):a.setProfile(n.profile)),n.systemAudio&&(l.systemAudio=!0,l.echoCancellation=n.echoCancellation,l.noiseSuppression=n.noiseSuppression,l.autoGainControl=n.autoGainControl),T(n.fillMode)||(u.objectFit=n.fillMode),n.videoTrack&&(l.videoTrack=n.videoTrack),n.audioTrack&&(l.audioTrack=n.audioTrack),n.captureElement&&(l.captureElement=n.captureElement),n.preferDisplaySurface&&(l.preferDisplaySurface=n.preferDisplaySurface),n.qosPreference&&(l.contentHint=qn(n.qosPreference)));let m=yield a.capture(l);if(a.mediaTrack.addEventListener(f.ENDED,()=>{this._stopScreenShare(),this.emit(x.SCREEN_SHARE_STOPPED)}),m.getAudioTracks()[0]){c=new To(this._room.audioManager);let g=m.getAudioTracks()[0];(h=e.option)!=null&&h.systemAudio&&!((_=e.option)!=null&&_.audioTrack)&&(c.sourceTrack=g),yield c.setInputMediaStreamTrack(g),he(s)&&c.mediaTrack&&(c.mediaTrack.enabled=!s),this._speakerId&&c.setAudioOutput(this._speakerId)}if(tt(a,a).add("player-state-changed",g=>{this.emit(x.VIDEO_PLAY_STATE_CHANGED,L(O({},g),{userId:"",streamType:"sub"}))}),r&&this._room.isJoined){let g=[a];c&&(g.push(c),this._checkScreenAudioEchoCancellation(a,c)),g.forEach(E=>this._room.publish(E).catch(()=>{}))}this._localScreenTrack=a,this._localScreenAudioTrack=c,this._localScreenConfig=L(O({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:u,track:a})})}updateScreenShare(e){return p(this,null,function*(){var c;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:r,muteSystemAudio:s,option:n}=e,a={};if(n&&(T(n.fillMode)||(a.objectFit=n.fillMode),n.qosPreference)){let l=qn(n.qosPreference);this._localScreenTrack.setContentHint(l)}if(this._room.isJoined&&!T(r)){if(r&&!this._localScreenConfig.publish){let l=[this._localScreenTrack];this._localScreenAudioTrack&&l.push(this._localScreenAudioTrack),l.forEach(u=>this._room.publish(u).catch(()=>{}))}if(this._localScreenConfig.publish&&!r){let l=[this._localScreenTrack];this._localScreenAudioTrack&&l.push(this._localScreenAudioTrack),l.forEach(u=>this._room.unpublish(u).catch(()=>{}))}}(c=this._localScreenAudioTrack)!=null&&c.mediaTrack&&he(s)&&(this._localScreenAudioTrack.mediaTrack.enabled=!s),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),ei(this._localScreenConfig,e)})}stopScreenShare(){return p(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return p(this,null,function*(){let{view:t,userId:r,streamType:s,option:n}=e,a=`${r}_${s}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${r}, streamType:${s}`);return}let c=this._room.remotePublishedUserMap.get(r);if(!c)return;let l={},u=s==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;u.on("decode-failed",m=>{this.emit(x.ERROR,new V({code:$.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))}),u.on("video-size-changed",m=>{this.emit(x.VIDEO_SIZE_CHANGED,L(O({},m),{streamType:ki(m.streamType)}))}),this._listenOutputTrackChanged(u),n&&(T(n.fillMode)||(l.objectFit=n.fillMode),T(n.mirror)||(l.mirror=n.mirror),T(n.poster)||(l.poster=n.poster),l.canvasRender=n.canvasRender,s==="main"&&!T(n.small)&&(!c.remoteVideoTrack.isSubscribing&&!c.remoteVideoTrack.isSubscribed&&c.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,u.user)),T(n.draggable)||u.setDraggable(n.draggable)),yield this._room.subscribe(u),yield this._enableVideoDecodeFallback(u,s),yield this._updateVideoPlayOption({view:t,playOption:l,track:u}),this._emitTrackEvent(u),this._remoteVideoConfigMap.set(a,{config:e}),n&&!T(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:u,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return p(this,null,function*(){var k,re;let{view:t,userId:r,streamType:s,option:n,mute:a}=e,c=`${r}_${s}`,l=this._remoteVideoConfigMap.get(c);if(!l||!this._room.remotePublishedUserMap.has(r))return;let u={};n&&(T(n.fillMode)||(u.objectFit=n.fillMode),T(n.mirror)||(u.mirror=n.mirror));let m=null,h=this._room.remotePublishedUserMap.get(r);if(s==="main"&&(h!=null&&h.muteState.hasVideo)&&(m=h.remoteVideoTrack),s==="sub"&&(h!=null&&h.muteState.hasAuxiliary)&&(m=h.remoteAuxiliaryTrack),!m)return;let{config:_}=l;s==="main"&&n&&!T(n.small)&&this._room.changeType(n.small,m.user),n&&!T(n.draggable)&&m.setDraggable(n.draggable),he(a)&&(m.ignoreUpdatePlayingState=!0,a?(yield m.player.pause(),yield this.room.unsubscribe(m)):(yield this.room.subscribe(m),yield m.player.resume(!0))),yield this._updateVideoPlayOption({view:t,playOption:u,track:m,prevConfig:_}),ei(_,e);let g=T(n==null?void 0:n.receiveWhenViewVisible)?(k=_.option)==null?void 0:k.receiveWhenViewVisible:n.receiveWhenViewVisible,E=T(t)?_.view:t,A=T(n==null?void 0:n.viewRoot)?(re=_.option)==null?void 0:re.viewRoot:n.viewRoot;this._observeView({remoteTrack:m,view:E,receiveWhenViewVisible:g,viewRoot:A})})}stopRemoteVideo(e){return p(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return p(this,null,function*(){let r=[],s=this._room.remotePublishedUserMap.get(e.userId);if(s){let{muteState:n,remoteVideoTrack:a,remoteAuxiliaryTrack:c}=s;e.streamType==="main"&&(a.stop(),n.hasVideo&&r.push(a)),e.streamType==="sub"&&(c.stop(),n.hasAuxiliary&&r.push(c))}for(let n of r)t&&(delete n.ignoreUpdatePlayingState,yield this._room.unsubscribe(n),this._mediaTrackMap.delete(n.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)})}_removeRemoteVideoConfig(e,t){let r=`${e}_${t}`,s=this._remoteVideoConfigMap.get(r);s&&s.observer&&s.observer.disconnect(),this._remoteVideoConfigMap.delete(r)}muteRemoteAudio(e,t){return p(this,null,function*(){this._remoteAudioMuteMap.set(e,t);try{if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let r=[...this._room.remotePublishedUserMap.values()];for(let s of r)s.muteState.hasAudio&&!this._remoteAudioConfigMap.has(s.userId)&&(yield this._startRemoteAudio({userId:s.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(r){throw r.code!==$.OPERATION_ABORT&&this._remoteAudioMuteMap.delete(e),r}})}setRemoteAudioVolume(e,t){if(e==="*"){this._remoteAudioVolumeMap.set("*",t),this._remoteAudioVolumeMap.forEach((s,n)=>this._remoteAudioVolumeMap.set(n,t));let r=[...this._room.remotePublishedUserMap.values()];for(let s of r)this._remoteAudioVolumeMap.set(s.userId,t),s.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:s.remoteAudioTrack})}else if(e){let r=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,t),r&&r.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:r.remoteAudioTrack})}}startPlugin(e,t){return p(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return p(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return p(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,r){if(this.listeners(e).includes(t))return this;if(this._log.debug("on",e),super.on(e,t,r),this._eventListened.add(e),this.listeners(x.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:s}=this.room.audioManager;s.get("")||s.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return this}emit(e,...t){try{wf.has(e)||this._log.debug(`emit ${e} ${JSON.stringify(t)}`)}catch(r){}return super.emit(e,...t)}off(e,t,r){if(this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,r),(e===q.EVENT.AUDIO_FRAME||e==="*")&&this.listeners(q.EVENT.AUDIO_FRAME).length===0){let{getPCMAbortCtrlMap:s}=this.room.audioManager;s.forEach(n=>{n==null||n.abort("off")}),s.clear()}return this}getAudioTrack(e={userId:"",streamType:"main"}){let t,r=null,s="main",n=!1;if(ie(e)?t=e:(t=e.userId,n=e.processed===!0,e.streamType&&(s=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);a&&(r=a.remoteAudioTrack)}else r=s==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return r?n&&r.outMediaTrack&&r.outMediaTrack!==r.mediaTrack?r.outMediaTrack.clone():r.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:r="main",processed:s=!1}=e,n=null;if(t==="")r==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),r==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(t);a&&(n=r==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?s&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:t,streamType:r="main"}=e;if(t){let s=this._room.remotePublishedUserMap.get(t);if(r==="main"&&(s!=null&&s.muteState.hasVideo))return s.remoteVideoTrack.getVideoFrame();if(r==="sub"&&(s!=null&&s.muteState.hasAuxiliary))return s.remoteAuxiliaryTrack.getVideoFrame()}else{if(r==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(r==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var t,r;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(r=this._localScreenAudioTrack)==null||r.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(s=>s.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return p(this,null,function*(){(yield Nr()).forEach(r=>{r.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}),ze=r)}),this._log.warn(`the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: ${ft}/en/TRTC.html#.setCurrentSpeaker`)})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return p(this,null,function*(){var a;let{userId:t}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let s={},n=r.remoteAudioTrack;n.on("decode-failed",c=>{this.emit(x.ERROR,new V({code:$.OPERATION_FAILED,extraCode:5508,message:"audio decode failed"}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let c=(a=this._remoteAudioVolumeMap.get(t))!=null?a:this._remoteAudioVolumeMap.get("*"),l=z(c)?c:100;s.volume=l,this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(n),de(ce(n,"decode-failed"),ke(ce(n,J.INIT)),Te(()=>{this.startPlugin(Yn.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:n}),S.emit("115",{userId:t,room:this.room}),n.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:n.outMediaTrack,refId:`ra-${t}`})}catch(c){throw this._remoteAudioConfigMap.delete(t),c}this._emitTrackEvent(n)})}_stopRemoteAudio(e,t=!0){return p(this,null,function*(){let r=this._room.remotePublishedUserMap.get(e.userId);r&&(r.remoteAudioTrack.stop(),r.muteState.hasAudio&&t&&(yield this._room.unsubscribe(r.remoteAudioTrack)),this._mediaTrackMap.delete(r.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`),S.emit("116",{userId:e.userId,room:this.room}),this.room.audioManager.updateAudioReference({type:"remove",refId:`ra-${e.userId}`})})}_enableVideoDecodeFallback(e,t){let r=this._room.videoDecodeFallbackType;if(!r||!this._plugins.has("TRTCVideoDecoder"))return;e.log.debug("remote video will fall back when decode failed",e.id);let s;de(ce(e,"decode-failed"),ke(ce(e,J.INIT)),Bn(()=>{this._room.downlinkVideoCodec!=="h265"&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})}),mo(ce(e,"decode-downgrade-state-changed")),Te(n=>{s=n.state,this.emit(x.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,L(O({},n),{streamType:t,userId:e.userId}))},n=>{e.log.error("fallback",n)},()=>{s==="STARTED"&&e.log.info("fallback complete")}))}_updateVideoPlayOption(n){return p(this,arguments,function*({view:e,playOption:t,track:r,prevConfig:s}){if(r.setMirror(t.mirror),T(e)&&s&&s.view&&!Uo(t)){let a=Fo(s.view);a.length>0&&(yield r.play(a,t))}if(!T(e)){let a=Fo(e);a.length>0?yield r.play(a,t):r.stop()}})}_updateAudioPlayOption(s){return p(this,arguments,function*({playOption:e={},track:t,prevConfig:r}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}if(T(e.muted)||t.setPlayerMute(e.muted),T(e.volume)||t.setAudioVolume(e.volume/100),t instanceof kt&&t.mediaTrack){let n=e.muted===!1&&!T(e.volume)&&e.volume>0?"add":"remove";this.room.audioManager.updateAudioReference({type:n,audioReference:t.mediaTrack,refId:"em"})}else if(t instanceof gi){let n=e.muted?0:e.volume;if(T(n))return;this.room.audioManager.updateAudioReference({type:"updateVolume",refId:`ra-${t.userId}`,volume:e.volume})}})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,t=!0){let r=e.isRemote?e.userId:"";e.outMediaTrack&&(t&&this._mediaTrackMap.get(e.outMediaTrack)===r||(this._mediaTrackMap.set(e.outMediaTrack,r),this.emit(x.TRACK,{userId:r,streamType:ki(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var t,r,s;let e=[];if((t=this._localAudioConfig)!=null&&t.publish&&this._localAudioTrack&&e.push(this._localAudioTrack),(r=this._localVideoConfig)!=null&&r.publish&&this._localVideoTrack&&e.push(this._localVideoTrack),(s=this._localScreenConfig)!=null&&s.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack),this._checkScreenAudioEchoCancellation(this._localScreenTrack,this._localScreenAudioTrack)),e.length!==0)return Promise.all(e.map(n=>this._room.publish(n).catch(()=>{})))}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:r,viewRoot:s}){if(T(t)||T(r))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${ki(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||Ie(t)&&t.length===0||!r){a==null||a.disconnect(),e.isSubscribed||(this._log.info("_observeView observer disconnect, resubscribe",e.userId,e.strMediaType),this._room.subscribe(e).catch(()=>{}));return}let l=n.visibleViewMap||new Map,u=-1;(!a||a.root!==s)&&(a==null||a.disconnect(),l.clear(),a=new IntersectionObserver(h=>{h.forEach(_=>{l.set(_.target,_.isIntersecting),e.log.info(`view ${_.target.id} is${_.isIntersecting?"":" not"} visible`)}),clearTimeout(u),u=window.setTimeout(()=>{[...l.values()].find(g=>g)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:s}));let m=new Set(Fo(t));l.forEach((h,_)=>{m.has(_)||(a.unobserve(_),l.delete(_))}),m.forEach(h=>{l.set(h,!0),a.observe(h)}),a.takeRecords().forEach(h=>{l.set(h.target,h.isIntersecting)}),n.visibleViewMap=l,n.observer=a}_exitRoom(){return p(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()})}_stopScreenShare(){return p(this,null,function*(){var e;if(this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield Promise.all(t.map(r=>this._room.unpublish(r).catch(()=>{})))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(((e=this._localScreenAudioTrack.trackSettings)==null?void 0:e.echoCancellation)===!1&&this.stopPlugin("AudioProcessor"),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),Le(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_checkScreenAudioEchoCancellation(e,t){return p(this,null,function*(){var s,n;if(!e||!t)return;let r=(s=e.trackSettings)==null?void 0:s.displaySurface;if(((n=t.trackSettings)==null?void 0:n.echoCancellation)===!1&&(r==="monitor"||r==="browser"&&e.isShareCurrentTab)){this._log.warn("echoCancellation of screen audio track is disable. Try starting audioProcessor plugin");try{yield this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,isScreenAudioNeedAudioProcess:!0,isLocalAudioNeedAudioProcess:!1})}catch(a){this._log.warn("start audioProcessor plugin failed: ",a)}}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!ze||ls(ze))&&(this._initActiveSpeaker(),S.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return p(this,null,function*(){if(ze&&!ls(ze))this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:ze});else{let e=yield Nr();e[0]&&!ls(e[0])?(ze=e[0],this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):S.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let r=this._room.remotePublishedUserMap.get(e);if(r){let s=t==="main"?r.remoteVideoTrack:r.remoteAuxiliaryTrack,n=[s];this._room.autoReceiveAudio&&r.remoteAudioTrack.isAvailable&&n.push(r.remoteAudioTrack),this._room.subscribe(...n).then(()=>{this._emitTrackEvent(s)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:t}){t.hasAudio&&t.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:t}){this._stopRemoteVideo({userId:e,streamType:t},!1).catch(()=>{})}sendSEIMessage(e,t){var s;let r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:L(O({seiPayloadType:243},t),{small:!!((s=this._localVideoTrack)!=null&&s.small)})}),v.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,r;(r=(t=this._room).sendCustomMessage)==null||r.call(t,e),v.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,t){return p(this,null,function*(){return this._log.info(`callExperimentalAPI(${e}, ${JSON.stringify(t)})`),Qf.call(e,O({trtcInstance:this},t))})}static setLogLevel(e,t){R.setLogLevel(e),T(t)||(t?R.enableUploadLog():R.disableUploadLog())}static isSupported(){return _c(q.frameWorkType)}static getPermissions(r){return p(this,arguments,function*({request:e=!0,types:t=["camera","microphone"]}){e&&(yield Zn.request(t).catch(a=>{var c;return R.error(`getPermissions request failed, error: ${(c=a==null?void 0:a.message)!=null?c:a}`)}));let[s,n]=yield Promise.all([Zn.get("camera"),Zn.get("microphone")]);return{camera:s,microphone:n}})}static getCameraList(e=!0){return At(e)}static getMicrophoneList(e=!0){return It(e)}static getSpeakerList(e=!0){return Nr(e)}static setCurrentSpeaker(e){return p(this,null,function*(){if(_e&&(e===So.SPEAKER||e===So.HEADSET)){let r=yield q.getMicrophoneList(),s="";if(r.forEach(n=>{n.label===e&&(s=n.deviceId)}),!s)return;Kn.forEach(n=>p(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield Nr()).forEach(r=>{r.deviceId===e&&(Kn.forEach(s=>{s._setCurrentSpeaker(e),s.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:r})}),ze=r)})})}static _addKVStat({type:e,key:t,value:r,base:s,useUV:n,version:a,max:c}){switch(a&&(ro.version=a),e){case"count":ro.addCount({key:t,useUV:n});break;case"enum":ro.addEnum({key:t,value:r,useUV:n});break;case"number":ro.addNumber({key:t,value:r,split:s,max:c});break}}};d(q,"VERSION",wh),d(q,"_loggerManager",R),d(q,"EVENT",x),d(q,"ERROR_CODE",$),d(q,"TYPE",So),d(q,"frameWorkType",30),M([Ae({replaceArg:e=>({argIndex:0,value:{name:"plugin"in e?e.plugin.Name:e.Name,assetsPath:"assetsPath"in e?e==null?void 0:e.assetsPath:"default"}})})],q.prototype,"use",1),M([st(We.TRTC.enterRoom),wr("room",([e],[t])=>(e.roomId||e.strRoomId)===(t.roomId||t.strRoomId)&&e.userId===t.userId&&e.sdkAppId===t.sdkAppId),Q(e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)}),Ae()],q.prototype,"enterRoom",1),M([Ae()],q.prototype,"exitRoom",1),M([st(We.TRTC.switchRoom),Ae(),ir()],q.prototype,"switchRoom",1),M([st(We.TRTC.switchRole),Ao("room",{merge:(e,t)=>t}),Ae()],q.prototype,"switchRole",1),M([Ae()],q.prototype,"destroy",1),M([st(We.TRTC.startLocalAudio),wr("audio",([e],[t])=>{var r,s;return((r=e==null?void 0:e.option)==null?void 0:r.microphoneId)===((s=t==null?void 0:t.option)==null?void 0:s.microphoneId)}),Ae()],q.prototype,"startLocalAudio",1),M([st(We.TRTC.updateLocalAudio),Ao("audio",{debounce:{delay:200,getKey:()=>`${Zf}-localAudio`,isNeedToDebounce:e=>{var t;return!T((t=e.option)==null?void 0:t.captureVolume)}}}),Ae()],q.prototype,"updateLocalAudio",1),M([Lr("audio"),Ae()],q.prototype,"stopLocalAudio",1),M([st(We.TRTC.startLocalVideo),wr("video",([e],[t])=>{var r,s;return((r=e==null?void 0:e.option)==null?void 0:r.cameraId)===((s=t==null?void 0:t.option)==null?void 0:s.cameraId)}),Ae()],q.prototype,"startLocalVideo",1),M([st(We.TRTC.updateLocalVideo),Ao("video"),Ae()],q.prototype,"updateLocalVideo",1),M([Lr("video"),Ae()],q.prototype,"stopLocalVideo",1),M([st(We.TRTC.startScreenShare),wr("screen",()=>!0),Ae()],q.prototype,"startScreenShare",1),M([st(We.TRTC.updateScreenShare),Ao("screen"),Ae()],q.prototype,"updateScreenShare",1),M([Ae()],q.prototype,"stopScreenShare",1),M([st(We.TRTC.startRemoteVideo),wr(e=>`v${e.userId}${e.streamType}`,()=>!0),Ae({getRemoteId:e=>`${e.userId}_${e.streamType}`})],q.prototype,"startRemoteVideo",1),M([st(We.TRTC.updateRemoteVideo),Ao(e=>`v${e.userId}${e.streamType}`),Ae({getRemoteId:e=>`${e.userId}_${e.streamType}`})],q.prototype,"updateRemoteVideo",1),M([st(We.TRTC.stopRemoteVideo),Q(e=>function(t){return p(this,null,function*(){if(t.userId==="*"){let r=[];return this._room.remotePublishedUserMap.forEach(s=>{this._remoteVideoConfigMap.has(`${s.userId}_main`)&&r.push(this.stopRemoteVideo({streamType:"main",userId:s.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${s.userId}_sub`)&&r.push(this.stopRemoteVideo({streamType:"sub",userId:s.userId}).catch(()=>{}))}),Promise.all(r)}return e.call(this,t)})}),Ae({getRemoteId:e=>`${e.userId}_${e.streamType}`})],q.prototype,"stopRemoteVideo",1),M([Lr(e=>`v${e.userId}${e.streamType}`)],q.prototype,"_stopRemoteVideo",1),M([st(...We.TRTC.muteRemoteAudio),Ae({getRemoteId:e=>e})],q.prototype,"muteRemoteAudio",1),M([Lh(...We.TRTC.setRemoteAudioVolume),Wf(200,e=>e),Ae({getRemoteId:e=>e})],q.prototype,"setRemoteAudioVolume",1),M([pd("start"),Ct(e=>{var t;return(t=e.afterStart)==null?void 0:t.call(e)}),wr((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),Ae({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Kl[e.getName()],ignoreLog:e=>e.getName()==="Debug",ignoreErrorLog:e=>e.getName()==="AudioProcessor"})],q.prototype,"startPlugin",1),M([pd("update"),Ao((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t),{merge:(e,t)=>(ei(e[1],t[1]),e)}),Ae({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>eu[e.getName()]})],q.prototype,"updatePlugin",1),M([pd("stop"),Lr((e,t)=>{if(e.disableRandomCall)return null;let r=e.getGroup(t),s=e.getAlias();return r==="*"?new RegExp(`${s}.*`):s+r}),Ae({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>tu[e.getName()]})],q.prototype,"stopPlugin",1),M([Lh(...We.TRTC.enableAudioVolumeEvaluation)],q.prototype,"enableAudioVolumeEvaluation",1),M([Ae()],q.prototype,"getVideoSnapshot",1),M([Ae()],q.prototype,"_setCurrentSpeaker",1),M([wr(e=>`a${e.userId}`,()=>!0)],q.prototype,"_startRemoteAudio",1),M([Q(e=>function(t){return p(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(r=>this._stopRemoteAudio(L(O({},t),{userId:r.userId})).catch(()=>{}))):e.call(this,t)})}),Lr(e=>`a${e.userId}`)],q.prototype,"_stopRemoteAudio",1),M([Lr("room")],q.prototype,"_exitRoom",1),M([Lr("screen")],q.prototype,"_stopScreenShare",1),M([st(...We.TRTC.sendSEIMessage),Ch({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],q.prototype,"sendSEIMessage",1),M([st(We.TRTC.sendCustomMessage),Ch({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],q.prototype,"sendCustomMessage",1),M([xr()],q,"create",1),M([st(We.TRTC.create)],q,"_create",1),M([xr()],q,"setLogLevel",1),M([xr()],q,"isSupported",1),M([xr()],q,"getPermissions",1),M([xr()],q,"getCameraList",1),M([xr()],q,"getMicrophoneList",1),M([xr()],q,"getSpeakerList",1);var qh=q,ea=qh;var Jh=class{constructor(){d(this,"_set",new Set);S.on(C.LEAVE_SUCCESS,this.delete,this),S.on(C.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,r){return`${t}_${e}_${i}_${r}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:r}){return r.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,r.useStringRoomId))}handleSwitchRoomSuccess({room:i,currentRoomId:e,targetRoomId:t}){i.scene!=="rtc"&&(this._set.delete(this.getKey(i.userId,e,i.sdkAppId,i.useStringRoomId)),this._set.add(this.getKey(i.userId,t,i.sdkAppId,i.useStringRoomId)))}};function KS(){return p(this,null,function*(){let o,i;try{let _=yield It();o=_&&_.length}catch(_){}try{let _=yield At();i=_&&_.length}catch(_){}let e={microphone:o,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:r,isH264DecodeSupported:s,isVp8DecodeSupported:n,isH265EncodeSupported:a,isH265DecodeSupported:c}=this.checkSystemResult.detail,l=bi.basis(),u={webRTC:l.isWebRTCSupported,getUserMedia:l.isGetUserMediaSupported,webSocket:l.isWebSocketsSupported,screenShare:l.isScreenShareSupported,webAudio:l.isWebAudioSupported,h264Encode:t,h264Decode:s,vp8Encode:r,vp8Decode:n,h265Encode:a,h265Decode:c},m={browser:l.browser,os:l.os,trtc:u,devices:e},h={isWebCodecSupported:l.isWebCodecSupported,isMediaSessionSupported:l.isMediaSessionSupported,isWebTransportSupported:l.isWebTransportSupported};se.uploadEvent({log:`trtcstats-${JSON.stringify(m)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(m)}`),se.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(h)}`,userId:this.userId}),mu()})}function e_(){return Q(o=>{let i=new Jh;return function(e,t,r){return p(this,null,function*(){let s=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=t,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new D({code:I.INVALID_OPERATION,message:H({key:F.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new D({code:I.INVALID_OPERATION,message:H({key:F.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:s}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${s} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),S.emit(C.JOIN_START,{room:this,roomId:s,params:e});let n=vt.getEnv();n||(n=Bi.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(ga.OLD_CLOUD_LADDER)?n=Bi.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(ga.WEBRTC)&&(n=Bi.WEBRTC))),se.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),bi.checkSystemRequirementsInternal(r).then(a=>{this.checkSystemResult=a,KS.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!vt.getEnv()&&(yield this.schedule(e,r));let a=yield o.call(this,e,t,r);return this.roomId=s,this._joinedTimestamp=vt.performanceNow(),S.emit(C.JOIN_SUCCESS,{room:this}),r===30&&!e.component&&se.uploadEvent({log:`stat-conv-${Number(oi)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw i.delete({room:this,roomId:s}),S.emit(C.JOIN_FAILED,{room:this,error:a}),a}})}})}var t_=()=>Q(o=>function(...i){return p(this,null,function*(){S.emit(C.LEAVE_START,{room:this}),yield o.call(this,...i),S.emit(C.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function i_(){return Q(o=>function(...i){let e=o.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var o_=Ge(at());var Se={SETUP_SUCCESS:"1",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4",SETUP_FAILED:"5",DISCONNECTED:"6",CLOSE:"7",ONLINE:"8"};var qt={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140,FALLBACK_CODEC:66,SEND_SWITCH_ROOM_RES:4160,SEND_SWITCH_ROOM_SUBED_REQ:4161,UPDATE_NETWORK_TIME_RESULT:5001,CUSTOM_CMD_RES:8220},r_=[qt.UPDATE_REMOTE_MUTE_STAT,qt.UPLINK_NETWORK_STATS,qt.USER_LIST_RES,qt.MUTE_RESULT,qt.SERVER_FIRST_PACKAGE_RECEIVED,qt.RECEIVE_CUSTOM_MSG,qt.UPDATE_NETWORK_TIME_RESULT],G={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",START_PUBLISH_CDN_STREAM_RES:"start-publish-cdn-stream-res",UPDATE_PUBLISH_CDN_STREAM_RES:"update-publish-cdn-stream-res",STOP_PUBLISH_CDN_STREAM_RES:"stop-publish-cdn-stream-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg",FALLBACK_CODEC:"fallback-codec",SEND_SWITCH_ROOM_RES:"send-switch-room-res",SEND_SWITCH_ROOM_SUBED_REQ:"send-switch-room-subed-res",UPDATE_NETWORK_TIME_RESULT:"update_network_time_result",CUSTOM_CMD_RES:"custom-cmd-res"},Y={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",START_PUBLISH_CDN_STREAM:"start_publish_cdn_stream",UPDATE_PUBLISH_CDN_STREAM:"update_publish_cdn_stream",STOP_PUBLISH_CDN_STREAM:"stop_publish_cdn_stream",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3",ABILITY_STATUS_REPORT:"ability_status_report",RECONNECT_WS:"reconnect",SEND_CUSTOM_MSG:"channel_msg",SWITCH_ROOM:"switch_room",UPDATE_NETWORK_TIME:"update_network_time",CUSTOM_CMD:"abstract_cmd"};var bd=new Set;function s_(o){let i=[...bd.values()].find(e=>e.room.userId===o&&!e.room.isJoined);return i||null}var tI=["autoTest","relayInnerIp","relayOuterIp","mcd","newRelay","clientIp"],bs=class extends o_.default{constructor(e){var r,s,n;super();d(this,"room");d(this,"sdkAppId");d(this,"userId");d(this,"userSig");d(this,"url");d(this,"backupUrl");d(this,"destroyed",!1);d(this,"_socketInUse");d(this,"_socket");d(this,"_backupSocket");d(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[],reportToken:void 0});d(this,"_currentState","DISCONNECTED");d(this,"_isReconnecting",!1);d(this,"_seq",0);d(this,"_log");d(this,"_lastMessageTime",-1);d(this,"_connectStartTime",-1);d(this,"_stopConnectRetry");d(this,"_isFirstConnect",!0);d(this,"bytesSent",0);d(this,"bytesReceived",0);d(this,"keepAlive",!1);d(this,"signalDomainWhenUnifiedProxy");d(this,"stopKeepAliveTimeout");d(this,"rtt",0);this.room=e.room,this.sdkAppId=e.sdkAppId,this.userId=e.userId,this.userSig=e.userSig,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy;let t=((s=(r=this.room.scheduleResult)==null?void 0:r.config)==null?void 0:s.keepAliveClient)||0;(n=this.room.joinParams)!=null&&n.keepAlive&&!t&&(t=1),t-bd.size>0&&this.room.enableSPC&&(this.keepAlive=!0,bd.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=R.createLogger({parent:this.room.getLogger(),id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get race(){return this.room.enableSPC&&!this.room.proxy_ws}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`);let t=new URLSearchParams(location.search);return tI.forEach(r=>{let s=t.get(`trtc_${r}`);s&&(e+=`&${r}=${encodeURIComponent(s)}`)}),this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return p(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}] ${this.race?"race":""}${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connectStartTime=U();let t=[this.connectWS({url:this._urlWithParam,isMain:!0,timeout:e})];this.race&&this._backupUrlWithParam!==this._urlWithParam&&t.push(this.connectWS({url:this._backupUrlWithParam,isMain:!1,timeout:e})),this._socketInUse=yield Xr(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?f.BACKUP:f.MAIN),this._isFirstConnect&&(v.addSuccessEvent({key:521720}),this._isFirstConnect=!1),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:r}){let s=new WebSocket(e);this.bindSocket(s),r?this._socket=s:this._backupSocket=s;let n=-1;return new Promise((a,c)=>{s.onclose=c,s.onerror=c,s.onopen=()=>a(s),t&&(n=setTimeout(()=>{this.unbindAndCloseSocket(r?f.MAIN:f.BACKUP),c(new D({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{s.onclose=null,s.onerror=null,s.onopen=null,clearTimeout(n)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===f.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}onclose(e){e.target===this._socketInUse&&(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),(!e.wasClean||e.code!==1e3)&&this.startReconnection(),this.room.isJoining&&this.emit(Se.SETUP_FAILED,new D({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(f.MAIN),this.unbindAndCloseSocket(f.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(Se.SETUP_FAILED,new D({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;let{isOnline:t}=this;this._lastMessageTime=Date.now(),t||this.emit(Se.ONLINE),this.bytesReceived+=qs(e.data);let r=JSON.parse(e.data),{cmd:s,data:n}=r,a=Object.values(qt),l=Object.keys(qt)[a.indexOf(s)],u=G[l]||s;switch(r_.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),u&&this._log.info(`Received event: [ ${u} ]`)),s){case qt.CHANNEL_SETUP_RESULT:{if(r.code===0)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,n.svrTime&&da(n.svrTime-new Date().getTime()),this._log.info(`ChannelSetup Success ${U()-this._connectStartTime}`),v.addSuccessEvent({key:521701,cost:U()-this._connectStartTime}),this._connectStartTime=-1,this.emit(Se.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let m=new D({code:I.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:r.code,message:H({key:F.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:r.code,errorMsg:r.message}})});this._log.error(`${r.code}, ${r.message}`),this.close(),v.addFailedEvent({key:521701,error:m}),this.emit(Se.SETUP_FAILED,m)}break}case qt.JOIN_ROOM_RESULT:{r.code===0&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.bakRelayIps=n.bakRelayIps,this._signalInfo.relayPort=n.relayPort,this._signalInfo.tinyId=r.tinyId,this._signalInfo.endReportExtend=n.endReportExtend,this._signalInfo.reportToken=n.reportToken,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(u,{data:r});break}default:this.emit(String(u),{data:r});break}}reGetSignalChannelUrl(){return p(this,null,function*(){try{if(!this.room.joinParams)return;Lt(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?f.MAIN:f.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return p(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive){this.close();return}this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:r,relayInnerIp:s,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:Y.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:s,relayOuterIp:r,relayPort:n},responseCommand:G.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),v.addSuccessEvent({key:521702,cost:U()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(v.addFailedEvent({key:521702,error:a.code}),this._log.warn(`reconnect failed, ${a.code} ${a.message}`),this.room.reJoin())}catch(e){this._log.error(e),this.room.reJoin()}}})}send(e,t={}){if(this.isConnected&&!this.room.isLeft){let r={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},s=JSON.stringify(r);return this._socketInUse.send(s),this.bytesSent+=qs(s),r.seq}}sendWaitForResponse({command:e,data:t,timeout:r=5e3,responseCommand:s,commandDesc:n,enableLog:a=!0,addReceiveTime:c=!1}){return new Promise((l,u)=>{let m=()=>{clearTimeout(h),u(new D({code:I.API_CALL_ABORTED,message:`${e} aborted due to connection closed`}))};this.once(Se.CLOSE,m);let h=setTimeout(()=>{this.off(s,_),this.off(Se.CLOSE,m);let E=new D({code:I.API_CALL_TIMEOUT,message:H({key:F.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(E),u(E)},r),_=E=>{E.data.seq===g&&(clearTimeout(h),this.off(s,_),this.off(Se.CLOSE,m),c&&(E.data.receiveTime=Date.now()),l(E))};this.on(s,_);let g=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:r,retries:s=0,retryTimeout:n=0}=e;return Ai({retryFunction:this.sendWaitForResponse,onError:({retry:a,reject:c,error:l})=>{!this.room.isJoined||this.destroyed||l.code===I.API_CALL_ABORTED?c(l):this.isOnline?a():(this._log.warn(`retry ${r} when connected`),this.once(Se.ONLINE,a))},onRetrying:a=>{this._log.warn(`${t||r} timeout observed, retrying [${a}/${s}]`)},settings:{retries:s,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),bd.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,bakRelayIps:[],endReportExtend:void 0,reportToken:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(f.MAIN),this.unbindAndCloseSocket(f.BACKUP),this.emitConnectionStateChanged("DISCONNECTED"),this.emit(Se.CLOSE)}destroy(){this.close(),this.destroyed=!0}getBackupRelayIpPair(){var t;let e=(t=this._signalInfo.bakRelayIps)==null?void 0:t.shift();return e&&(e.relayPort=e.relayPort||this._signalInfo.relayPort),e}clearBakRelayIps(){this._signalInfo.bakRelayIps=[]}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(G.JOIN_ROOM_RESULT,t)},e*1e3);let t=r=>{r.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(G.JOIN_ROOM_RESULT,t))};this.on(G.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(Se.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(Se.CONNECTED):e==="DISCONNECTED"&&this.emit(Se.DISCONNECTED))}};M([Mt({settings:{retries:1/0,timeout:2e3},onError(e,t){!this.room.isDestroyed&&!this.destroyed&&(this._isFirstConnect&&(v.addFailedEvent({key:521720,error:e}),this._isFirstConnect=!1),t())},onRetrying(e,t){this._log.warn(`retrying to connect ${e}`),e>=3&&e%3===0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,(this.room.isDestroyed||this.destroyed)&&t())}})],bs.prototype,"connect",1);var n_=Ge(at());var jh=0,Xh=!1,vd=new Set,iI=o=>jh>2&&!Xh&&vd.size===0&&o,zh=!1,pt=class{constructor(i){d(this,"userId");d(this,"tinyId");d(this,"_sdpSemantics");d(this,"_isUplink");d(this,"_room");d(this,"_log");d(this,"_signalChannel");d(this,"_isErrorObserved",!1);d(this,"_waitForPeerConnectionConnectedPromise");d(this,"_waitForPeerConnectionConnectedPromiseReject",null);d(this,"_peerConnection",null);d(this,"_emitter",new n_.default);d(this,"_currentState","DISCONNECTED");d(this,"_isReconnecting",!1);d(this,"_reconnectionCount",0);d(this,"_reconnectionTimer",-1);d(this,"_isFirstConnection",!0);d(this,"_prevTime",-1);d(this,"_localAddress");d(this,"_remoteAddress");this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=i.room.getLogger().createChild({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=U())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,v.addSuccessEvent({key:521705,cost:Math.min(U()-this._prevTime,30*1e3)})):this._isReconnecting&&v.addSuccessEvent({key:521706,cost:U()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,v.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&v.addFailedEvent({key:521706,error:i}),i}}initialize(){let i={iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(i),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(i){this._log.info("close connection"),this._emitter.emit("closed",i),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),vd.delete(this)}closePeerConnection(i=!1){this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,i&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new D({code:I.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return Qt;let i=null;if(this._isUplink){if(!Rr()||this._peerConnection.getSenders().length===0)return Qt;i=this._peerConnection.getSenders()[0].transport}else{if(!oo()||this._peerConnection.getReceivers().length===0)return Qt;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:Qt}onConnectionStateChange(i){let e=this._peerConnection.iceConnectionState,t=this.getDTLSTransportState();if(this._log.info(`connectionState: ${i.target.connectionState}, ICE: ${e}, DTLS: ${t}`),i.target.connectionState===Ce.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===Ce.FAILED||i.target.connectionState===Ce.CLOSED){let r=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,s=new D({message:r,code:I.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",s)}(i.target.connectionState===Ce.CONNECTED||i.target.connectionState===Ce.COMPLETED)&&(this.logSelectedCandidate(),se.logSuccessEvent({userId:this._room.userId,eventType:Ze.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(jh=0,Xh=!1,zh=!0,vd.add(this)):vd.delete(this),S.emit(C.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:i,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:i}),this._currentState=i,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return p(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(Cr(e)){let t=i.get(e.localCandidateId),r=i.get(e.remoteCandidateId);t&&(this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.candidateType==="relay"?`relayProtocol:${t.relayProtocol}`:""}`),this._localAddress=`${t.ip||t.address}:${t.port}`),r&&(this._log.info(`remote candidate: ${r.candidateType} ${r.protocol}:${r.ip||r.address}:${r.port}`),this._remoteAddress=`${r.protocol}:${r.ip||r.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(n),s(),i())},r=({room:a})=>{a===this._room&&(clearTimeout(n),s(),e(new D({code:I.API_CALL_ABORTED,message:H({key:F.CONNECTION_ABORTED,data:"leave room"})})))},s=()=>{S.off(C.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{s();let a=new D({code:I.API_CALL_TIMEOUT,message:"connection timeout"});jh+=1,iI(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Xh=!0,this._emitter.emit("firewall-restriction")),e(a)},Bs);S.on(C.LEAVE_SUCCESS,r,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(Se.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Hi()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new D({code:this._isUplink?I.UPLINK_RECONNECTION_FAILED:I.DOWNLINK_RECONNECTION_FAILED,message:H({key:this._isUplink?F.UPLINK_RECONNECTION_FAILED:F.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",i),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn(`reconnect() trying [${this._reconnectionCount}]`),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(Se.CONNECTED,this.reconnect,this),-1)}on(i,e,t){this._emitter.on(i,e,t)}off(i,e,t){this._emitter.off(i,e,t)}getIsReconnecting(){return this._isReconnecting}get isH264(){var i,e;return!!((e=(i=this._peerConnection)==null?void 0:i.remoteDescription)!=null&&e.sdp.includes("H264"))}setOffer(i){var e;return(e=this._peerConnection)==null?void 0:e.setLocalDescription(i)}setAnswer(i){var e;return(e=this._peerConnection)==null?void 0:e.setRemoteDescription(i)}};M([Rt(521712,!1)],pt.prototype,"setOffer",1),M([Rt(521713,!1)],pt.prototype,"setAnswer",1);var Kh=Ge(Zh());var De=function(o){return Kh.default.parse(o)},Jt=function(o){return Kh.default.write(o)},p_=function(o){let i=De(o);return i.media.forEach(e=>{e.type===f.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),Jt(i)};function f_(o){let i=De(o);return i.media.forEach(e=>{var t,r;if(e.type===f.VIDEO){let s=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&s.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let l=c.match(/apt=(\d+)/);l&&l[1]&&s.has(Number(l[1]))&&s.add(a)});let n=({payload:a})=>!s.has(a);e.rtp=e.rtp.filter(n),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=(r=e.payloads)==null?void 0:r.split(" ").filter(a=>!s.has(Number(a))).join(" ")}}),Jt(i)}function Nd(o){return Object.keys(o).filter(i=>o[i])}var Ns=class Ns extends pt{constructor(e){super(L(O({},e),{isUplink:!1}));d(this,"_flag",0);d(this,"isRobot",!1);d(this,"role","anchor");d(this,"remoteAudioTrack");d(this,"remoteVideoTrack");d(this,"remoteAuxiliaryTrack");d(this,"ssrc",{audio:0,video:0,auxiliary:0});d(this,"_isSDPExchanging",!1);d(this,"_videoCodec");this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new gi(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new Oi(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Es(this._room,this)}get videoCodec(){var t,r;let e=(r=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:r.sdp;return e?e.includes("H264")?"h264":"vp8":this._videoCodec||"h264"}set videoCodec(e){this._videoCodec=e}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return Kt(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,s;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(s=this.remoteAuxiliaryTrack)==null||s.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===f.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var s,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((s=this.remoteVideoTrack)==null||s.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){let t=e.streams[0],{track:r}=e,s=t.id===Fs?f.MAIN:f.AUXILIARY;this._log.debug(`ontrack ${s} ${r.kind}`);let n=f.AUDIO;r.kind===f.VIDEO&&(n=s===f.MAIN?f.VIDEO:f.AUXILIARY);let a=this.remoteAudioTrack;n===f.VIDEO?a=this.remoteVideoTrack:n===f.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(r)}addRRTRLine(e){let t=e.split(`\r
|
|
68
|
+
2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},'"displaySurface":"window"':{tips:"Screen sharing captures the application window",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"monitor"':{tips:"Screen sharing captures the entire screen",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"browser"':{tips:"Screen sharing captures a certain tab page",color:"blue",class:"blue",textColor:"#fff"},updateMediaSettings:{tips:"The resolution and frame rate below are the actual resolution and frame rate captured",color:"blue",class:"blue",textColor:"#fff"},"main stream start to play with":{tips:"Call remoteStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"stream start to play with":{tips:"Call localStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"main setAudioVolume to 0":{tips:"Business side calls remoteStream.setAudioVolume(0) interface to set the playback volume to 0, which will cause the playback to be silent",color:"orange",class:"orange",textColor:"#fff"},"screen sharing was stopped because the video track is ended":{tips:"Screen sharing capture stopped, possible reasons: user clicks the stop button, the window/page shared by the user is closed, etc.",color:"orange",class:"orange",textColor:"#fff"},"Join() => joining room":{tips:"Call client.join interface",color:"blue",class:"blue",textColor:"#fff"},"publish() => publishing local stream":{tips:"Call client.publish interface",color:"blue",class:"blue",textColor:"#fff"},"subscribe() => subscribe to":{tips:"Call client.subscribe interface",color:"blue",class:"blue",textColor:"#fff"},"switchRole() => switch role":{tips:"Call client.switchRole interface",color:"blue",class:"blue",textColor:"#fff"}};["enterRoom","exitRoom","switchRole","destroy","startLocalAudio","updateLocalAudio","stopLocalAudio","startLocalVideo","updateLocalVideo","stopLocalVideo","startScreenShare","updateScreenShare","stopScreenShare","startRemoteVideo","updateRemoteVideo","stopRemoteVideo","muteRemoteAudio","setRemoteAudioVolume"].forEach(o=>{Xf[`${o}()`]={tips:`Call trtc.${o}`,color:"blue",class:"blue",textColor:"#fff"}});var Gx=Object.keys(Xf);var YS=0,Ad,zn=class zn{constructor(i){this.core=i;d(this,"_core");d(this,"log");d(this,"dumpLocalVideoMap",{});d(this,"dumpRemoteVideoMap",{});d(this,"dialog");this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${++YS}`}),this.log.info("created")}getName(){return zn.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(i){switch(i){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return p(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog(),this.addVideoProcessor())})}update(e){return p(this,arguments,function*({visible:i}){i?(yield this.openDebugDiaLog(),this.addVideoProcessor()):(this.closeDebugDiaLog(),this.removeVideoProcessor())})}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return p(this,null,function*(){var i;if(!this.dialog)try{if(Ad)yield Ad;else{let e=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((i=window.sessionStorage)==null?void 0:i.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${qf}@${He}/assets/debug-dialog.js`;Ad=this._core.fileDownloader.loadScript(e),yield Ad}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(e){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(e))}})}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):$h,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):Wh,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo({frame:i,mediaType:e}){return $h({frame:i,onDump:()=>{if(!e)return;let t=e===2?"sub":"main",r=this.dumpLocalVideoMap[t];r&&(r.data.push(i.data.slice(0)),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}})}decodeVideo({frame:i,track:e}){return Wh({frame:i,onDump:()=>{if(!e)return;let t=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];t&&(t.data.push(i.data.slice(0)),t.duration>0&&Date.now()-t.startTimestamp>t.duration*1e3&&t.onDumpEnd())}})}};d(zn,"Name","Debug"),d(zn,"autoStart",!0);var Cd=zn;var zf=o=>{switch(o){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},Rd=class{constructor(i,e,t){d(this,"trackDoneOB");d(this,"startOB");d(this,"stopOB");d(this,"inputFrameCount",0);d(this,"decodedFrameCount",0);d(this,"type","auto");d(this,"config");d(this,"decoder");d(this,"_decodeSink");let{kvStatManager:r,trtc:s}=i;this.config=t.config,this.trackDoneOB=ce(e,J.INIT),this.stopOB=ot(),this.startOB=ot(),t.type==="auto"?this.type="webCodecs":this.type=t.type;let n=ot(),a=c=>{let l=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),de(l,ke(this.stopOB),Te(()=>{},u=>{e.log.error(u),r.addFailedEvent({key:zf(this.type),error:u}),c>4?this.startOB.error(u):this.startOB.next(c+1)})),de(l,or(1),ph(Vn))};de(this.startOB,xn(0),Mr(a),ke(this.stopOB),Te(()=>{e.player.setOutput(),n.next("STARTED")},c=>{n.next("FAILED")},()=>{r.addSuccessEvent({key:zf(this.type)}),r.addSuccessEvent({key:504702})}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.startOB.next(0)}close(i){this.stopOB.next(i)}pipe(i){return rr()(e=>p(this,null,function*(){this._decodeSink=e,e.defer(()=>{var r;(r=this.decoder)==null||r.close()});let{type:t}=this;try{switch(t){case"webCodecs":this.decoder=new AudioDecoder({error:r=>{i.log.error(r),e.error(4)},output:r=>{this.decodedFrameCount++,e.next(r),i.player.write(r)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(r){i.log.error(r),e.error(t==="webCodecs"?2:6)}}))}decodeFrame(i){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:i.data,timestamp:i.timestamp,type:"key"}))}},ZS={type:"object"},Qn=class Qn{constructor(i){this.core=i;d(this,"log");d(this,"contextMap",new Map);d(this,"decodeProcessorMap",new WeakMap);this.log=i.log.createChild({id:`${this.getAlias()}`})}getAlias(){return Qn.Name}getGroup(i){return i.track.userId+i.track.streamType}getName(){return Qn.Name}getValidateRule(i){return ZS}start(i){let{track:e}=i;this.decodeProcessorMap.set(e,this.decode(i)),this.core.room.audioManager.addDecodeProcessor({processor:({frame:t,track:r})=>this.decodeProcessorMap.has(r)?this.decodeProcessorMap.get(r)({frame:t,track:r}):t,type:3})}decode(i){return({frame:e,track:t})=>{if(t!==i.track)return e;if(this.contextMap.has(t))return this.contextMap.get(t).decodeFrame(e);let r=new Rd(this.core,t,i);return de(r.trackDoneOB,or(1),Te(()=>{this.core.clearStarted(this,this.getGroup(i)),this.stop({track:t})})),this.contextMap.set(t,r),r.decodeFrame(e)}}stop({track:i}){let e=this.contextMap.get(i);e&&(e.close("stop"),this.contextMap.delete(i),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(i){let e=this.contextMap.get(i.track);if(e){if(i.type==="mock"){e.mock(10);return}e.close("update"),this.contextMap.set(i.track,new Rd(this.core,i.track,i))}}};d(Qn,"Name","TRTCAudioDecoder");var Yn=Qn;var yd=class{constructor(){d(this,"log");this.log=R.createLogger({id:"exp"})}call(i,e){return p(this,null,function*(){return le(this[i])?this[i](e):Promise.reject(new D({code:I.INVALID_PARAMETER,message:H({key:F.API_NOT_EXIST,data:{name:i}})}))})}enableAudioFrameEvent(i){return p(this,null,function*(){let{trtcInstance:e,enable:t,userId:r,sampleRate:s=48e3,channelCount:n=1,port:a}=i,{audioManager:c}=e.room,{getPCMAbortCtrlMap:l,audioFrameEventConfigMap:u}=c;if(u.set(r,{enable:t,sampleRate:s,channelCount:n,port:a}),t)if(r==="*")e.room.remotePublishedUserMap.forEach(m=>{if(m.remoteAudioTrack.isAvailable){if(l.get(m.userId))return;let h=c.getPCM(_=>{e.emit(x.AUDIO_FRAME,_)},m.userId);l.set(m.userId,h)}});else{if(l.get(r))return;let m=c.getPCM(h=>{e.emit(x.AUDIO_FRAME,h)},r);l.set(r,m)}else if(r==="*")e.room.remotePublishedUserMap.forEach(m=>{if(m.remoteAudioTrack.isSubscribed){let{userId:h}=m,_=l.get(h);_==null||_.abort("disable"),l.delete(h)}});else{let m=l.get(r);m==null||m.abort("disable"),l.delete(r)}})}resumeRemotePlayer(i){return p(this,null,function*(){if(i.userId==="*"){let t=[];return i.trtcInstance.room.remotePublishedUserMap.forEach(r=>{let{remoteAudioTrack:s,remoteVideoTrack:n,remoteAuxiliaryTrack:a}=r;i.streamType?i.streamType==="main"?(s.isAvailable&&t.push(s.player.resume()),n.isAvailable&&t.push(n.player.resume())):a.isAvailable&&t.push(a.player.resume()):(s.isAvailable&&t.push(s.player.resume()),n.isAvailable&&t.push(n.player.resume()),a.isAvailable&&t.push(a.player.resume()))}),Promise.all(t)}let e=i.trtcInstance.room.remotePublishedUserMap.get(i.userId);if(e)return i.streamType==="main"?Promise.all([e.remoteAudioTrack.player.resume(),e.remoteVideoTrack.player.resume()]):e.remoteAuxiliaryTrack.player.resume()})}pauseRemotePlayer(i){if(i.userId==="*")i.trtcInstance.room.remotePublishedUserMap.forEach(e=>{let{remoteAudioTrack:t,remoteVideoTrack:r,remoteAuxiliaryTrack:s}=e;i.streamType?i.streamType==="main"?(t.isAvailable&&t.player.pause(),r.isAvailable&&r.player.pause(!1)):s.isAvailable&&s.player.pause(!1):(t.isAvailable&&t.player.pause(),r.isAvailable&&r.player.pause(!1),s.isAvailable&&s.player.pause(!1))});else{let e=i.trtcInstance.room.remotePublishedUserMap.get(i.userId);e&&(i.streamType==="main"?(e.remoteAudioTrack.player.pause(),e.remoteVideoTrack.player.pause(!1)):e.remoteAuxiliaryTrack.player.pause(!1))}}};M([Sf({name:"options",type:"object",required:!0,properties:{enable:{required:!0,type:"boolean"},userId:{required:!0,type:"string"},sampleRate:{type:"number",values:[8e3,16e3,32e3,44100,48e3]},channelCount:{type:"number",values:[1,2]},port:{type:"messageport"}}})],yd.prototype,"enableAudioFrameEvent",1);var Qf=new yd;var Yf=Ge(at(),1);var Gh=class extends Yf.EventEmitter{constructor(){super();d(this,"states",{});d(this,"permissionChangeHandler");d(this,"log");this.log=R.createLogger({id:"pm"}),this.permissionChangeHandler=()=>{var e,t;this.emit("permission-state-change",{camera:(e=this.states.camera)==null?void 0:e.state,microphone:(t=this.states.microphone)==null?void 0:t.state})}}request(e){return p(this,null,function*(){if(this.log.info(`request ${e.join(", ")}`),e.length===0)return Promise.resolve();(yield navigator.mediaDevices.getUserMedia({video:e.includes("camera"),audio:e.includes("microphone")})).getTracks().forEach(r=>r.stop())})}get(e){return p(this,null,function*(){try{return this.states[e]||(this.states[e]=yield navigator.permissions.query({name:e}),this.states[e].addEventListener("change",this.permissionChangeHandler)),this.log.info(`get ${e} permission state: ${this.states[e].state}`),this.states[e].state}catch(t){return this.log.error(`get ${e} permission failed, error: ${t instanceof Error?t.message:t}`),null}})}destroy(){Object.values(this.states).forEach(e=>{e==null||e.removeEventListener("change",this.permissionChangeHandler)}),this.states={}}},Zn=new Gh;var Zf=0,Kn=new Set,ze=null;qd(wh);es.checkStorage();var q=class q extends Kf.EventEmitter{constructor(e,t){super();d(this,"_room");d(this,"_eventListened",new Set);d(this,"_localVideoTrack",null);d(this,"_localAudioTrack",null);d(this,"_localScreenTrack",null);d(this,"_localScreenAudioTrack",null);d(this,"_localVideoConfig",null);d(this,"_localScreenConfig",null);d(this,"_localAudioConfig",null);d(this,"_remoteVideoConfigMap",new Map);d(this,"_remoteAudioConfigMap",new Map);d(this,"_remoteAudioVolumeMap",new Map);d(this,"_remoteAudioMuteMap",new Map);d(this,"_mediaTrackMap",new WeakMap);d(this,"_log",R.createLogger({id:`t${++Zf}`}));d(this,"_plugins",new Map);d(this,"_networkQuality",null);d(this,"_speakerId");d(this,"enterRoomParams");d(this,"_enableAutoSwitchWhenRecapturing",!0);this._room=new e(O({logger:this._log,frameWorkType:q.frameWorkType},t)),this._room.videoDecodeFallbackType=t.videoDecodeFallback,he(t.enableAutoSwitchWhenRecapturing)&&(this._enableAutoSwitchWhenRecapturing=t.enableAutoSwitchWhenRecapturing),this._log.info(`create() ${JSON.stringify(t,(r,s)=>r==="plugins"?s.map(n=>n.Name):s)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(r){return this._room.audioManager.dump(r)}}}),t.plugins&&t.plugins.forEach(r=>{this._use(r,t.assetsPath)}),this._use(Td,t.assetsPath),this._use(_d,t.assetsPath),this._use(Sd,t.assetsPath),this._use(Yn,t.assetsPath),this._use(Cd),t.enableSEI&&En&&this._use(Id),this._room.on("audio-volume",r=>{var s,n;!r.find(a=>a.userId==="")&&this._localAudioTrack&&r.push({userId:"",volume:Math.floor(((s=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?s:this._localAudioTrack.getAudioLevel())*100),floatVolume:(n=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?n:this._localAudioTrack.getInternalAudioLevel()}),t.volumeType===1&&r.forEach(a=>{var l;let c=a.userId===""?this._localAudioTrack:(l=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:l.remoteAudioTrack;c&&(a.volume=c.dbVolume)}),t.enableDbVolume&&r.forEach(a=>{var l;let c=a.userId===""?this._localAudioTrack:(l=this.room.remotePublishedUserMap.get(a.userId))==null?void 0:l.remoteAudioTrack;c&&(a.volume=c.dbVolume)}),this.emit(x.AUDIO_VOLUME,{result:r.sort((a,c)=>c.volume-a.volume)})}),this._room.videoManager.on("error",r=>{this._log.error(new V({code:$.OPERATION_FAILED,extraCode:5504,message:r.message,originError:r}))}),this._listenEvents(),this._initActiveSpeaker(),Hf(this,"trtc")}static create(e){}static _create(e,t){Cf();let r=new q(e,t||{});return Kn.add(r),r.__v_skip=!0,r}get room(){return this._room}_listenEvents(){tt(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(x.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit(x.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{Lt(!0),this._exitRoom().finally(()=>{this.emit(x.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(x.ERROR,V.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(x.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let t=L(O({},e),{uplinkRTT:Math.min(e.uplinkRTT,$s),downlinkRTT:Math.min(e.downlinkRTT,$s)});this.emit(x.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{tt(r,r).add("player-state-changed",s=>{let n=L(O({},s),{userId:e.userId});r.kind===f.VIDEO&&(n.streamType=ki(r.streamType)),this.emit(r.kind===f.AUDIO?x.AUDIO_PLAY_STATE_CHANGED:x.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",s=>{s.getCode()===I.PLAY_NOT_ALLOWED&&this.emit(x.AUTOPLAY_FAILED,{userId:r.userId,mediaType:r.strMediaType,resume:()=>r.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{Le(r)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:r}=t,s=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:c}=t;a||this._remoteAudioConfigMap.delete(r),c||this._removeRemoteVideoConfig(r,"main"),t.hasAuxiliary||this._removeRemoteVideoConfig(r,"sub"),n!==c&&(c?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"}),this.emit(c?x.REMOTE_VIDEO_AVAILABLE:x.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),s!==a&&(a?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:t}),this.emit(a?x.REMOTE_AUDIO_AVAILABLE:x.REMOTE_AUDIO_UNAVAILABLE,{userId:r})),e.hasAuxiliary!==t.hasAuxiliary&&(t.hasAuxiliary?this._onVideoAvailable({userId:r,streamType:"sub"}):this._onVideoUnavailable({userId:r,streamType:"sub"}),this.emit(t.hasAuxiliary?x.REMOTE_VIDEO_AVAILABLE:x.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}))}).add("sei-message",e=>{this.emit(x.SEI_MESSAGE,L(O({},e),{streamType:ki(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(x.ERROR,new V({code:$.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var s,n,a,c,l,u,m;let t={2:"big",3:"small",7:"sub"},r={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((s=e.msg_down_stream_info[0])==null?void 0:s.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,$s),upLoss:((c=this._networkQuality)==null?void 0:c.uplinkLoss)||0,downLoss:((l=this._networkQuality)==null?void 0:l.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((u=e.msg_up_stream_info.msg_audio_status)==null?void 0:u.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((m=e.msg_up_stream_info.msg_audio_status)==null?void 0:m.uint32_audio_level)||0)/Dt},video:e.msg_up_stream_info.msg_video_status.filter(h=>t[h.uint32_video_stream_type]).map(h=>({bitrate:(h.uint32_video_codec_bitrate||0)/1e3,width:h.uint32_video_width,height:h.uint32_video_height,frameRate:h.uint32_video_enc_fps,videoType:t[h.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(h=>({userId:h.msg_user_info.str_identifier,audio:{bitrate:(h.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(h.msg_audio_status.uint32_audio_level||0)/Dt,point2pointDelay:(h.msg_audio_status.uint32_audio_p2p_delay||0)+(h.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:h.msg_audio_status.uint32_audio_cache_ms||0},video:h.msg_video_status.map(_=>({bitrate:(_.uint32_video_codec_bitrate||0)/1e3,width:_.uint32_video_width,height:_.uint32_video_height,frameRate:_.uint32_video_dec_fps,videoType:t[_.uint32_video_stream_type],point2pointDelay:(_.uint32_video_p2p_delay||0)+(_.uint32_video_cache_ms||0),jitterBufferDelay:_.uint32_video_cache_ms||0,codec:_.uint32_video_codec}))}))};this.emit(x.STATISTICS,r)}).add("custom-message",e=>{this.emit(x.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(x.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(x.FIRST_VIDEO_FRAME,L(O({},e),{streamType:ki(e.streamType)}))}).add("audio-frame",e=>{this.emit(x.AUDIO_FRAME,e)}),tt(this,be).add("audioInputAdded",e=>{this.emit(x.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(x.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(x.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(x.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>p(this,null,function*(){if(this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),ze&&ze.deviceId===Hs){let t=(yield Nr()).find(r=>r.deviceId===Hs);t&&ze.groupId!==t.groupId&&(ze=t,this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>p(this,null,function*(){this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield Nr())[0];if(!t||!ze||ze.groupId===t.groupId)return;let r=ze.deviceId===e.deviceId,s=ze.deviceId===Hs&&ze.deviceId===t.deviceId;(r||s)&&(ze=t,this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))})),tt(this,Zn).add("permission-state-change",e=>{this.emit(x.PERMISSION_STATE_CHANGE,e)}),this.room.enableSEI&&this.on(x.SEI_MESSAGE,e=>{var r;let t=(r=this.room.remotePublishedUserMap.get(e.userId))==null?void 0:r.remoteVideoTrack;t&&t.updateAlphaRenderInfo(e)})}getNetworkTime(){return Fi()}use(e){let t,r;return"plugin"in e?(t=e.plugin,r=e.assetsPath):t=e,t.Name==="Chorus"&&(this.room.enableChorus=!0),this._use(t,r)}_use(e,t){let r=this._plugins.get(e.Name);if(r)return this._log.warn("duplicate install plugin",e.Name),r;let s=new e(Bf.call(this,{TRTC:q,room:this._room,assetsPath:t,errorModule:{RtcError:V,ErrorCode:$,CoreErrorCode:I,ErrorCodeDictionary:wt}}));return this._plugins.set(e.Name,s),s.__v_skip=!0,e.autoStart&&this.startPlugin(e.Name),s}enterRoom(e){return p(this,null,function*(){var c,l;this.enterRoomParams=e;let{scene:t="rtc",enableAutoPlayDialog:r=!0,autoReceiveAudio:s=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!ie(e.proxy)&&e.proxy.turnServer&&((l=(c=this._room).setTurnServer)==null||l.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=r,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=n,he(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,useH265:e.useH265||!1,keepAlive:e.keepAlive};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,q.frameWorkType),this._checkTrackToPublish(),Bh.start()})}exitRoom(){return p(this,null,function*(){return yield this._exitRoom()})}switchRoom(e){return p(this,null,function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(e)}catch(t){if(t instanceof ws&&(t.code===I.API_CALL_TIMEOUT||t.code===I.SWITCH_ROOM_FAILED))this._log.warn(`switchRoom ${t.code===I.API_CALL_TIMEOUT?"timeout":"failed"}, fallback to exitRoom() and enterRoom()`),yield this._rejoinRoom(e);else throw t}else yield this._rejoinRoom(e)})}_rejoinRoom(e){return p(this,null,function*(){yield this.exitRoom();let t=O(O({},this.enterRoomParams),e);yield this.enterRoom(t)})}_clearRemoteTracks(){new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch(()=>{})}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let t=e.includes("main")?"main":"sub",r=e.split(`_${t}`)[0];r&&this._stopRemoteVideo({userId:r,streamType:t}).catch(()=>{})}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),$f(this),this._room.remotePublishedUserMap.forEach(e=>{Le(e.remoteAudioTrack),Le(e.remoteVideoTrack),Le(e.remoteAuxiliaryTrack)})}switchRole(e,t){return p(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),t!=null&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)}),this._plugins.clear(),Le(this),this.removeAllListeners(),this._room.destroy(),Kn.delete(this),Kn.size===0&&Bh.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),S.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return p(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,mute:r,option:s}=e,n=new kt(this._room.audioManager),a={},c={muted:!0};s&&(T(s.microphoneId)?T(s.audioTrack)||(a.customSource=s.audioTrack):a.deviceId=s.microphoneId,s&&z(s.captureVolume)&&n.setCaptureVolume(s.captureVolume),T(s.profile)||(ie(s.profile)?fa[s.profile]&&n.setProfile(fa[s.profile]):n.setProfile(s.profile)),z(s.earMonitorVolume)&&(c.muted=!(s.earMonitorVolume>0),c.volume=s.earMonitorVolume),T(s.echoCancellation)||(n.profile.echoCancellation=s.echoCancellation),T(s.noiseSuppression)||(n.profile.noiseSuppression=s.noiseSuppression),T(s.autoGainControl)||(n.profile.autoGainControl=s.autoGainControl),he(this._enableAutoSwitchWhenRecapturing)&&(n.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),n.on("5",l=>{this.emit(x.ERROR,new V({code:$.DEVICE_ERROR,extraCode:5309,messageParams:{error:l}}))}),n.on("2",l=>{this.emit(x.DEVICE_CHANGED,{type:"microphone",action:"active",device:l})}),n.on("4",l=>{let u;l.error&&(u=V.convertFrom(l.error)),this.emit(x.PUBLISH_STATE_CHANGED,L(O({},l),{error:u}))}),n.on("6",()=>{}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),T(r)||n.setMute(r),tt(n,n).add("player-state-changed",l=>{this.emit(x.AUDIO_PLAY_STATE_CHANGED,L(O({},l),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=L(O({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:n}),S.emit("113",{userId:"",room:this.room})})}updateLocalAudio(e){return p(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:r,option:s}=e,n={};s&&(s.microphoneId?yield this._localAudioTrack.switchDevice(s.microphoneId):T(s.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(s.audioTrack)),T(s.captureVolume)||this._localAudioTrack.setCaptureVolume(s.captureVolume),T(s.earMonitorVolume)||(n.muted=!(s.earMonitorVolume>0),n.volume=s.earMonitorVolume),yield this._localAudioTrack.update3A(s)),this._room.isJoined&&!T(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),T(r)||this._localAudioTrack.setMute(r),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),ei(this._localAudioConfig,e)})}stopLocalAudio(){return p(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),S.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),Le(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return p(this,arguments,function*(e={publish:!0,view:null,capture:!0}){var m;if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:t,publish:r=!0,capture:s=!0,mute:n,option:a}=e,c=new je(this._room.videoManager),l={},u={};a&&(he(a.avoidCropping)&&(c.avoidCropping=a.avoidCropping),a.cameraId?l.deviceId=a.cameraId:T(a.useFrontCamera)?T(a.videoTrack)||(l.customSource=a.videoTrack):l.facingMode=a.useFrontCamera?f.FACING_MODE_USER:f.FACING_MODE_ENVIRONMENT,T(a.retryWhenExactFailed)||(l.retryWhenExactFailed=a.retryWhenExactFailed),a.qosPreference&&(l.contentHint=qn(a.qosPreference)),T(a.profile)||(ie(a.profile)?zt[a.profile]&&c.setProfile(zt[a.profile]):c.setProfile(a.profile)),T(a.fillMode)||(u.objectFit=a.fillMode),T(a.mirror)||(u.mirror=a.mirror),T(a.small)||(T(a.smallMode)||(this._room.smallMode=a.smallMode),he(a.small)&&a.small===!1?c.stopSmall():c.updateSmallConfig(Is(a.small,!0))),T(a.rotation)||c.setRotation(a.rotation),he(this._enableAutoSwitchWhenRecapturing)&&(c.enableAutoSwitchWhenRecapturing=this._enableAutoSwitchWhenRecapturing)),c.once("first-video-frame",h=>{this.emit(x.FIRST_VIDEO_FRAME,L(O({},h),{streamType:ki(h.streamType)}))}),c.on("5",h=>{this.emit(x.ERROR,new V({code:$.DEVICE_ERROR,extraCode:5308,messageParams:{error:h}}))}),c.on("2",h=>{this.emit(x.DEVICE_CHANGED,{type:"camera",action:"active",device:h})}),c.on("4",h=>{let _;h.error&&(_=V.convertFrom(h.error)),this.emit(x.PUBLISH_STATE_CHANGED,L(O({},h),{error:_}))}),c.on("6",()=>{}),this._listenOutputTrackChanged(c),s?yield c.capture(l):(m=c.manager)==null||m.changeInput(c),T(n)||(yield c.setMute(n)),tt(c,c).add("player-state-changed",h=>{this.emit(x.VIDEO_PLAY_STATE_CHANGED,L(O({},h),{userId:"",streamType:"main"}))}).add("video-size-changed",h=>{this.emit(x.VIDEO_SIZE_CHANGED,L(O({},h),{streamType:ki(h.streamType)}))}),r&&this._room.isJoined&&this._room.publish(c).catch(()=>{}),this._localVideoTrack=c,this._localVideoConfig=L(O({},e),{view:t,publish:r,capture:s}),yield this._updateVideoPlayOption({view:t,playOption:u,track:c})})}updateLocalVideo(e){return p(this,null,function*(){var l,u,m;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:r,mute:s,capture:n,option:a}=e,c={};if(this._localVideoConfig.capture)n!==!1?a!=null&&a.cameraId?yield this._localVideoTrack.switchDevice(a==null?void 0:a.cameraId):T(a==null?void 0:a.useFrontCamera)?T(a==null?void 0:a.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(a==null?void 0:a.videoTrack)):yield this._localVideoTrack.switchDevice(a!=null&&a.useFrontCamera?f.FACING_MODE_USER:f.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(n){let h={};h.deviceId=(a==null?void 0:a.cameraId)||((l=this._localVideoConfig.option)==null?void 0:l.cameraId),h.facingMode=a!=null&&a.useFrontCamera||(u=this._localVideoConfig.option)!=null&&u.useFrontCamera?f.FACING_MODE_USER:f.FACING_MODE_ENVIRONMENT,h.customSource=(a==null?void 0:a.videoTrack)||((m=this._localVideoConfig.option)==null?void 0:m.videoTrack),yield this._localVideoTrack.capture(h)}a&&(T(a.profile)||(ie(a.profile)?zt[a.profile]&&this._localVideoTrack.setProfile(zt[a.profile]):this._localVideoTrack.setProfile(a.profile),(!a.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(a.cameraId))&&T(a.useFrontCamera)&&(yield this._localVideoTrack.applyProfile())),T(a.fillMode)||(c.objectFit=a.fillMode),T(a.mirror)||(c.mirror=a.mirror),T(a.rotation)||this._localVideoTrack.setRotation(a.rotation),a.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(qn(a.qosPreference)),T(a.small)||(he(a.small)&&!a.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(Is(a.small,!0)))),this._room.isJoined&&T(r)&&this._localVideoConfig.publish&&n&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&((r!=null?r:this._localVideoConfig.publish)?this._room.publish(this._localVideoTrack).catch(()=>{}):this._room.unpublish(this._localVideoTrack).catch(()=>{})),T(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:t,playOption:c,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),ei(this._localVideoConfig,e)})}stopLocalVideo(){return p(this,null,function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),Le(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return p(this,arguments,function*(e={publish:!0,view:null}){var h,_;if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:t=null,publish:r=!0,muteSystemAudio:s,option:n}=e,a=new Pt(this._room.videoManager);a.on("4",g=>{let E;g.error&&(E=V.convertFrom(g.error)),this.emit(x.PUBLISH_STATE_CHANGED,L(O({},g),{error:E}))}),a.once("first-video-frame",g=>{this.emit(x.FIRST_VIDEO_FRAME,L(O({},g),{streamType:ki(g.streamType)}))}),this._listenOutputTrackChanged(a),e.streamType==="main"&&(a.mediaType=4);let c=null,l={},u={};n&&(T(n.profile)||(ie(n.profile)?_a[n.profile]&&a.setProfile(_a[n.profile]):a.setProfile(n.profile)),n.systemAudio&&(l.systemAudio=!0,l.echoCancellation=n.echoCancellation,l.noiseSuppression=n.noiseSuppression,l.autoGainControl=n.autoGainControl),T(n.fillMode)||(u.objectFit=n.fillMode),n.videoTrack&&(l.videoTrack=n.videoTrack),n.audioTrack&&(l.audioTrack=n.audioTrack),n.captureElement&&(l.captureElement=n.captureElement),n.preferDisplaySurface&&(l.preferDisplaySurface=n.preferDisplaySurface),n.qosPreference&&(l.contentHint=qn(n.qosPreference)));let m=yield a.capture(l);if(a.mediaTrack.addEventListener(f.ENDED,()=>{this._stopScreenShare(),this.emit(x.SCREEN_SHARE_STOPPED)}),m.getAudioTracks()[0]){c=new To(this._room.audioManager);let g=m.getAudioTracks()[0];(h=e.option)!=null&&h.systemAudio&&!((_=e.option)!=null&&_.audioTrack)&&(c.sourceTrack=g),yield c.setInputMediaStreamTrack(g),he(s)&&c.mediaTrack&&(c.mediaTrack.enabled=!s),this._speakerId&&c.setAudioOutput(this._speakerId)}if(tt(a,a).add("player-state-changed",g=>{this.emit(x.VIDEO_PLAY_STATE_CHANGED,L(O({},g),{userId:"",streamType:"sub"}))}),r&&this._room.isJoined){let g=[a];c&&(g.push(c),this._checkScreenAudioEchoCancellation(a,c)),g.forEach(E=>this._room.publish(E).catch(()=>{}))}this._localScreenTrack=a,this._localScreenAudioTrack=c,this._localScreenConfig=L(O({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:u,track:a})})}updateScreenShare(e){return p(this,null,function*(){var c;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:r,muteSystemAudio:s,option:n}=e,a={};if(n&&(T(n.fillMode)||(a.objectFit=n.fillMode),n.qosPreference)){let l=qn(n.qosPreference);this._localScreenTrack.setContentHint(l)}if(this._room.isJoined&&!T(r)){if(r&&!this._localScreenConfig.publish){let l=[this._localScreenTrack];this._localScreenAudioTrack&&l.push(this._localScreenAudioTrack),l.forEach(u=>this._room.publish(u).catch(()=>{}))}if(this._localScreenConfig.publish&&!r){let l=[this._localScreenTrack];this._localScreenAudioTrack&&l.push(this._localScreenAudioTrack),l.forEach(u=>this._room.unpublish(u).catch(()=>{}))}}(c=this._localScreenAudioTrack)!=null&&c.mediaTrack&&he(s)&&(this._localScreenAudioTrack.mediaTrack.enabled=!s),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),ei(this._localScreenConfig,e)})}stopScreenShare(){return p(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return p(this,null,function*(){let{view:t,userId:r,streamType:s,option:n}=e,a=`${r}_${s}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${r}, streamType:${s}`);return}let c=this._room.remotePublishedUserMap.get(r);if(!c)return;let l={},u=s==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;u.on("decode-failed",m=>{this.emit(x.ERROR,new V({code:$.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))}),u.on("video-size-changed",m=>{this.emit(x.VIDEO_SIZE_CHANGED,L(O({},m),{streamType:ki(m.streamType)}))}),this._listenOutputTrackChanged(u),n&&(T(n.fillMode)||(l.objectFit=n.fillMode),T(n.mirror)||(l.mirror=n.mirror),T(n.poster)||(l.poster=n.poster),l.canvasRender=n.canvasRender,s==="main"&&!T(n.small)&&(!c.remoteVideoTrack.isSubscribing&&!c.remoteVideoTrack.isSubscribed&&c.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,u.user)),T(n.draggable)||u.setDraggable(n.draggable)),yield this._room.subscribe(u),yield this._enableVideoDecodeFallback(u,s),yield this._updateVideoPlayOption({view:t,playOption:l,track:u}),this._emitTrackEvent(u),this._remoteVideoConfigMap.set(a,{config:e}),n&&!T(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:u,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return p(this,null,function*(){var k,re;let{view:t,userId:r,streamType:s,option:n,mute:a}=e,c=`${r}_${s}`,l=this._remoteVideoConfigMap.get(c);if(!l||!this._room.remotePublishedUserMap.has(r))return;let u={};n&&(T(n.fillMode)||(u.objectFit=n.fillMode),T(n.mirror)||(u.mirror=n.mirror));let m=null,h=this._room.remotePublishedUserMap.get(r);if(s==="main"&&(h!=null&&h.muteState.hasVideo)&&(m=h.remoteVideoTrack),s==="sub"&&(h!=null&&h.muteState.hasAuxiliary)&&(m=h.remoteAuxiliaryTrack),!m)return;let{config:_}=l;s==="main"&&n&&!T(n.small)&&this._room.changeType(n.small,m.user),n&&!T(n.draggable)&&m.setDraggable(n.draggable),he(a)&&(m.ignoreUpdatePlayingState=!0,a?(yield m.player.pause(),yield this.room.unsubscribe(m)):(yield this.room.subscribe(m),yield m.player.resume(!0))),yield this._updateVideoPlayOption({view:t,playOption:u,track:m,prevConfig:_}),ei(_,e);let g=T(n==null?void 0:n.receiveWhenViewVisible)?(k=_.option)==null?void 0:k.receiveWhenViewVisible:n.receiveWhenViewVisible,E=T(t)?_.view:t,A=T(n==null?void 0:n.viewRoot)?(re=_.option)==null?void 0:re.viewRoot:n.viewRoot;this._observeView({remoteTrack:m,view:E,receiveWhenViewVisible:g,viewRoot:A})})}stopRemoteVideo(e){return p(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return p(this,null,function*(){let r=[],s=this._room.remotePublishedUserMap.get(e.userId);if(s){let{muteState:n,remoteVideoTrack:a,remoteAuxiliaryTrack:c}=s;e.streamType==="main"&&(a.stop(),n.hasVideo&&r.push(a)),e.streamType==="sub"&&(c.stop(),n.hasAuxiliary&&r.push(c))}for(let n of r)t&&(delete n.ignoreUpdatePlayingState,yield this._room.unsubscribe(n),this._mediaTrackMap.delete(n.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)})}_removeRemoteVideoConfig(e,t){let r=`${e}_${t}`,s=this._remoteVideoConfigMap.get(r);s&&s.observer&&s.observer.disconnect(),this._remoteVideoConfigMap.delete(r)}muteRemoteAudio(e,t){return p(this,null,function*(){this._remoteAudioMuteMap.set(e,t);try{if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let r=[...this._room.remotePublishedUserMap.values()];for(let s of r)s.muteState.hasAudio&&!this._remoteAudioConfigMap.has(s.userId)&&(yield this._startRemoteAudio({userId:s.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(r){throw r.code!==$.OPERATION_ABORT&&this._remoteAudioMuteMap.delete(e),r}})}setRemoteAudioVolume(e,t){if(e==="*"){this._remoteAudioVolumeMap.set("*",t),this._remoteAudioVolumeMap.forEach((s,n)=>this._remoteAudioVolumeMap.set(n,t));let r=[...this._room.remotePublishedUserMap.values()];for(let s of r)this._remoteAudioVolumeMap.set(s.userId,t),s.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:s.remoteAudioTrack})}else if(e){let r=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,t),r&&r.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:r.remoteAudioTrack})}}startPlugin(e,t){return p(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return p(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return p(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,r){if(this.listeners(e).includes(t))return this;if(this._log.debug("on",e),super.on(e,t,r),this._eventListened.add(e),this.listeners(x.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:s}=this.room.audioManager;s.get("")||s.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return this}emit(e,...t){try{wf.has(e)||this._log.debug(`emit ${e} ${JSON.stringify(t)}`)}catch(r){}return super.emit(e,...t)}off(e,t,r){if(this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,r),(e===q.EVENT.AUDIO_FRAME||e==="*")&&this.listeners(q.EVENT.AUDIO_FRAME).length===0){let{getPCMAbortCtrlMap:s}=this.room.audioManager;s.forEach(n=>{n==null||n.abort("off")}),s.clear()}return this}getAudioTrack(e={userId:"",streamType:"main"}){let t,r=null,s="main",n=!1;if(ie(e)?t=e:(t=e.userId,n=e.processed===!0,e.streamType&&(s=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);a&&(r=a.remoteAudioTrack)}else r=s==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return r?n&&r.outMediaTrack&&r.outMediaTrack!==r.mediaTrack?r.outMediaTrack.clone():r.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:r="main",processed:s=!1}=e,n=null;if(t==="")r==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),r==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(t);a&&(n=r==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?s&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:t,streamType:r="main"}=e;if(t){let s=this._room.remotePublishedUserMap.get(t);if(r==="main"&&(s!=null&&s.muteState.hasVideo))return s.remoteVideoTrack.getVideoFrame();if(r==="sub"&&(s!=null&&s.muteState.hasAuxiliary))return s.remoteAuxiliaryTrack.getVideoFrame()}else{if(r==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(r==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var t,r;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(r=this._localScreenAudioTrack)==null||r.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(s=>s.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return p(this,null,function*(){(yield Nr()).forEach(r=>{r.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}),ze=r)}),this._log.warn(`the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: ${ft}/en/TRTC.html#.setCurrentSpeaker`)})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return p(this,null,function*(){var a;let{userId:t}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let s={},n=r.remoteAudioTrack;n.on("decode-failed",c=>{this.emit(x.ERROR,new V({code:$.OPERATION_FAILED,extraCode:5508,message:"audio decode failed"}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let c=(a=this._remoteAudioVolumeMap.get(t))!=null?a:this._remoteAudioVolumeMap.get("*"),l=z(c)?c:100;s.volume=l,this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(n),de(ce(n,"decode-failed"),ke(ce(n,J.INIT)),Te(()=>{this.startPlugin(Yn.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:n}),S.emit("115",{userId:t,room:this.room}),n.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:n.outMediaTrack,refId:`ra-${t}`})}catch(c){throw this._remoteAudioConfigMap.delete(t),c}this._emitTrackEvent(n)})}_stopRemoteAudio(e,t=!0){return p(this,null,function*(){let r=this._room.remotePublishedUserMap.get(e.userId);r&&(r.remoteAudioTrack.stop(),r.muteState.hasAudio&&t&&(yield this._room.unsubscribe(r.remoteAudioTrack)),this._mediaTrackMap.delete(r.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`),S.emit("116",{userId:e.userId,room:this.room}),this.room.audioManager.updateAudioReference({type:"remove",refId:`ra-${e.userId}`})})}_enableVideoDecodeFallback(e,t){let r=this._room.videoDecodeFallbackType;if(!r||!this._plugins.has("TRTCVideoDecoder"))return;e.log.debug("remote video will fall back when decode failed",e.id);let s;de(ce(e,"decode-failed"),ke(ce(e,J.INIT)),Bn(()=>{this._room.downlinkVideoCodec!=="h265"&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})}),mo(ce(e,"decode-downgrade-state-changed")),Te(n=>{s=n.state,this.emit(x.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,L(O({},n),{streamType:t,userId:e.userId}))},n=>{e.log.error("fallback",n)},()=>{s==="STARTED"&&e.log.info("fallback complete")}))}_updateVideoPlayOption(n){return p(this,arguments,function*({view:e,playOption:t,track:r,prevConfig:s}){if(r.setMirror(t.mirror),T(e)&&s&&s.view&&!Uo(t)){let a=Fo(s.view);a.length>0&&(yield r.play(a,t))}if(!T(e)){let a=Fo(e);a.length>0?yield r.play(a,t):r.stop()}})}_updateAudioPlayOption(s){return p(this,arguments,function*({playOption:e={},track:t,prevConfig:r}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}if(T(e.muted)||t.setPlayerMute(e.muted),T(e.volume)||t.setAudioVolume(e.volume/100),t instanceof kt&&t.mediaTrack){let n=e.muted===!1&&!T(e.volume)&&e.volume>0?"add":"remove";this.room.audioManager.updateAudioReference({type:n,audioReference:t.mediaTrack,refId:"em"})}else if(t instanceof gi){let n=e.muted?0:e.volume;if(T(n))return;this.room.audioManager.updateAudioReference({type:"updateVolume",refId:`ra-${t.userId}`,volume:e.volume})}})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,t=!0){let r=e.isRemote?e.userId:"";e.outMediaTrack&&(t&&this._mediaTrackMap.get(e.outMediaTrack)===r||(this._mediaTrackMap.set(e.outMediaTrack,r),this.emit(x.TRACK,{userId:r,streamType:ki(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var t,r,s;let e=[];if((t=this._localAudioConfig)!=null&&t.publish&&this._localAudioTrack&&e.push(this._localAudioTrack),(r=this._localVideoConfig)!=null&&r.publish&&this._localVideoTrack&&e.push(this._localVideoTrack),(s=this._localScreenConfig)!=null&&s.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack),this._checkScreenAudioEchoCancellation(this._localScreenTrack,this._localScreenAudioTrack)),e.length!==0)return Promise.all(e.map(n=>this._room.publish(n).catch(()=>{})))}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:r,viewRoot:s}){if(T(t)||T(r))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${ki(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||Ie(t)&&t.length===0||!r){a==null||a.disconnect(),e.isSubscribed||(this._log.info("_observeView observer disconnect, resubscribe",e.userId,e.strMediaType),this._room.subscribe(e).catch(()=>{}));return}let l=n.visibleViewMap||new Map,u=-1;(!a||a.root!==s)&&(a==null||a.disconnect(),l.clear(),a=new IntersectionObserver(h=>{h.forEach(_=>{l.set(_.target,_.isIntersecting),e.log.info(`view ${_.target.id} is${_.isIntersecting?"":" not"} visible`)}),clearTimeout(u),u=window.setTimeout(()=>{[...l.values()].find(g=>g)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:s}));let m=new Set(Fo(t));l.forEach((h,_)=>{m.has(_)||(a.unobserve(_),l.delete(_))}),m.forEach(h=>{l.set(h,!0),a.observe(h)}),a.takeRecords().forEach(h=>{l.set(h.target,h.isIntersecting)}),n.visibleViewMap=l,n.observer=a}_exitRoom(){return p(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()})}_stopScreenShare(){return p(this,null,function*(){var e;if(this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield Promise.all(t.map(r=>this._room.unpublish(r).catch(()=>{})))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(((e=this._localScreenAudioTrack.trackSettings)==null?void 0:e.echoCancellation)===!1&&this.stopPlugin("AudioProcessor"),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),Le(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_checkScreenAudioEchoCancellation(e,t){return p(this,null,function*(){var s,n;if(!e||!t)return;let r=(s=e.trackSettings)==null?void 0:s.displaySurface;if(((n=t.trackSettings)==null?void 0:n.echoCancellation)===!1&&(r==="monitor"||r==="browser"&&e.isShareCurrentTab)){this._log.warn("echoCancellation of screen audio track is disable. Try starting audioProcessor plugin");try{yield this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,isScreenAudioNeedAudioProcess:!0,isLocalAudioNeedAudioProcess:!1})}catch(a){this._log.warn("start audioProcessor plugin failed: ",a)}}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!ze||ls(ze))&&(this._initActiveSpeaker(),S.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return p(this,null,function*(){if(ze&&!ls(ze))this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:ze});else{let e=yield Nr();e[0]&&!ls(e[0])?(ze=e[0],this.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):S.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let r=this._room.remotePublishedUserMap.get(e);if(r){let s=t==="main"?r.remoteVideoTrack:r.remoteAuxiliaryTrack,n=[s];this._room.autoReceiveAudio&&r.remoteAudioTrack.isAvailable&&n.push(r.remoteAudioTrack),this._room.subscribe(...n).then(()=>{this._emitTrackEvent(s)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:t}){t.hasAudio&&t.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:t}){this._stopRemoteVideo({userId:e,streamType:t},!1).catch(()=>{})}sendSEIMessage(e,t){var s;let r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:L(O({seiPayloadType:243},t),{small:!!((s=this._localVideoTrack)!=null&&s.small)})}),v.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,r;(r=(t=this._room).sendCustomMessage)==null||r.call(t,e),v.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,t){return p(this,null,function*(){return this._log.info(`callExperimentalAPI(${e}, ${JSON.stringify(t)})`),Qf.call(e,O({trtcInstance:this},t))})}static setLogLevel(e,t){R.setLogLevel(e),T(t)||(t?R.enableUploadLog():R.disableUploadLog())}static isSupported(){return _c(q.frameWorkType)}static getPermissions(r){return p(this,arguments,function*({request:e=!0,types:t=["camera","microphone"]}){e&&(yield Zn.request(t).catch(a=>{var c;return R.error(`getPermissions request failed, error: ${(c=a==null?void 0:a.message)!=null?c:a}`)}));let[s,n]=yield Promise.all([Zn.get("camera"),Zn.get("microphone")]);return{camera:s,microphone:n}})}static getCameraList(e=!0){return At(e)}static getMicrophoneList(e=!0){return It(e)}static getSpeakerList(e=!0){return Nr(e)}static setCurrentSpeaker(e){return p(this,null,function*(){if(_e&&(e===So.SPEAKER||e===So.HEADSET)){let r=yield q.getMicrophoneList(),s="";if(r.forEach(n=>{n.label===e&&(s=n.deviceId)}),!s)return;Kn.forEach(n=>p(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield Nr()).forEach(r=>{r.deviceId===e&&(Kn.forEach(s=>{s._setCurrentSpeaker(e),s.emit(x.DEVICE_CHANGED,{type:"speaker",action:"active",device:r})}),ze=r)})})}static _addKVStat({type:e,key:t,value:r,base:s,useUV:n,version:a,max:c}){switch(a&&(ro.version=a),e){case"count":ro.addCount({key:t,useUV:n});break;case"enum":ro.addEnum({key:t,value:r,useUV:n});break;case"number":ro.addNumber({key:t,value:r,split:s,max:c});break}}};d(q,"VERSION",wh),d(q,"_loggerManager",R),d(q,"EVENT",x),d(q,"ERROR_CODE",$),d(q,"TYPE",So),d(q,"frameWorkType",30),M([Ae({replaceArg:e=>({argIndex:0,value:{name:"plugin"in e?e.plugin.Name:e.Name,assetsPath:"assetsPath"in e?e==null?void 0:e.assetsPath:"default"}})})],q.prototype,"use",1),M([st(We.TRTC.enterRoom),wr("room",([e],[t])=>(e.roomId||e.strRoomId)===(t.roomId||t.strRoomId)&&e.userId===t.userId&&e.sdkAppId===t.sdkAppId),Q(e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)}),Ae()],q.prototype,"enterRoom",1),M([Ae()],q.prototype,"exitRoom",1),M([st(We.TRTC.switchRoom),Ae(),ir()],q.prototype,"switchRoom",1),M([st(We.TRTC.switchRole),Ao("room",{merge:(e,t)=>t}),Ae()],q.prototype,"switchRole",1),M([Ae()],q.prototype,"destroy",1),M([st(We.TRTC.startLocalAudio),wr("audio",([e],[t])=>{var r,s;return((r=e==null?void 0:e.option)==null?void 0:r.microphoneId)===((s=t==null?void 0:t.option)==null?void 0:s.microphoneId)}),Ae()],q.prototype,"startLocalAudio",1),M([st(We.TRTC.updateLocalAudio),Ao("audio",{debounce:{delay:200,getKey:()=>`${Zf}-localAudio`,isNeedToDebounce:e=>{var t;return!T((t=e.option)==null?void 0:t.captureVolume)}}}),Ae()],q.prototype,"updateLocalAudio",1),M([Lr("audio"),Ae()],q.prototype,"stopLocalAudio",1),M([st(We.TRTC.startLocalVideo),wr("video",([e],[t])=>{var r,s;return((r=e==null?void 0:e.option)==null?void 0:r.cameraId)===((s=t==null?void 0:t.option)==null?void 0:s.cameraId)}),Ae()],q.prototype,"startLocalVideo",1),M([st(We.TRTC.updateLocalVideo),Ao("video"),Ae()],q.prototype,"updateLocalVideo",1),M([Lr("video"),Ae()],q.prototype,"stopLocalVideo",1),M([st(We.TRTC.startScreenShare),wr("screen",()=>!0),Ae()],q.prototype,"startScreenShare",1),M([st(We.TRTC.updateScreenShare),Ao("screen"),Ae()],q.prototype,"updateScreenShare",1),M([Ae()],q.prototype,"stopScreenShare",1),M([st(We.TRTC.startRemoteVideo),wr(e=>`v${e.userId}${e.streamType}`,()=>!0),Ae({getRemoteId:e=>`${e.userId}_${e.streamType}`})],q.prototype,"startRemoteVideo",1),M([st(We.TRTC.updateRemoteVideo),Ao(e=>`v${e.userId}${e.streamType}`),Ae({getRemoteId:e=>`${e.userId}_${e.streamType}`})],q.prototype,"updateRemoteVideo",1),M([st(We.TRTC.stopRemoteVideo),Q(e=>function(t){return p(this,null,function*(){if(t.userId==="*"){let r=[];return this._room.remotePublishedUserMap.forEach(s=>{this._remoteVideoConfigMap.has(`${s.userId}_main`)&&r.push(this.stopRemoteVideo({streamType:"main",userId:s.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${s.userId}_sub`)&&r.push(this.stopRemoteVideo({streamType:"sub",userId:s.userId}).catch(()=>{}))}),Promise.all(r)}return e.call(this,t)})}),Ae({getRemoteId:e=>`${e.userId}_${e.streamType}`})],q.prototype,"stopRemoteVideo",1),M([Lr(e=>`v${e.userId}${e.streamType}`)],q.prototype,"_stopRemoteVideo",1),M([st(...We.TRTC.muteRemoteAudio),Ae({getRemoteId:e=>e})],q.prototype,"muteRemoteAudio",1),M([Lh(...We.TRTC.setRemoteAudioVolume),Wf(200,e=>e),Ae({getRemoteId:e=>e})],q.prototype,"setRemoteAudioVolume",1),M([pd("start"),Ct(e=>{var t;return(t=e.afterStart)==null?void 0:t.call(e)}),wr((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),Ae({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Kl[e.getName()],ignoreLog:e=>e.getName()==="Debug",ignoreErrorLog:e=>e.getName()==="AudioProcessor"})],q.prototype,"startPlugin",1),M([pd("update"),Ao((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t),{merge:(e,t)=>(ei(e[1],t[1]),e)}),Ae({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>eu[e.getName()]})],q.prototype,"updatePlugin",1),M([pd("stop"),Lr((e,t)=>{if(e.disableRandomCall)return null;let r=e.getGroup(t),s=e.getAlias();return r==="*"?new RegExp(`${s}.*`):s+r}),Ae({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>tu[e.getName()]})],q.prototype,"stopPlugin",1),M([Lh(...We.TRTC.enableAudioVolumeEvaluation)],q.prototype,"enableAudioVolumeEvaluation",1),M([Ae()],q.prototype,"getVideoSnapshot",1),M([Ae()],q.prototype,"_setCurrentSpeaker",1),M([wr(e=>`a${e.userId}`,()=>!0)],q.prototype,"_startRemoteAudio",1),M([Q(e=>function(t){return p(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(r=>this._stopRemoteAudio(L(O({},t),{userId:r.userId})).catch(()=>{}))):e.call(this,t)})}),Lr(e=>`a${e.userId}`)],q.prototype,"_stopRemoteAudio",1),M([Lr("room")],q.prototype,"_exitRoom",1),M([Lr("screen")],q.prototype,"_stopScreenShare",1),M([st(...We.TRTC.sendSEIMessage),Ch({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],q.prototype,"sendSEIMessage",1),M([st(We.TRTC.sendCustomMessage),Ch({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],q.prototype,"sendCustomMessage",1),M([xr()],q,"create",1),M([st(We.TRTC.create)],q,"_create",1),M([xr()],q,"setLogLevel",1),M([xr()],q,"isSupported",1),M([xr()],q,"getPermissions",1),M([xr()],q,"getCameraList",1),M([xr()],q,"getMicrophoneList",1),M([xr()],q,"getSpeakerList",1);var qh=q,ea=qh;var Jh=class{constructor(){d(this,"_set",new Set);S.on(C.LEAVE_SUCCESS,this.delete,this),S.on(C.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,r){return`${t}_${e}_${i}_${r}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:r}){return r.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,r.useStringRoomId))}handleSwitchRoomSuccess({room:i,currentRoomId:e,targetRoomId:t}){i.scene!=="rtc"&&(this._set.delete(this.getKey(i.userId,e,i.sdkAppId,i.useStringRoomId)),this._set.add(this.getKey(i.userId,t,i.sdkAppId,i.useStringRoomId)))}};function KS(){return p(this,null,function*(){let o,i;try{let _=yield It();o=_&&_.length}catch(_){}try{let _=yield At();i=_&&_.length}catch(_){}let e={microphone:o,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:r,isH264DecodeSupported:s,isVp8DecodeSupported:n,isH265EncodeSupported:a,isH265DecodeSupported:c}=this.checkSystemResult.detail,l=bi.basis(),u={webRTC:l.isWebRTCSupported,getUserMedia:l.isGetUserMediaSupported,webSocket:l.isWebSocketsSupported,screenShare:l.isScreenShareSupported,webAudio:l.isWebAudioSupported,h264Encode:t,h264Decode:s,vp8Encode:r,vp8Decode:n,h265Encode:a,h265Decode:c},m={browser:l.browser,os:l.os,trtc:u,devices:e},h={isWebCodecSupported:l.isWebCodecSupported,isMediaSessionSupported:l.isMediaSessionSupported,isWebTransportSupported:l.isWebTransportSupported};se.uploadEvent({log:`trtcstats-${JSON.stringify(m)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(m)}`),se.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(h)}`,userId:this.userId}),mu()})}function e_(){return Q(o=>{let i=new Jh;return function(e,t,r){return p(this,null,function*(){let s=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=t,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new D({code:I.INVALID_OPERATION,message:H({key:F.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new D({code:I.INVALID_OPERATION,message:H({key:F.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:s}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${s} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),S.emit(C.JOIN_START,{room:this,roomId:s,params:e});let n=vt.getEnv();n||(n=Bi.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(ga.OLD_CLOUD_LADDER)?n=Bi.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(ga.WEBRTC)&&(n=Bi.WEBRTC))),se.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),bi.checkSystemRequirementsInternal(r).then(a=>{this.checkSystemResult=a,KS.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!vt.getEnv()&&(yield this.schedule(e,r));let a=yield o.call(this,e,t,r);return this.roomId=s,this._joinedTimestamp=vt.performanceNow(),S.emit(C.JOIN_SUCCESS,{room:this}),r===30&&!e.component&&se.uploadEvent({log:`stat-conv-${Number(oi)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw i.delete({room:this,roomId:s}),S.emit(C.JOIN_FAILED,{room:this,error:a}),a}})}})}var t_=()=>Q(o=>function(...i){return p(this,null,function*(){S.emit(C.LEAVE_START,{room:this}),yield o.call(this,...i),S.emit(C.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function i_(){return Q(o=>function(...i){let e=o.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var o_=Ge(at());var Se={SETUP_SUCCESS:"1",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4",SETUP_FAILED:"5",DISCONNECTED:"6",CLOSE:"7",ONLINE:"8"};var qt={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140,FALLBACK_CODEC:66,SEND_SWITCH_ROOM_RES:4160,SEND_SWITCH_ROOM_SUBED_REQ:4161,UPDATE_NETWORK_TIME_RESULT:5001,CUSTOM_CMD_RES:8220},r_=[qt.UPDATE_REMOTE_MUTE_STAT,qt.UPLINK_NETWORK_STATS,qt.USER_LIST_RES,qt.MUTE_RESULT,qt.SERVER_FIRST_PACKAGE_RECEIVED,qt.RECEIVE_CUSTOM_MSG,qt.UPDATE_NETWORK_TIME_RESULT],G={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",START_PUBLISH_CDN_STREAM_RES:"start-publish-cdn-stream-res",UPDATE_PUBLISH_CDN_STREAM_RES:"update-publish-cdn-stream-res",STOP_PUBLISH_CDN_STREAM_RES:"stop-publish-cdn-stream-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg",FALLBACK_CODEC:"fallback-codec",SEND_SWITCH_ROOM_RES:"send-switch-room-res",SEND_SWITCH_ROOM_SUBED_REQ:"send-switch-room-subed-res",UPDATE_NETWORK_TIME_RESULT:"update_network_time_result",CUSTOM_CMD_RES:"custom-cmd-res"},Y={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",START_PUBLISH_CDN_STREAM:"start_publish_cdn_stream",UPDATE_PUBLISH_CDN_STREAM:"update_publish_cdn_stream",STOP_PUBLISH_CDN_STREAM:"stop_publish_cdn_stream",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3",ABILITY_STATUS_REPORT:"ability_status_report",RECONNECT_WS:"reconnect",SEND_CUSTOM_MSG:"channel_msg",SWITCH_ROOM:"switch_room",UPDATE_NETWORK_TIME:"update_network_time",CUSTOM_CMD:"abstract_cmd"};var bd=new Set;function s_(o){let i=[...bd.values()].find(e=>e.room.userId===o&&!e.room.isJoined);return i||null}var tI=["autoTest","relayInnerIp","relayOuterIp","mcd","newRelay","clientIp"],bs=class extends o_.default{constructor(e){var r,s,n;super();d(this,"room");d(this,"sdkAppId");d(this,"userId");d(this,"userSig");d(this,"url");d(this,"backupUrl");d(this,"destroyed",!1);d(this,"_socketInUse");d(this,"_socket");d(this,"_backupSocket");d(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[],reportToken:void 0});d(this,"_currentState","DISCONNECTED");d(this,"_isReconnecting",!1);d(this,"_seq",0);d(this,"_log");d(this,"_lastMessageTime",-1);d(this,"_connectStartTime",-1);d(this,"_stopConnectRetry");d(this,"_isFirstConnect",!0);d(this,"bytesSent",0);d(this,"bytesReceived",0);d(this,"keepAlive",!1);d(this,"signalDomainWhenUnifiedProxy");d(this,"stopKeepAliveTimeout");d(this,"rtt",0);this.room=e.room,this.sdkAppId=e.sdkAppId,this.userId=e.userId,this.userSig=e.userSig,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy;let t=((s=(r=this.room.scheduleResult)==null?void 0:r.config)==null?void 0:s.keepAliveClient)||0;(n=this.room.joinParams)!=null&&n.keepAlive&&!t&&(t=1),t-bd.size>0&&this.room.enableSPC&&(this.keepAlive=!0,bd.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=R.createLogger({parent:this.room.getLogger(),id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get race(){return this.room.enableSPC&&!this.room.proxy_ws}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`);let t=new URLSearchParams(location.search);return tI.forEach(r=>{let s=t.get(`trtc_${r}`);s&&(e+=`&${r}=${encodeURIComponent(s)}`)}),this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return p(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}] ${this.race?"race":""}${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connectStartTime=U();let t=[this.connectWS({url:this._urlWithParam,isMain:!0,timeout:e})];this.race&&this._backupUrlWithParam!==this._urlWithParam&&t.push(this.connectWS({url:this._backupUrlWithParam,isMain:!1,timeout:e})),this._socketInUse=yield Xr(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?f.BACKUP:f.MAIN),this._isFirstConnect&&(v.addSuccessEvent({key:521720}),this._isFirstConnect=!1),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:r}){let s=new WebSocket(e);this.bindSocket(s),r?this._socket=s:this._backupSocket=s;let n=-1;return new Promise((a,c)=>{s.onclose=c,s.onerror=c,s.onopen=()=>a(s),t&&(n=setTimeout(()=>{this.unbindAndCloseSocket(r?f.MAIN:f.BACKUP),c(new D({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{s.onclose=null,s.onerror=null,s.onopen=null,clearTimeout(n)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===f.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}onclose(e){e.target===this._socketInUse&&(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),(!e.wasClean||e.code!==1e3)&&this.startReconnection(),this.room.isJoining&&this.emit(Se.SETUP_FAILED,new D({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(f.MAIN),this.unbindAndCloseSocket(f.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(Se.SETUP_FAILED,new D({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;let{isOnline:t}=this;this._lastMessageTime=Date.now(),t||this.emit(Se.ONLINE),this.bytesReceived+=qs(e.data);let r=JSON.parse(e.data),{cmd:s,data:n}=r,a=Object.values(qt),l=Object.keys(qt)[a.indexOf(s)],u=G[l]||s;switch(r_.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),u&&this._log.info(`Received event: [ ${u} ]`)),s){case qt.CHANNEL_SETUP_RESULT:{if(r.code===0)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,n.svrTime&&da(n.svrTime-new Date().getTime()),this._log.info(`ChannelSetup Success ${U()-this._connectStartTime}`),v.addSuccessEvent({key:521701,cost:U()-this._connectStartTime}),this._connectStartTime=-1,this.emit(Se.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let m=new D({code:I.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:r.code,message:H({key:F.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:r.code,errorMsg:r.message}})});this._log.error(`${r.code}, ${r.message}`),this.close(),v.addFailedEvent({key:521701,error:m}),this.emit(Se.SETUP_FAILED,m)}break}case qt.JOIN_ROOM_RESULT:{r.code===0&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.bakRelayIps=n.bakRelayIps,this._signalInfo.relayPort=n.relayPort,this._signalInfo.tinyId=r.tinyId,this._signalInfo.endReportExtend=n.endReportExtend,this._signalInfo.reportToken=n.reportToken,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(u,{data:r});break}default:this.emit(String(u),{data:r});break}}reGetSignalChannelUrl(){return p(this,null,function*(){try{if(!this.room.joinParams)return;Lt(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?f.MAIN:f.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return p(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive){this.close();return}this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:r,relayInnerIp:s,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:Y.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:s,relayOuterIp:r,relayPort:n},responseCommand:G.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),v.addSuccessEvent({key:521702,cost:U()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(v.addFailedEvent({key:521702,error:a.code}),this._log.warn(`reconnect failed, ${a.code} ${a.message}`),this.room.reJoin())}catch(e){this._log.error(e),this.room.reJoin()}}})}send(e,t={}){if(this.isConnected&&!this.room.isLeft){let r={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},s=JSON.stringify(r);return this._socketInUse.send(s),this.bytesSent+=qs(s),r.seq}}sendWaitForResponse({command:e,data:t,timeout:r=5e3,responseCommand:s,commandDesc:n,enableLog:a=!0,addReceiveTime:c=!1}){return new Promise((l,u)=>{let m=()=>{clearTimeout(h),u(new D({code:I.API_CALL_ABORTED,message:`${e} aborted due to connection closed`}))};this.once(Se.CLOSE,m);let h=setTimeout(()=>{this.off(s,_),this.off(Se.CLOSE,m);let E=new D({code:I.API_CALL_TIMEOUT,message:H({key:F.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(E),u(E)},r),_=E=>{E.data.seq===g&&(clearTimeout(h),this.off(s,_),this.off(Se.CLOSE,m),c&&(E.data.receiveTime=Date.now()),l(E))};this.on(s,_);let g=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:r,retries:s=0,retryTimeout:n=0}=e;return Ai({retryFunction:this.sendWaitForResponse,onError:({retry:a,reject:c,error:l})=>{!this.room.isJoined||this.destroyed||l.code===I.API_CALL_ABORTED?c(l):this.isOnline?a():(this._log.warn(`retry ${r} when connected`),this.once(Se.ONLINE,a))},onRetrying:a=>{this._log.warn(`${t||r} timeout observed, retrying [${a}/${s}]`)},settings:{retries:s,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),bd.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,bakRelayIps:[],endReportExtend:void 0,reportToken:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(f.MAIN),this.unbindAndCloseSocket(f.BACKUP),this.emitConnectionStateChanged("DISCONNECTED"),this.emit(Se.CLOSE)}destroy(){this.close(),this.destroyed=!0}getBackupRelayIpPair(){var t;let e=(t=this._signalInfo.bakRelayIps)==null?void 0:t.shift();return e&&(e.relayPort=e.relayPort||this._signalInfo.relayPort),e}clearBakRelayIps(){this._signalInfo.bakRelayIps=[]}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(G.JOIN_ROOM_RESULT,t)},e*1e3);let t=r=>{r.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(G.JOIN_ROOM_RESULT,t))};this.on(G.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(Se.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(Se.CONNECTED):e==="DISCONNECTED"&&this.emit(Se.DISCONNECTED))}};M([Mt({settings:{retries:1/0,timeout:2e3},onError(e,t){!this.room.isDestroyed&&!this.destroyed&&(this._isFirstConnect&&(v.addFailedEvent({key:521720,error:e}),this._isFirstConnect=!1),t())},onRetrying(e,t){this._log.warn(`retrying to connect ${e}`),e>=3&&e%3===0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,(this.room.isDestroyed||this.destroyed)&&t())}})],bs.prototype,"connect",1);var n_=Ge(at());var jh=0,Xh=!1,vd=new Set,iI=o=>jh>2&&!Xh&&vd.size===0&&o,zh=!1,pt=class{constructor(i){d(this,"userId");d(this,"tinyId");d(this,"_sdpSemantics");d(this,"_isUplink");d(this,"_room");d(this,"_log");d(this,"_signalChannel");d(this,"_isErrorObserved",!1);d(this,"_waitForPeerConnectionConnectedPromise");d(this,"_waitForPeerConnectionConnectedPromiseReject",null);d(this,"_peerConnection",null);d(this,"_emitter",new n_.default);d(this,"_currentState","DISCONNECTED");d(this,"_isReconnecting",!1);d(this,"_reconnectionCount",0);d(this,"_reconnectionTimer",-1);d(this,"_isFirstConnection",!0);d(this,"_prevTime",-1);d(this,"_localAddress");d(this,"_remoteAddress");this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=i.room.getLogger().createChild({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=U())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,v.addSuccessEvent({key:521705,cost:Math.min(U()-this._prevTime,30*1e3)})):this._isReconnecting&&v.addSuccessEvent({key:521706,cost:U()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,v.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&v.addFailedEvent({key:521706,error:i}),i}}initialize(){let i={iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(i),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(i){this._log.info("close connection"),this._emitter.emit("closed",i),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),vd.delete(this)}closePeerConnection(i=!1){this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,i&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new D({code:I.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return Qt;let i=null;if(this._isUplink){if(!Rr()||this._peerConnection.getSenders().length===0)return Qt;i=this._peerConnection.getSenders()[0].transport}else{if(!oo()||this._peerConnection.getReceivers().length===0)return Qt;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:Qt}onConnectionStateChange(i){let e=this._peerConnection.iceConnectionState,t=this.getDTLSTransportState();if(this._log.info(`connectionState: ${i.target.connectionState}, ICE: ${e}, DTLS: ${t}`),i.target.connectionState===Ce.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===Ce.FAILED||i.target.connectionState===Ce.CLOSED){let r=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,s=new D({message:r,code:I.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",s)}(i.target.connectionState===Ce.CONNECTED||i.target.connectionState===Ce.COMPLETED)&&(this.logSelectedCandidate(),se.logSuccessEvent({userId:this._room.userId,eventType:Ze.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(jh=0,Xh=!1,zh=!0,vd.add(this)):vd.delete(this),S.emit(C.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:i,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:i}),this._currentState=i,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return p(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(Cr(e)){let t=i.get(e.localCandidateId),r=i.get(e.remoteCandidateId);t&&(this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.candidateType==="relay"?`relayProtocol:${t.relayProtocol}`:""}`),this._localAddress=`${t.ip||t.address}:${t.port}`),r&&(this._log.info(`remote candidate: ${r.candidateType} ${r.protocol}:${r.ip||r.address}:${r.port}`),this._remoteAddress=`${r.protocol}:${r.ip||r.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(n),s(),i())},r=({room:a})=>{a===this._room&&(clearTimeout(n),s(),e(new D({code:I.API_CALL_ABORTED,message:H({key:F.CONNECTION_ABORTED,data:"leave room"})})))},s=()=>{S.off(C.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{s();let a=new D({code:I.API_CALL_TIMEOUT,message:"connection timeout"});jh+=1,iI(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Xh=!0,this._emitter.emit("firewall-restriction")),e(a)},Bs);S.on(C.LEAVE_SUCCESS,r,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(Se.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Hi()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new D({code:this._isUplink?I.UPLINK_RECONNECTION_FAILED:I.DOWNLINK_RECONNECTION_FAILED,message:H({key:this._isUplink?F.UPLINK_RECONNECTION_FAILED:F.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",i),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn(`reconnect() trying [${this._reconnectionCount}]`),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(Se.CONNECTED,this.reconnect,this),-1)}on(i,e,t){this._emitter.on(i,e,t)}off(i,e,t){this._emitter.off(i,e,t)}getIsReconnecting(){return this._isReconnecting}get isH264(){var i,e;return!!((e=(i=this._peerConnection)==null?void 0:i.remoteDescription)!=null&&e.sdp.includes("H264"))}setOffer(i){var e;return(e=this._peerConnection)==null?void 0:e.setLocalDescription(i)}setAnswer(i){var e;return(e=this._peerConnection)==null?void 0:e.setRemoteDescription(i)}};M([Rt(521712,!1)],pt.prototype,"setOffer",1),M([Rt(521713,!1)],pt.prototype,"setAnswer",1);var Kh=Ge(Zh());var De=function(o){return Kh.default.parse(o)},Jt=function(o){return Kh.default.write(o)},p_=function(o){let i=De(o);return i.media.forEach(e=>{e.type===f.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),Jt(i)};function f_(o){let i=De(o);return i.media.forEach(e=>{var t,r;if(e.type===f.VIDEO){let s=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&s.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let l=c.match(/apt=(\d+)/);l&&l[1]&&s.has(Number(l[1]))&&s.add(a)});let n=({payload:a})=>!s.has(a);e.rtp=e.rtp.filter(n),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=(r=e.payloads)==null?void 0:r.split(" ").filter(a=>!s.has(Number(a))).join(" ")}}),Jt(i)}function Nd(o){return Object.keys(o).filter(i=>o[i])}var Ns=class Ns extends pt{constructor(e){super(L(O({},e),{isUplink:!1}));d(this,"_flag",0);d(this,"isRobot",!1);d(this,"role","anchor");d(this,"remoteAudioTrack");d(this,"remoteVideoTrack");d(this,"remoteAuxiliaryTrack");d(this,"ssrc",{audio:0,video:0,auxiliary:0});d(this,"_isSDPExchanging",!1);d(this,"_videoCodec");this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new gi(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new Oi(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Es(this._room,this)}get videoCodec(){var t,r;let e=(r=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:r.sdp;return e?e.includes("H264")?"h264":"vp8":this._videoCodec||"h264"}set videoCodec(e){this._videoCodec=e}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return Kt(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,s;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(s=this.remoteAuxiliaryTrack)==null||s.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===f.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var s,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((s=this.remoteVideoTrack)==null||s.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){let t=e.streams[0],{track:r}=e,s=t.id===Fs?f.MAIN:f.AUXILIARY;this._log.debug(`ontrack ${s} ${r.kind}`);let n=f.AUDIO;r.kind===f.VIDEO&&(n=s===f.MAIN?f.VIDEO:f.AUXILIARY);let a=this.remoteAudioTrack;n===f.VIDEO?a=this.remoteVideoTrack:n===f.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(r)}addRRTRLine(e){let t=e.split(`\r
|
|
69
69
|
`),r=new Map;t.forEach((n,a)=>{/^a=rtcp-fb:/.test(n)&&t[a+1]&&!/^a=rtcp-fb:/.test(t[a+1])&&r.set(a+1,`${n.match(/^a=rtcp-fb:\d+/)[0]} rrtr`)});let s=[...r];for(let n=0;n<s.length;n++){let[a,c]=s[n];t.splice(a+n,0,c)}return t.join(`\r
|
|
70
70
|
`)}addSPSDescription(e){let t=De(e);return t.media.forEach(r=>{r.type===f.VIDEO&&r.fmtp.forEach(s=>{s.config+=";sps-pps-idr-in-keyframe=1"})}),Jt(t)}removeSDESDescription(e){let t=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],r=De(e);return r.media.forEach(s=>{s.ext&&(s.ext=s.ext.filter(n=>!t.includes(n.uri)))}),Jt(r)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return p(this,null,function*(){var r,s;try{if((((r=this._peerConnection)==null?void 0:r.connectionState)===Ce.NEW||((s=this._peerConnection)==null?void 0:s.connectionState)===Ce.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e)){this._peerConnection||(this.initialize(),yield this.connect(e));return}if(this._log.info(`subscribe ${t} ${JSON.stringify(e)}`),this._peerConnection||this._isSDPExchanging){let n="subscribe_change";Object.values(e).find(a=>a===!0)||(n="unsubscribe"),yield this.sendSubscription(n,e)}else this.initialize(),yield this.connect(e)}catch(n){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${n.message} ${JSON.stringify(this.muteState)}`),new D({code:I.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}unsubscribe(r){return p(this,arguments,function*({remoteTracks:e,streamType:t}){if(this._currentState==="CONNECTED"&&(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed)){this._log.info(`${t} stream already unsubscribed`);return}let s=O({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:s.audio=!1;break;case 4:s.video=!1;break;case 8:s.smallVideo=!1;break;case 2:s.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(s).find(a=>a===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${Nd(s)}]`),yield this.sendSubscription(n,s),n==="unsubscribe"&&(this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},s=Y.UNSUBSCRIBE,n=G.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},s=Y.SUBSCRIBE_CHANGE,n=G.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:s,data:r,responseCommand:n,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new D({code:a.code,message:H({key:F.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}connect(){return p(this,arguments,function*(e=this.subscribeState){try{yield this.exchangeSDP(e),yield this.waitForPeerConnectionConnected()}catch(t){throw this.closePeerConnection(!0),t}})}exchangeSDP(e){return p(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:r}=this._peerConnection.localDescription,s={type:t,sdp:r,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:Y.SUBSCRIBE,commandDesc:"exchange sdp",data:s,responseCommand:G.SUBSCRIBE_RESULT,timeout:il});if(!this._peerConnection){let a=new D({code:I.INVALID_OPERATION,message:H({key:F.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return p(this,null,function*(){let e={voiceActivityDetection:!1};St()&&this._sdpSemantics===gr?(this._peerConnection.addTransceiver(f.AUDIO,{direction:ne.RECVONLY}),this._peerConnection.addTransceiver(f.VIDEO,{direction:ne.RECVONLY}),this._peerConnection.addTransceiver(f.VIDEO,{direction:ne.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:r}=yield fc();r||(this._log.warn("remove h264 desc from sdp"),t.sdp=f_(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=p_(t.sdp),this._sdpSemantics===gr&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)})}onSubscribeResult(e){return p(this,null,function*(){let{code:t,message:r=""}=e&&e.data||{},{type:s,sdp:n}=e&&e.data&&e.data.data||{};if(t===Hr)throw new D({code:I.NOT_SUPPORTED_H264,message:H({key:F.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new D({code:t,message:H({key:F.EXCHANGE_SDP_FAILED,data:{errMsg:r}})});this._log.debug(`accept remote answer: ${n}`),yield this.setAnswer({type:s,sdp:n}),this.updateSSRC(n)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{De(e).media.forEach(r=>{if(r.ssrcs)if(r.type===f.AUDIO){let s=r.ssrcs.find(n=>{var a;return(a=n.value)==null?void 0:a.includes(Fs)});s&&(this.ssrc.audio=Number(s.id))}else{let s=r.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(Fs)}),n=r.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(Yd)});s&&(this.ssrc.video=Number(s.id)),n&&(this.ssrc.auxiliary=Number(n.id))}})}catch(t){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return p(this,null,function*(){if(!(Pe(Ns.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(t){let r=Zt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${r/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},r)}})}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}get audioReceiver(){var e;return((e=this._peerConnection)==null?void 0:e.getReceivers()[0])||null}};M([Q(e=>function(...t){return new Promise((r,s)=>{let n=a=>{this._emitter.off("closed",n),s(new D({code:I.API_CALL_ABORTED,message:H({key:F.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,s).finally(()=>{this._emitter.off("closed",n)})})})],Ns.prototype,"subscribe",1),M([Rt(521717,!1)],Ns.prototype,"unsubscribe",1),M([Ct(pt.prototype.afterConnect),Mc(pt.prototype.beforeConnect)],Ns.prototype,"connect",1);var em=Ns,tm=em;var g_={voiceActivityDetection:!1},Ds=class Ds extends pt{constructor(e){super(L(O({},e),{isUplink:!0}));d(this,"localMainAudioTrack",null);d(this,"localMainVideoTrack",null);d(this,"localAuxAudioTrack",null);d(this,"localAuxVideoTrack",null);d(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});d(this,"_isPublishingAux",!1);d(this,"_publishingLocalAudioTrack");d(this,"_publishingLocalVideoTrack");d(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});d(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var n,a,c;let r=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:r,state:e}))),s}publish(s){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),t&&(this._publishingLocalVideoTrack=t),this._isPublishingAux=r;let n;t&&!r&&t.small&&(n=this._room.videoManager.smallTrack),this.sendMediaSettings(),St()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:r}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:n}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,r?(t&&(this.localAuxVideoTrack=t),e&&(this.localAuxAudioTrack=e)):(t&&(this.localMainVideoTrack=t),e&&(this.localMainAudioTrack=e)),this.installTrackMuteEvents(e,t),this.sendMutedFlag()})}publishByTransceiver(n){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:s}){this._log.info("publish by transceiver");let a=new MediaStream,c=t==null?void 0:t.outMediaTrack,l=e==null?void 0:e.outMediaTrack;l&&a.addTrack(l),c&&a.addTrack(c);let u=this._peerConnection.getTransceivers();if(u.length===0)this._peerConnection.addTransceiver(l||f.AUDIO,{direction:ne.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s?f.VIDEO:c||f.VIDEO,{direction:ne.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(r||f.VIDEO,{direction:ne.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s?c||f.VIDEO:f.VIDEO,{direction:ne.SENDONLY,streams:[a]}),yield this.connect();else{let m=[];if(l&&(u[0].sender.track||m.push(0),yield u[0].sender.replaceTrack(l),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:f.AUDIO})),c){let h=s?3:1;yield u[h].sender.replaceTrack(c),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:f.VIDEO,videoType:s?f.AUXILIARY:f.BIG}),m.push(h),r&&(yield u[2].sender.replaceTrack(r),yield this.setBandwidth({bandwidth:t.small.bitrate,type:f.VIDEO,videoType:f.SMALL}),m.push(2))}yield this.setTransceiverDirection(ne.SENDONLY,m),yield this.doPublishChange(),t==null||t.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),t==null||t.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}})}publishByAddTrack(s){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r}){this._log.info("publish by addtrack");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack;if(this._peerConnection&&this._peerConnection.connectionState!=="new"){e&&a&&(yield this.addTrack(e)),n&&(yield this.addTrack(t));return}let c=new MediaStream;if(a&&c.addTrack(a),n&&c.addTrack(n),a&&this._peerConnection.addTrack(a,c),n&&(this._peerConnection.addTrack(n,c),r)){let l=new MediaStream;l.addTrack(r),this._peerConnection.addTrack(r,l)}yield this.connect()})}enableSmall(e){return p(this,null,function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(ne.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(ne.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!yr()){if(e&&e.outMediaTrack&&!t&&this.localMainVideoTrack){yield this.removeTrack(e),this.localMainAudioTrack=null;return}if(t&&t.outMediaTrack&&!e&&this.localMainAudioTrack){yield this.removeTrack(t),this.localMainVideoTrack=null;return}yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),this.emitConnectionStateChangedEvent("DISCONNECTED",t);return}let s=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(s?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localAuxAudioTrack&&!this.localMainAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(s?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=L(O({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=L(O({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(ne.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return p(this,null,function*(){let t={state:this._room.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponse({command:Y.PUBLISH_STATE_CHANGE,data:t,responseCommand:G.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:Y.UNPUBLISH,commandDesc:"unpublish",responseCommand:G.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===I.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let r=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:s,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:s=this._publishingLocalVideoTrack),yi){if(r&&r.outMediaTrack){let a=r.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(s&&s.outMediaTrack){let a=s.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=s.profile.bitrate*1e3,s.small&&(this._mediaSettings.smallVideoWidth=s.small.width,this._mediaSettings.smallVideoHeight=s.small.height,this._mediaSettings.smallVideoFps=s.small.frameRate,this._mediaSettings.smallVideoBps=s.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else r&&r.outMediaTrack&&(this._mediaSettings.audioChannel=r.profile.channelCount,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=r.profile.sampleRate),s&&s.outMediaTrack&&(this._mediaSettings.videoWidth=s.profile.width,this._mediaSettings.videoHeight=s.profile.height,this._mediaSettings.videoFps=s.profile.frameRate,this._mediaSettings.videoBps=s.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Y.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:G.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return p(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?f.AUXILIARY:f.MAIN} stream`),St()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return p(this,null,function*(){var s;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===f.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((s=this.localMainVideoTrack)!=null&&s.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===ne.INACTIVE&&(yield this.setTransceiverDirection(ne.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return p(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;yr()&&this._peerConnection.getTransceivers().findIndex(s=>s.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let r=this._peerConnection.getSenders().find(s=>s.track&&s.track.kind===t.kind);if(r&&r.track){this._log.warn("sender already exists, remove sender first");let s=r.track;this.removeSender(r),yield this.updateOffer("remove",s)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===f.VIDEO&&e instanceof je&&e.small){let s=new MediaStream,{smallTrack:n}=this._room.videoManager;s.addTrack(n),this._peerConnection.addTrack(n,s)}yield this.updateOffer("add",t)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===Mo||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=De(e);for(let r=0;r<t.media.length;r++)if(Number(t.media[r].mid)===0&&t.media[r].type===f.VIDEO)return!0;return!1}removeSender(e){let t=null;yr()&&(t=this._peerConnection.getTransceivers().find(r=>r.sender&&r.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&le(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return p(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?f.AUXILIARY:f.MAIN} stream`),St()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return p(this,null,function*(){if(!e.outMediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===f.AUDIO)yield r[0].sender.replaceTrack(null);else{let s=t?3:1;yield r[s].sender.replaceTrack(null),s===1&&e.small&&(yield r[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(ne.INACTIVE,[s])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return p(this,null,function*(){if(!K)return;let r=!1,s=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let n=this._peerConnection.getTransceivers();if(t.forEach(l=>{n[l].direction!==e&&(n[l].direction=e,r=!0)}),r){this._log.info("updating offer");let l=yield this._peerConnection.createOffer();yield this.setOffer(l)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
|
|
71
71
|
`).map(l=>{if(l.match(new RegExp(`a=(${ne.INACTIVE}|${ne.RECVONLY}|${ne.SENDONLY})`))&&a++,t.includes(a)){if(e===ne.INACTIVE&&l.includes(`a=${ne.RECVONLY}`))return s=!0,`a=${e}`;if(e===ne.SENDONLY&&l.includes(`a=${ne.INACTIVE}`))return s=!0,`a=${ne.RECVONLY}`}return l}).join(`\r
|
|
@@ -119,4 +119,4 @@ offer: ${t==null?void 0:t.sdp}`),s}})}setIceServers(e){return p(this,null,functi
|
|
|
119
119
|
next offer: ${this.filterSDPDirection(e==null?void 0:e.sdp)}`),this._log.warn(`current answer: ${this.filterSDPDirection((a=this._peerConnection.remoteDescription)==null?void 0:a.sdp)}
|
|
120
120
|
next answer: ${this.filterSDPDirection(t)}`),this._log.warn(`offer: ${e==null?void 0:e.sdp}`),this._log.warn(`answer: ${t}`),this._log.warn(`transceivers: ${JSON.stringify(this._peerConnection.getTransceivers().map(({mid:l,currentDirection:u,direction:m,stopped:h})=>({mid:l,currentDirection:u,direction:m,stopped:h})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._isSDPLogged=!0),this._updateSDPPromise=null,s(c)}})),this._updateSDPPromise}setTransceiverDirection(e,t){return p(this,null,function*(){if(!K||!this._peerConnection||!this._parsedAnswer)return;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let r=this._peerConnection.getTransceivers();t.forEach(s=>{r[s].direction!==e&&(r[s].direction=e)});for(let s of t){let n=this._parsedAnswer.media[s].direction;e===ne.INACTIVE&&n===ne.RECVONLY&&(this._parsedAnswer.media[s].direction=e),e===ne.SENDONLY&&n===ne.INACTIVE&&(this._parsedAnswer.media[s].direction=ne.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(e=""){return De(e).media.map(r=>r.direction)}setOffer(e){this._log.info("setting offer");let t=O_(e.sdp,this.clientAbility,this._serverAbility);return this._log.debug(t),this._peerConnection.setLocalDescription({type:"offer",sdp:t})}setAnswer(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._peerConnection.setRemoteDescription(e)}switchVideoEncoder(e){return p(this,null,function*(){if(e==="h265"&&!this._parsedAnswer&&(this._parsedAnswer=De(this._peerConnection.remoteDescription.sdp)),!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach(r=>{var s;if(r.type===f.VIDEO){let n=this._serverAbility.video.codecs.find(a=>a.codec.toLowerCase()===e);n&&!((s=r.payloads)!=null&&s.includes(String(n.payload)))&&(r.fmtp=[],r.payloads="",r.rtp=[],r.rtcpFb=[],Vr(r,n),t=!0)}}),t&&(this._log.warn(`switch video encoder to ${e}`),yield this.updateSDP())})}useHWEncoder(e=!0,t){return p(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let r=!1,s=[];T(t)?s=this._parsedAnswer.media.slice(1,4):t===2?s.push(this._parsedAnswer.media[1]):t===3?s.push(this._parsedAnswer.media[2]):t===7&&s.push(this._parsedAnswer.media[3]),s.forEach(n=>{var a;if(n.type===f.VIDEO){let c;e&&this.is42001fSupported?c=this.clientAbility.video.codecs.find(l=>l.fmtp.includes("42001f")):e||(c=this._serverAbility.video.codecs.find(l=>l.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264"))),c&&!((a=n.payloads)!=null&&a.includes(String(c.payload)))&&(n.fmtp=[],n.payloads="",n.rtp=[],n.rtcpFb=[],Vr(n,c),r=!0)}}),r&&(this._log.warn(`use ${e?"hw":"sw"} encoder`),yield this.updateSDP())})}setProfileLevelId(e="42e01f",t){return p(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let r=!1,s=[];T(t)?s=this._parsedAnswer.media.slice(1,4):t===2?s.push(this._parsedAnswer.media[1]):t===3?s.push(this._parsedAnswer.media[2]):t===7&&s.push(this._parsedAnswer.media[3]),s.forEach(n=>{var a;if(n.type===f.VIDEO){let c;e&&(c=this.clientAbility.video.codecs.find(l=>l.fmtp.includes(e))),c&&!((a=n.payloads)!=null&&a.includes(String(c.payload)))&&(n.fmtp=[],n.payloads="",n.rtp=[],n.rtcpFb=[],Vr(n,c),r=!0)}}),r&&(this._log.warn(`use ${e}`),yield this.updateSDP())})}sendDataChannelMessage(e){var t;(t=this._datachannel)==null||t.send(e)}reset(){var e;this._peerConnection&&(this._peerConnection.close(),this._peerConnection.removeEventListener("track",this._peerConnection._onaddstreampoly,this),this._peerConnection._onaddstreampoly=null,this._peerConnection=null),(e=this.clearWaitForConnectedPromise)==null||e.call(this),this._parsedAnswer=null,this.originOffer=null}close(){this._log.info("close pc"),this.isDestroyed=!0,this.removeRTCListener(),this.insertableStreamsAbortMap.forEach(e=>Ii(e.abort)&&e.abort("destroy")),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners(),this._room.healthDetector.off("1",this.onBadHealth,this)}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map(r=>t[r])}get isUsingRelay(){return this._room.getIceTransportPolicy()==="relay"}detectTCPAndUDP({uplinkRTT:e,downlinkRTT:t}){var u;if(this.currentState!=="CONNECTED"||this._isRelayTried&&!this._room.forceRelay||this._room.getIceServers().length===0)return;let r=this._signalChannel.rtt,s=Math.max(e,t),{rttRatioThreshold:n,rttThreshold:a}=((u=this._room.scheduleResult.config)==null?void 0:u.useTurnTcpInfo)||{};if(!n||!a||!r||!s)return;let c=Math.floor(s/r),l=(this._isRelayTried||c>n)&&s>a;if(!l){this._rttOverCount=0;return}++this._rttOverCount<5||(this._log.warn(`detectTCPAndUDP ws-rtt: ${r} upRTT: ${e} downRTT: ${t} ratio: ${c} over-count: ${this._rttOverCount} isOver: ${l} isRelayTried: ${this._isRelayTried} force-relay: ${this._room.forceRelay}`),!this.isUsingRelay&&!this._isRelayTried?(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0)):this._room.forceRelay&&this.switchRelay(!1))}switchRelay(e,t=!1){return p(this,null,function*(){if(this.isUsingRelay===e)return;let r=e?"relay":"udp",s=e?521709:521710;try{this._room.forceRelay=e,this._log.warn(`switchRelay ${r}`);let n=Date.now();yield this.doSwitchRelay(r),this._log.warn(`switchRelay ${r} success`),v.addSuccessEvent({key:s,cost:Date.now()-n})}catch(n){this._log.warn(`switchRelay ${r} failed`,n),v.addFailedEvent({key:s,error:n}),t?this._room.reJoin():yield this.switchRelay(!e,!0)}})}doSwitchRelay(e){return new Promise((t,r)=>{let s=setTimeout(()=>{this.stopReconnection(),r(new Error(`switch ${e} timeout`))},1e4);this.startReconnection().then(t,r).finally(()=>clearTimeout(s))})}removeRTCListener(){this._peerConnection&&(this._peerConnection.oniceconnectionstatechange=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.onsignalingstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}requestRemoteFallbackToH264(){this._log.warn("H265 decode failed, remote need to fallback h264"),this._h265DecodeFailed=!0,this._signalChannel.sendWaitForResponse({command:Y.UPDATE_CONSTRAINT_CONFIG,data:{videoDecCodec:"h264"},responseCommand:G.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)})}};M([Lc("reconnect")],jt.prototype,"startReconnection",1),M([_i(e=>e.userId)],jt.prototype,"addDownlink",1),M([_i(e=>e)],jt.prototype,"removeDownlink",1),M([ir(!0)],jt.prototype,"updateSDP",1),M([Rt(521712,!1),Eo(10,0)],jt.prototype,"setOffer",1),M([Rt(521713,!1),Eo(10,0)],jt.prototype,"setAnswer",1),M([Tf()],jt.prototype,"close",1);var dm=class{constructor(i){d(this,"tag");d(this,"len");d(this,"data");let e=new DataView(i);this.tag=e.getUint16(),this.len=e.getUint16(2),this.data=new Uint8Array(i).slice(4,4+this.len).buffer}},lm=class{constructor(i){d(this,"tinyId");d(this,"data");let e=new DataView(i),t=0,r=[];for(;t<e.byteLength;){let s=e.getUint16(t+2),n=new dm(new Uint8Array(i).slice(t,t+2+2+s).buffer);r.push(n),t+=4+s}r.forEach(s=>{s.tag===1?this.tinyId=new TextDecoder().decode(s.data):s.tag===2&&(this.data=s.data)})}},w_=new Set;function xt(){let o=Math.floor(Math.random()*4294967296);return w_.has(o)?xt():(w_.add(o),o)}var V_=Ge(at());var bo=class extends V_.default{constructor(e){super();d(this,"userId");d(this,"tinyId");d(this,"_sdpSemantics");d(this,"_isUplink");d(this,"_room");d(this,"_log");d(this,"_currentState","DISCONNECTED");d(this,"_prevTime",-1);d(this,"_blackSmallVideoDetectionId");this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=R.createLogger({parent:this._room.getLogger(),id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink})}get _peerConnection(){var e;return((e=this.singlePC)==null?void 0:e.getPeerConnection())||null}get singlePC(){return this._room.singlePC}get _signalChannel(){return this._room.signalChannel}close(e){this._log.info("close connection"),this.emit("closed",e)}emitConnectionStateChangedEvent(e){return e===this._currentState?!1:(S.emit(C.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}getCurrentState(){return this._currentState}get isH264(){var e,t;return!!((t=(e=this._peerConnection)==null?void 0:e.remoteDescription)!=null&&t.sdp.includes("H264"))}};var um=class{constructor(){d(this,"worker");d(this,"callbacks",new Map);d(this,"_log");d(this,"sleep",{});d(this,"heartbeatListenerCleaner",new Map);d(this,"userIdMap",new Map);this._log=R.createLogger({id:"bvd"})}getWorker(){if(!this.worker){let i=`
|
|
121
121
|
const tracks=new Map;let canvas,ctx;const log=(...t)=>postMessage({type:"log",message:"[worker] "+t.join(" ")});function startDetection(e,t,a){if(!tracks.has(e)){const c={reader:a.getReader(),blackCount:0,timeoutId:null,intervalId:null};tracks.set(e,c),c.timeoutId=setTimeout(()=>stopDetection(e,"timeout"),t),c.intervalId=setInterval(async()=>{try{await isFrameBlack(e)?(c.blackCount++,postMessage({type:"blackCount",trackId:e,count:c.blackCount}),3<=c.blackCount&&(postMessage({type:"black",trackId:e}),stopDetection(e,"black"))):c.blackCount=0}catch(t){log("check black video error:",t.message),stopDetection(e,"error")}},1e3)}}function stopDetection(t,e){var a=tracks.get(t);a&&(a.timeoutId&&clearTimeout(a.timeoutId),a.intervalId&&clearInterval(a.intervalId),a.reader&&a.reader.cancel(),tracks.delete(t),postMessage({type:e,trackId:t}))}async function isFrameBlack(t){t=tracks.get(t);if(!t)return!1;var t=t.reader,{done:t,value:e}=await t.read();if(!e||t)return!1;canvas||(canvas=new OffscreenCanvas(e.codedWidth,e.codedHeight),ctx=canvas.getContext("2d",{willReadFrequently:!0})),canvas.width===e.codedWidth&&canvas.height===e.codedHeight||(canvas.width=e.codedWidth,canvas.height=e.codedHeight,ctx=canvas.getContext("2d",{willReadFrequently:!0})),ctx.drawImage(e,0,0,canvas.width,canvas.height);t=getFrameBlackRatio(ctx.getImageData(0,0,canvas.width,canvas.height));return e.close(),1===t}function getFrameBlackRatio(t){var e=t.data;let a=0;for(let t=0;t<100;t++){var c=4*Math.floor(Math.random()*(e.length/4)),[c,r,n,o]=[e[c],e[1+c],e[2+c],e[3+c]];0<o&&0===c&&0===r&&0===n&&a++}return a/100}self.onmessage=t=>{var{type:t,trackId:e,timeout:a,readable:c}=t.data;"addTrack"===t&&startDetection(e,a,c),"removeTrack"===t&&stopDetection(e)};
|
|
122
|
-
`,e=new Blob([i],{type:"application/javascript"}),t=URL.createObjectURL(e);this.worker=new Worker(t),URL.revokeObjectURL(t),this.worker.onerror=r=>this._log.warn("worker error:",r.message,r.filename||"unknown",r.lineno||"unknown"),this.worker.onmessage=r=>{var l;let{type:s,trackId:n,message:a,count:c}=r.data;if(s==="black")(l=this.callbacks.get(n))==null||l();else if(s==="log")this._log.warn(a);else if(s==="blackCount"){let u=this.userIdMap.get(n);this._log.warn(`${u||n} black count: ${c}`)}}}return this.worker}start({track:i,isUplink:e,room:t,userId:r,onBlack:s}){if(this._log.debug("start detect black video",i.id),!fn()||!s||!i||typeof Worker=="undefined"){this._log.warn("black video detector not supported");return}let n=a=>{var l,u,m,h;let c;if(e)c=(u=(l=a.msg_up_stream_info)==null?void 0:l.msg_video_status)==null?void 0:u.filter(_=>_.uint32_video_stream_type===3)[0];else{let _=(m=a.msg_down_stream_info)==null?void 0:m.filter(g=>{var E;return((E=g.msg_user_info)==null?void 0:E.str_identifier)===r})[0];c=(h=_==null?void 0:_.msg_video_status)==null?void 0:h.filter(g=>g.uint32_video_stream_type===3)[0]}if(c){let _=(c.uint32_video_codec_bitrate||0)/1e3;if(this.sleep[i.id]&&this.sleep[i.id]>0){this.sleep[i.id]-=1;return}_>0&&_<10&&(this.sleep[i.id]=30,this._log.info("track bitrate",_,"start check"),this.checkOnce(i,30*1e3))}};return t.on("heartbeat-report",n),this.heartbeatListenerCleaner.set(i.id,()=>t.off("heartbeat-report",n)),this.callbacks.set(i.id,s),this.userIdMap.set(i.id,r),i.id}checkOnce(i,e){try{let t=this.getWorker();if(!t)throw new Error("Worker not available");let r=new MediaStreamTrackProcessor({track:i});t.postMessage({type:"addTrack",trackId:i.id,timeout:e,readable:r.readable},[r.readable])}catch(t){this._log.warn("check error:",t),this.stop(i.id)}}stop(i){if(i){this.worker&&this.worker.postMessage({type:"removeTrack",trackId:i}),this.callbacks.delete(i),delete this.sleep[i];let e=this.heartbeatListenerCleaner.get(i);e&&e(),this.heartbeatListenerCleaner.delete(i),this.userIdMap.delete(i)}}destroy(){this.callbacks.forEach((i,e)=>this.stop(e)),this.worker&&(this.worker.terminate(),this.worker=null)}},ur=new um;var Ud=class extends bo{constructor(e){super(L(O({},e),{isUplink:!0}));d(this,"localMainAudioTrack",null);d(this,"localMainVideoTrack",null);d(this,"localAuxAudioTrack",null);d(this,"localAuxVideoTrack",null);d(this,"_isPublishingAux",!1);d(this,"_publishingLocalAudioTrack");d(this,"_publishingLocalVideoTrack");d(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,videoDecCodec:"",audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});d(this,"_flag",0);d(this,"_checkPublishStateTimeoutId",-1);this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:r,smallVideoSsrc:s,smallVideoRtxSsrc:n,auxVideoSsrc:a,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:r||0,small:s||0,smallRtx:n||0,auxiliary:a||0,auxiliaryRtx:c||0}}get flag(){return this._flag}set flag(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}checkPublishState(e=!1){try{if(!e&&this._checkPublishStateTimeoutId>0)return;let{serverPublishState:t}=this,{publishState:r}=this._room,s=Object.keys(r).filter(n=>{if(r[n]!==t[n]&&r[n])switch(n){case"audio":return!(!this.localMainAudioTrack||!this.localMainAudioTrack.isMediaTrackActive);case"bigVideo":case"smallVideo":return!(!this.localMainVideoTrack||!this.localMainVideoTrack.isMediaTrackActive);case"auxVideo":return!(!this.localAuxVideoTrack||!this.localAuxVideoTrack.isMediaTrackActive)}return!1});if(s.length>0){if(e)v.addCount({key:521e3}),s.forEach(n=>{this._log.warn(`${n} publish failed during call ${ni()} ${si()}`),v.addEnum({key:521719,value:F_[n]})});else{this._checkPublishStateTimeoutId=oe.run("timeout",()=>this.checkPublishState(!0),{delay:10*1e3,count:1});return}oe.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}}catch(t){this._log.warn("checkPublishState failed",t)}}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get serverPublishState(){return{audio:!!(this.flag&_r),bigVideo:!!(this.flag&fr),smallVideo:!!(this.flag&Vs),auxVideo:!!(this.flag&Br)}}initialize(){this.installEvents()}close(e){var r;let t=((r=this._peerConnection)==null?void 0:r.getSenders())||[];for(let s of t)s.replaceTrack(null);super.close(e),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}installSPCEvents(){var e,t;(e=this.singlePC)!=null&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(t=this.singlePC)==null||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallSPCEvents(){var e;(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}emitConnectionStateChangedEvent(e,t){var n,a,c;let r=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:r,state:e}))),s}onVideoEncodeFailed(e){return p(this,null,function*(){if(!e||!e.isMediaTrackActive)return;let{videoCodec:t,singlePC:r}=this;if(!r)return;let s={h265:{supported:r.isH264EncodeSupported,target:"h264",log:"h265 encoder not working"},h264:{supported:r.isVP8EncodeSupported,target:"vp8",log:"h264 encoder not working"},vp8:{supported:!1,target:"vp8",log:"vp8 encoder not working, no fallback available"}};if(t==="vp9"||t==="av1")return;let n=s[t];this._log.warn(n.log),n!=null&&n.supported&&(yield r.switchVideoEncoder(n.target))})}publish(s){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){var c,l,u,m,h,_,g;if(!this.singlePC)return;if(this.installEvents(),this.installTrackMuteEvents(e,t),t&&(t.retryEncodeFailed=this.onVideoEncodeFailed.bind(this)),yield this.singlePC.waitForPeerConnectionConnected(),e&&(this._publishingLocalAudioTrack=e),t){if(!this.singlePC.isH264EncodeSupported&&!this.singlePC.isVP8EncodeSupported)throw new D({code:I.NOT_SUPPORTED_H264,message:H({key:F.NOT_SUPPORTED_H264ENCODE})});this.singlePC.isUsingH264&&!this.singlePC.isH264EncodeSupported&&this.singlePC.isVP8EncodeSupported&&(this._log.warn("h264 encoder not supported"),yield this.singlePC.switchVideoEncoder("vp8")),_e&&Yo()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn(`fallback video to defaultBigVideoProfile: ${JSON.stringify(pr)}`),t.setProfile(pr),yield t.applyProfile()),this._publishingLocalVideoTrack=t}this._isPublishingAux=r;let n;if(t&&!r&&t.small&&(n=this._room.videoManager.smallTrack),yield this._signalChannel.sendWaitForResponseWithRetry({command:Y.SPC_PUBLISH,responseCommand:G.SPC_PUBLISH_RESULT,data:L(O({},this.singlePC.uplinkSSRC),{state:this._room.publishState,muteState:this._room.muteState}),retries:3}),yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:r}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,t){this[r?"localAuxVideoTrack":"localMainVideoTrack"]=t,yield this.singlePC.setDegradationPreference(this._peerConnection.getSenders()[r?3:1],t.contentHint,t.streamType);let{scaleResolutionDownBy:E}=t;yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[r?3:1],E,t.streamType)}e&&(this[r?"localAuxAudioTrack":"localMainAudioTrack"]=e),yield this.singlePC.setBandwidth({audio:((c=this.localMainAudioTrack)==null?void 0:c.profile.bitrate)||((l=this.localAuxAudioTrack)==null?void 0:l.profile.bitrate),bigVideo:(u=this.localMainVideoTrack)==null?void 0:u.profile.bitrate,smallVideo:(h=(m=this.localMainVideoTrack)==null?void 0:m.small)==null?void 0:h.bitrate,auxVideo:(_=this.localAuxVideoTrack)==null?void 0:_.profile.bitrate}),this.sendMediaSettings(),(this._room.preferHW||(g=this._room.scheduleResult.config)!=null&&g.preferHW)&&t&&t.profile.width*t.profile.height>=1280*720&&this.singlePC.useHWEncoder(!0,r?7:2);let a=new URLSearchParams(location.search).get("profileLevelId");a&&this.singlePC.setProfileLevelId(a)})}publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:s}){if(!St())return;this._log.info("publish by transceiver");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack,c=this._peerConnection.getTransceivers(),l=[],u=[],m=(_,g,E)=>{var k;let A=c[g].sender.replaceTrack(E);u.push(g),(k=this.singlePC)!=null&&k.enableInsertableStreams&&A.then(()=>this.createEncodedStreams(c[g].sender,_)),this.initSenderTransform(c[g].sender,_),l.push(A)};a&&m(e.mediaType,0,a),n&&m(t.mediaType,s?3:1,n),t!=null&&t.small&&l.push(this.publishSmall(this._room.videoManager.smallMode,t));let h=this.singlePC.setTransceiverDirection(ne.SENDONLY,u);return l.push(h),Promise.all(l)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._room.localMainAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._room.localMainVideoTrack;case 2:return this.localAuxVideoTrack||this._room.localAuxVideoTrack;default:return null}}createEncodedStreams(e,t){var a,c;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let r=e.createEncodedStreams(),s=new AbortController;(a=this.singlePC)==null||a.addAbortController(e,s),((c=this.getTrackByMediaType(t))!=null&&c.enableEncodeFrame?r.readable.pipeThrough(new TransformStream({transform:(l,u)=>{var h,_;let m=this.getTrackByMediaType(t);if(!m||!m.encodeFrame)return u.enqueue(l);m.isAudio?u.enqueue(m.enableEncodeFrame?m.encodeFrame(l):l):u.enqueue((h=this.singlePC)!=null&&h.isUsingH264||(_=this.singlePC)!=null&&_.isUsingH265?m.encodeFrame(l,t===8):l)}}),s):r.readable).pipeTo(r.writable,s).catch(l=>{this._log.debug("encoded stream error",l),l!=="destroy"&&this._log.warn(l)})}initSenderTransform(e,t){if(!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||!ss)return;let r=t!==2,s=t===8;e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:t===1,isMain:r,isSmall:s}))}enableSmall(e){return p(this,null,function*(){e?yield this.publishSmall(this._room.videoManager.smallMode):yield this.unpublishSmall()})}publishSmall(r){return p(this,arguments,function*(e,t=this.localMainVideoTrack){var l;if(!this.singlePC)return;if(e==="canvas"&&!gc()){this._log.warn("canvas mode small stream is not supported");return}let s=this._peerConnection.getTransceivers(),{sender:n}=s[2],a=yield this.doPublishSmall(e,t),c=e==="canvas"?524700:524701;if(v.addSuccessEvent({key:c}),!a){v.addFailedEvent({key:c,error:10001});return}(l=this.singlePC)!=null&&l.enableInsertableStreams&&this.createEncodedStreams(n,8),this.initSenderTransform(n,8),yield this.singlePC.setTransceiverDirection(ne.SENDONLY,[2]),this.updateMediaSettings(),yield this.doPublishChange(),n.track&&(this._blackSmallVideoDetectionId=ur.start({track:n.track,room:this._room,isUplink:!0,userId:this.userId,onBlack:()=>{this._log.warn("small video is black");let u=e==="canvas"?524700:524701;v.addFailedEvent({key:u,error:10002}),ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}}))})}doPublishSmall(r){return p(this,arguments,function*(e,t=this.localMainVideoTrack){if(!this.singlePC)return null;this._log.info("publish small",e);let s=this._peerConnection.getTransceivers(),{sender:n}=s[2];if(e==="canvas"&&this._room.videoManager.smallTrack)return yield n.replaceTrack(this._room.videoManager.smallTrack),"canvas";if(e==="api"&&(t!=null&&t.outMediaTrack)&&(t!=null&&t.small)){yield n.replaceTrack(t==null?void 0:t.outMediaTrack);let a=n.getParameters(),c=Ho(t==null?void 0:t.profile,t==null?void 0:t.small);return this._log.info("small scaleResolutionDownBy",c),a.encodings[0].scaleResolutionDownBy=c,n.setParameters(a),"api"}return this._log.warn(`small track can not be enabled, smallMode: ${this._room.videoManager.smallMode}, smallTrack: ${!!this._room.videoManager.smallTrack}, bigVideoTrack: ${!!(t!=null&&t.outMediaTrack)}`),null})}unpublishSmall(){return p(this,null,function*(){if(!this.singlePC)return;this._log.info("unpublish small"),yield this._peerConnection.getTransceivers()[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(ne.INACTIVE,[2]),this.updateMediaSettings(),yield this.doPublishChange(),ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){var l;yield(l=this.singlePC)==null?void 0:l.waitForPeerConnectionConnected();let s=t&&t===this.localAuxVideoTrack||e&&e===this.localAuxAudioTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(s?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localMainAudioTrack&&!this.localAuxAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(s?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=L(O({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=L(O({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.singlePC.setTransceiverDirection(ne.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return p(this,null,function*(){let t={state:this._room.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponseWithRetry({command:Y.PUBLISH_STATE_CHANGE,data:t,responseCommand:G.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:Y.UNPUBLISH,commandDesc:"unpublish",responseCommand:G.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===I.API_CALL_TIMEOUT||t.getCode()===I.API_CALL_ABORTED)return Promise.resolve();throw t})}updateMediaSettings(){var s,n;this._mediaSettings.videoCodec=((s=this.singlePC)==null?void 0:s.videoCodec)||"h264",this._mediaSettings.videoDecCodec=((n=this.singlePC)==null?void 0:n.downlinkVideoCodec)||"h264";let e=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:t,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:t=this._publishingLocalVideoTrack),yi){if(e&&e.outMediaTrack){let a=e.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(t&&t.outMediaTrack){let a=t.outMediaTrack.getSettings(),{scaleResolutionDownBy:c}=t;this._mediaSettings.videoWidth=(a.width||0)/c||0,this._mediaSettings.videoHeight=(a.height||0)/c||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=t.profile.bitrate*1e3,t.small&&(this._mediaSettings.smallVideoWidth=t.small.width,this._mediaSettings.smallVideoHeight=t.small.height,this._mediaSettings.smallVideoFps=t.small.frameRate,this._mediaSettings.smallVideoBps=t.small.bitrate*1e3)}if(r&&r.outMediaTrack){let a=r.outMediaTrack.getSettings(),{scaleResolutionDownBy:c}=r;this._mediaSettings.auxVideoWidth=(a.width||0)/c||0,this._mediaSettings.auxVideoHeight=(a.height||0)/c||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=r.profile.bitrate*1e3}}else e&&e.outMediaTrack&&(this._mediaSettings.audioChannel=e.profile.channelCount,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=e.profile.sampleRate),t&&t.outMediaTrack&&(this._mediaSettings.videoWidth=t.profile.width,this._mediaSettings.videoHeight=t.profile.height,this._mediaSettings.videoFps=t.profile.frameRate,this._mediaSettings.videoBps=t.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Y.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:G.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return p(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?f.AUXILIARY:f.MAIN} stream`),yr()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return p(this,null,function*(){var s;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===f.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((s=this.localMainVideoTrack)!=null&&s.small)&&this._room.videoManager.smallTrack&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===ne.INACTIVE&&(yield this.singlePC.setTransceiverDirection(ne.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(e){return p(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?f.AUXILIARY:f.MAIN} stream`),yr()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return p(this,null,function*(){if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===f.AUDIO)yield r[0].sender.replaceTrack(null);else{let s=t?3:1;yield r[s].sender.replaceTrack(null),s===1&&this._room.videoManager.hasSmall&&(yield r[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(ne.INACTIVE,[s])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(e){return p(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders(),r=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!r||t.find(a=>a.track===r))return!1;let s=e.mediaType===2||e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${r.kind} track ${r.id} ${r.label} on ${s?f.AUXILIARY:f.MAIN} stream`),r.kind===f.AUDIO&&t[0]&&(yield t[0].replaceTrack(r)),r.kind===f.VIDEO&&(!s&&t[1]&&(yield t[1].replaceTrack(r)),s&&t[3]&&(yield t[3].replaceTrack(r))),!0})}setBandwidth(s){return p(this,arguments,function*({bandwidth:e,type:t,videoType:r}){if(this.singlePC){let n={};t===f.AUDIO?n.audio=e:r==="big"?n.bigVideo=e:r==="small"?n.smallVideo=e:n.auxVideo=e,yield this.singlePC.setBandwidth(n)}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info(`send muted state: ${JSON.stringify(this._room.muteState)}`),this._signalChannel.sendWaitForResponseWithRetry({command:Y.UPDATE_MUTE_STAT,responseCommand:G.MUTE_RESULT,data:this._room.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&S.emit(C.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=f.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===f.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===f.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===f.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===f.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Hr?(this._log.error(Je.NOT_SUPPORTED_H264ENCODE),new D({code:I.NOT_SUPPORTED_H264,message:H({key:F.NOT_SUPPORTED_H264ENCODE})})):new D({code:I.UNKNOWN,message:H({key:F.SIGNAL_RESPONSE_FAILED,data:{signalResponse:G.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return p(this,null,function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))})}};M([Ct(({localVideoTrack:e})=>{e==null||delete e.retryEncodeFailed})],Ud.prototype,"unpublish",1);var F_=(r=>(r[r.audio=1]="audio",r[r.bigVideo=2]="bigVideo",r[r.smallVideo=3]="smallVideo",r[r.auxVideo=4]="auxVideo",r))(F_||{}),hm=Ud;function B_(o){return Object.keys(o).filter(i=>o[i])}var Os=class extends bo{constructor(e){super(L(O({},e),{isUplink:!1}));d(this,"_flag",0);d(this,"isRobot",!1);d(this,"role","anchor");d(this,"remoteAudioTrack");d(this,"remoteVideoTrack");d(this,"remoteAuxiliaryTrack");d(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});d(this,"jitterBufferTimeoutId",-1);d(this,"_videoCodec");this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new gi(this._room,this),this.remoteVideoTrack=new Oi(this._room,this),this.remoteAuxiliaryTrack=new Es(this._room,this),this.initialize()}get videoCodec(){var e;return this._videoCodec||((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264"}set videoCodec(e){this._videoCodec=e}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing}}get muteState(){return Kt(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,s;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(s=this.remoteAuxiliaryTrack)==null||s.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===f.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){clearTimeout(this.jitterBufferTimeoutId),super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){this.singlePC&&(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this),this.remoteVideoTrack.on("decode-failed",this.onDecodeFailed,this))}uninstallEvents(){this.singlePC&&(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this),this.remoteVideoTrack.off("decode-failed",this.onDecodeFailed,this))}emitConnectionStateChangedEvent(e){var s,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((s=this.remoteVideoTrack)==null||s.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){var u,m;let t=e.streams[0],{track:r,receiver:s}=e;if(!t.id.includes(this.tinyId))return;let a=t.id.includes("aux")?"auxiliary":"main";this._log.debug(`ontrack ${a} ${r.kind}`);let c=f.AUDIO;r.kind===f.VIDEO&&(c=a===f.MAIN?f.VIDEO:f.AUXILIARY);let l=this.remoteAudioTrack;c===f.VIDEO?l=this.remoteVideoTrack:c===f.AUXILIARY&&(l=this.remoteAuxiliaryTrack),(u=this.singlePC)==null||u.receiverRemoteTrackMap.set(s,l),(m=this.singlePC)!=null&&m.scriptTransformWorker&&this.initReceiverTransform(s,a,r.kind===f.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(s),l.setInputMediaStreamTrack(r)}createEncodedStreams(e){if(!this.singlePC.insertableStreamsAbortMap.has(e)){let t=e.createEncodedStreams(),r=new AbortController,s={abortController:r,enqueue:n=>{var c,l,u;let a=(c=this.singlePC)==null?void 0:c.receiverRemoteTrackMap.get(e);return!a||a.kind==="video"&&!((l=this.singlePC)!=null&&l.isUsingH264)&&!((u=this.singlePC)!=null&&u.isUsingH265)?n:a.decodeFrame(n)}};t.readable.pipeThrough(new TransformStream({transform:(n,a)=>{let c=s.enqueue(n);c&&a.enqueue(c)}})).pipeTo(t.writable,r).catch(n=>{n!=="destroy"&&this._log.warn(n)}),this.singlePC.addAbortController(e,r)}}initReceiverTransform(e,t,r){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:r,userId:this.userId,streamType:t}))}subscribe(e,t){return p(this,null,function*(){var r,s;try{let n=!0;if(this._log.info(`subscribe ${t} ${B_(e)}`),this.hasSSRC){let l="subscribe_change";Object.values(e).find(u=>u===!0)||(l="unsubscribe"),yield this.sendSubscription(l,e)}else{if(yield this._room.switchRoomSubedReq,(r=this.singlePC)!=null&&r.autoSubscribedUserMap.size){let l=this.singlePC.autoSubscribedUserMap.get(this.userId);if(l){this.singlePC.autoSubscribedUserMap.delete(this.userId);let u=(s=this.singlePC.autoSubscribedSsrcGroups.get(this._room.roomId))==null?void 0:s[l.groupIndex];u&&(this.ssrc={audio:u.audioSsrc,video:u.bigVideoSsrc,videoRtx:u.bigVideoRtxSsrc,auxiliary:u.auxVideoSsrc,auxiliaryRtx:u.auxVideoRtxSsrc},n=!1)}}yield this.doSubscribe(e,n),this.checkTrackEnded(e)}let{user:a,mediaTrack:c}=this.remoteVideoTrack;e.smallVideo&&c?(v.addSuccessEvent({key:524702}),this._blackSmallVideoDetectionId=ur.start({track:c,isUplink:!1,room:this._room,userId:this.userId,onBlack:()=>{this._log.warn("small video is black, auto change to big"),this._room.changeType(!1,a),v.addFailedEvent({key:524702}),ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}})):(ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0)}catch(n){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${n.message} ${JSON.stringify(this.muteState)}`),new D({code:I.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}checkTrackEnded(e){var t,r,s;if((e.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||e.video&&((r=this.remoteVideoTrack.mediaTrack)==null?void 0:r.readyState)==="ended"||e.auxiliary&&((s=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:s.readyState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),$e&&qe<92)return;this.singlePC.startReconnection()}}unsubscribe(r){return p(this,arguments,function*({remoteTracks:e,streamType:t}){var a;if(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed){this._log.info(`${t} stream already unsubscribed`);return}let s=O({},this.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:s.audio=!1;break;case 4:s.video=!1;break;case 8:s.smallVideo=!1;break;case 2:s.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(s).find(c=>c===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${B_(s)}]`),n==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(n,s),t==="main"&&(ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0),n==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},s=Y.UNSUBSCRIBE,n=G.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},s=Y.SUBSCRIBE_CHANGE,n=G.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:s,data:r,responseCommand:n,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let c=new D({code:a.code,message:H({key:F.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}onSinglePCReconnected(){return p(this,null,function*(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn(`resubscribe ${JSON.stringify(this.subscribeState)}`),yield this.doSubscribe(this.subscribeState),this.remoteAudioTrack.checkDecodeResult(),this.remoteVideoTrack.checkDecodeResult(),this.remoteAuxiliaryTrack.checkDecodeResult())})}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return p(this,arguments,function*(e=this.subscribeState,t=!0){if(this.singlePC){this.singlePC.addDownlinkQueue.add(this.tinyId),yield this.singlePC.waitForPeerConnectionConnected();try{if(t||!this.hasSSRC){let r={audioSsrc:xt(),bigVideoSsrc:xt(),bigVideoRtxSsrc:xt(),auxVideoSsrc:xt(),auxVideoRtxSsrc:xt()},{audioSsrc:s,bigVideoSsrc:n,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:l}=r;this.ssrc={audio:s,video:n,videoRtx:a,auxiliary:c,auxiliaryRtx:l},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});try{let u=yield this._signalChannel.sendWaitForResponseWithRetry({command:Y.SPC_SUBSCRIBE,responseCommand:G.SPC_SUBSCRIBE_RESULT,data:{srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:!1,ssrc:r},retries:3,retryTimeout:0});if(u.data.code!==0&&u.data.code!==-10036)throw new D({code:u.data.code,message:u.data.message})}catch(u){throw yield this.removeDownlink(),u}return}this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc})}finally{if(!Sc)return;let{main:r,aux:s}=this._room.jitterBufferDelay||{},{jitterDelay:n=r,jitterDelayAux:a=s}=this._room.scheduleResult.config||{};(z(n)||z(a))&&this.setJitterBufferDelay({mainDelay:n,auxDelay:a})}}})}removeDownlink(){return p(this,null,function*(){if(!this.singlePC)return;this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId);let e=this._room.scheduleResult.config;(e!=null&&e.jitterDelay||e!=null&&e.jitterDelayAux)&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)})}setJitterBufferDelay({mainDelay:e,auxDelay:t}){if(!Sc||!this.singlePC||!this._peerConnection||gt(e)&>(t))return Promise.resolve();this._log.info(`set jitterBuffer main: ${e} aux: ${t}`);let r=this.singlePC.getReceiversByUserId(this.userId);return z(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),z(t)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=t,gt(e)&&(this.remoteAudioTrack.jitterBufferDelay=t)),new Promise(s=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:s})})}doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:s}){try{if(e===0&&t===0)return r.forEach(a=>a.jitterBufferTarget=0),s();if(r.forEach(a=>{var m;let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack||gt(e)&&a.track===this.remoteAudioTrack.outMediaTrack;if(c&>(t)||!c&>(e))return;let l=c?t||0:e,u=(a.jitterBufferTarget||0)+100;u>l||(a.jitterBufferTarget=u,this._log.debug(`set ${c?"aux ":""}${(m=a==null?void 0:a.track)==null?void 0:m.kind} jitterBuffer delay ${u} -> ${l}`))}),!r.find(a=>{let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack?t||0:e;return a.jitterBufferTarget<c}))return this._log.info(`set jitterBuffer main: ${e} aux: ${t} done`),s();this.jitterBufferTimeoutId=setTimeout(()=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:s})},1e3)}catch(n){this._log.warn(`set jitterBuffer delay error: ${n}`),clearTimeout(this.jitterBufferTimeoutId),s()}}get audioReceiver(){var e;return((e=this.singlePC)==null?void 0:e.getReceiversByUserId(this.userId)[0])||null}onDecodeFailed(){this._room.downlinkVideoCodec==="h265"&&this._room.requestRemoteFallbackToH264()}};M([ir(),Q(e=>function(...t){return new Promise((r,s)=>{let n=a=>{this.off("closed",n),s(new D({code:I.API_CALL_ABORTED,message:H({key:F.CONNECTION_ABORTED,data:a})}))};this.on("closed",n),e.apply(this,t).then(r,s).finally(()=>{this.off("closed",n)})})})],Os.prototype,"subscribe",1),M([ir()],Os.prototype,"unsubscribe",1),M([_i(()=>"jitter")],Os.prototype,"setJitterBufferDelay",1);var H_=Os;function $_(){return Q(o=>function(...i){return p(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(t=>t.outMediaTrack&&t.state==="ready"),!i.length))return;S.emit("61",{room:this});let e=o.apply(this,i);return Promise.all(i.map(t=>t.publish(this,e)))})})}function W_(){return Q(o=>function(...i){let e=o.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var G_=Ge(at());function DI(){return Math.floor(Math.random()*16383)}var Fd=class Fd extends G_.EventEmitter{constructor(e,t){super();this.room=e;this.signalChannel=t;d(this,"log");d(this,"cmdIdSeqMap",new Map);d(this,"messageMap",new Map);this.log=R.createLogger({parent:e.getLogger(),id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(G.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",r=>{[...this.messageMap.keys()].forEach(s=>{s.split("_").slice(0,-1).join("_")===r&&this.messageMap.delete(s)})})}send({cmdId:e,data:t}){let r=this.cmdIdSeqMap.get(e)||DI(),s={cmdId:e,msg:btoa(String.fromCharCode(...new Uint8Array(t))),ordered:!0,reliable:!0,streamSeq:r};this.cmdIdSeqMap.set(e,r+1),this.signalChannel.send(Y.SEND_CUSTOM_MSG,s),this.log.debug(`send custom msg: ${JSON.stringify(s)}`)}onReceiveMsg(e){let{data:t}=e.data,r=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(r){let s={userId:r,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),n=>n.charCodeAt(0)).buffer};if(t.ordered){let n=`${r}_${s.cmdId}`,a=this.messageMap.get(n);if(!a||a.lastSeq===0)a||(a={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(n,a),setTimeout(()=>this.emitMessage(s,!0),100)),a.cachedMessageMap.set(s.seq,{message:s});else if(Math.abs(a.lastSeq-s.seq)>Fd.SEQ_INTERVAL)this.messageMap.set(n,{lastSeq:s.seq,cachedMessageMap:new Map}),this.emitMessage(s);else if(s.seq>a.lastSeq){if(s.seq===a.lastSeq+1)this.emitMessage(s);else if(!a.cachedMessageMap.has(s.seq)){let c=setTimeout(()=>this.emitMessage(s,!0),5e3);a.cachedMessageMap.set(s.seq,{message:s,timeoutId:c})}}else this.log.debug(`drop message ${s.userId}-${s.cmdId}-${s.seq}`)}else this.emit("message",s)}else{this.log.warn(`receive msg from unknown user, wait peer-join tinyId: ${t.srcTinyId}`);let s=n=>{n.tinyId===t.srcTinyId&&(this.room.off("peer-join",s),this.onReceiveMsg(e))};this.room.on("peer-join",s),Ke(2e3).then(()=>this.room.off("peer-join",s))}}emitMessage(e,t=!1){var a;let r=this.messageMap.get(`${e.userId}_${e.cmdId}`),s=e;if(r){if(t){let c=[...r.cachedMessageMap.values()].sort((l,u)=>l.message.seq-u.message.seq);c[0]&&(s=c[0].message)}r.lastSeq!==0&&s.seq-r.lastSeq>1&&this.log.debug(`msg lost userId: ${s.userId} seq: ${r.lastSeq} -> ${s.seq}`),r.lastSeq=s.seq,clearTimeout((a=r.cachedMessageMap.get(s.seq))==null?void 0:a.timeoutId),r.cachedMessageMap.delete(s.seq)}this.log.debug(`receive custom msg: ${JSON.stringify(s)}`),this.emit("message",s);let n=r==null?void 0:r.cachedMessageMap.get(s.seq+1);n&&this.emitMessage(n.message)}};d(Fd,"SEQ_INTERVAL",300);var Vd=Fd;var{isString:q_,isUndefined:vo,getNetworkType:MI,isEmpty:OI}=vt,Ti=class extends Ld{constructor(e){super(e);d(this,"_businessInfo");d(this,"userManager");d(this,"_version");d(this,"_heartbeat",-1);d(this,"_lastHeartBeatTime",-1);d(this,"_stats");d(this,"_joinTimeout",-1);d(this,"_firstPublishedList",null);d(this,"_joinReject",null);d(this,"_isRelayChanged",!1);d(this,"sdpSemantics");d(this,"signalChannel",null);d(this,"uplinkConnection",null);d(this,"singlePC",null);d(this,"enableSPC",os);d(this,"_changeBigSmallRecords",new Map);d(this,"networkQuality");d(this,"_iceTransportPolicy");d(this,"forceRelay",!1);d(this,"_turnServers",[]);d(this,"_iceServersFromJoin");d(this,"_syncUserListInterval",-1);d(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160});d(this,"enableSEI",!1);d(this,"_enableAudioVolumeEvaluation",!1);d(this,"_audioVolumeIntervalId",0);d(this,"_enableMultiAuxStream",!1);d(this,"_pureAudioPushMode",!1);d(this,"_customMessageManager");d(this,"preferHW",!1);d(this,"healthDetector");d(this,"playoutDelay");d(this,"jitterBufferDelay");d(this,"_updateAudioLevelTaskId",-1);d(this,"switchRoomSubedReq");d(this,"resolveSwitchRoomSubedReq");d(this,"enableVolumeControlInIOS");this._stats=new ra(this,this._log),this.userManager=new od(this.userId,this._log),this._version=He,this.sdpSemantics=Mo,vo(e.sdpSemantics)?bi.isUnifiedPlanDefault()&&(this.sdpSemantics=gr):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${MI()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=vo(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&os,!vo(e.enableSPC)&&os&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this._initBusinessInfo(e),this.healthDetector=new P_(this)}get isMainStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex(e=>e.muteState.hasAuxiliary)>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.userMap.values()].map(e=>[e.tinyId,e.userId]))}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.videoCodec)||"h264"}get downlinkVideoCodec(){var e;return((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264"}join(e,t,r){return p(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",s=>{this.emit("peer-join",s)}),this.userManager.on("2",s=>{this.closeDownLinkConnection(s,"remote user exitRoom"),this.emit("peer-leave",s)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",n=>{var s=aa(n,[]);S.emit(C.REMOTE_PUBLISH_STATE_CHANGED,O({room:this},s)),this.emit("remote-publish-state-changed",O({},s))}),this.joinParams=e,new Promise((s,n)=>p(this,null,function*(){var a,c;this._joinReject=n;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(u){if(u instanceof D&&u.code===I.SPC_INITIALIZED_FAILED)(a=this.signalChannel)==null||a.destroy(),yield this.initialize();else return n(u)}let l=U();yield this.doJoin(e,(c=this.singlePC)==null?void 0:c.clientAbility),v.addSuccessEvent({key:521708,cost:U()-l}),s(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(l){v.addFailedEvent({key:521708,error:l}),n(l)}this._joinReject=null}))})}initSinglePC(){return p(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new jt({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",e=>this.emit("sei-message",e)),this.singlePC.on("dump",e=>this.emit("dump",e)),this.singlePC.once("error",()=>this.fallbackToMPC());try{return yield this.singlePC.initialize()}catch(e){throw this.fallbackToMPC(),new D({code:I.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((r,s)=>p(this,null,function*(){var c,l,u;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(Se.SETUP_FAILED,m=>{this.clearJoinTimeout(),S.emit(C.JOIN_SIGNAL_CONNECTION_END,{room:this,error:m}),s(m)}),he((l=(c=this.scheduleResult)==null?void 0:c.config)==null?void 0:l.singlePC)&&os&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),t&&this.playoutDelay&&(t.playoutDelay=this.playoutDelay);let n={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:e.role,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:Ll(),netType:qr(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0,isChorus:!!this.enableChorus,enableNtpAudioFrame:!!this.enableChorus&&pn()};this._log.debug(`join room signal data: ${JSON.stringify(n)}`);let a=5e3;(u=this.scheduleResult.config)!=null&&u.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(a=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{s(new D({code:I.JOIN_ROOM_FAILED,message:H({key:F.JOIN_ROOM_TIMEOUT})}))},a),S.emit(C.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?Y.SPC_JOIN_ROOM:Y.JOIN_ROOM,n),this.signalChannel.once(G.JOIN_ROOM_RESULT,m=>p(this,null,function*(){this.clearJoinTimeout();let{code:h,message:_,data:g,tinyId:E}=m.data;S.emit(C.JOIN_RECEIVED_CMD_RES,{room:this,code:h}),h===0?(this._log.info("Join room success, start heartbeat"),E&&(this.tinyId=E),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=g.publishers,this._iceServersFromJoin=g.iceServer?[g.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then(()=>{var A;(A=this.singlePC)==null||A.connect(L(O({},g.ability),{useVp8:g.ability.useVp8||!!e.useVp8,useH265:g.ability.useH265&&!!e.useH265})).catch(()=>{})}),r()):(this._log.error(`Join room failed result: ${h} error: ${_}`),s(new D({code:I.JOIN_ROOM_FAILED,extraCode:h,message:H({key:F.JOIN_ROOM_FAILED,data:{error:_,code:h}})})))}))}))}reJoin(){return p(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this.joinParams.roomId}`);let e,t=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,t.push(this.initSinglePC().then(r=>(e=r,r)))),this.signalChannel&&(this.signalChannel.close(),t.push(this.signalChannel.connect())),yield Promise.all(t),yield this.doJoin(L(O({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),e),this._log.warn("reJoin success"),se.logSuccessEvent({userId:this.userId,eventType:Ze.REJOIN}),this.singlePC){let r=s=>{var n;s.state==="CONNECTED"&&((n=this.singlePC)==null||n.off(Li.CONNECTION_STATE_CHANGED,r),this.uplinkConnection instanceof hm&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(a=>{a.installEvents(),a.onSinglePCReconnected()}))};this.singlePC.on(Li.CONNECTION_STATE_CHANGED,r),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof ia&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(e){this._log.warn(`reJoin fail ${e}`),this.reset(),se.logFailedEvent({userId:this.userId,eventType:Ze.REJOIN,error:e}),this.emit("error",new D({code:I.JOIN_ROOM_FAILED,message:H({key:F.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}})}initialize(){return p(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),r=this.signalChannel||s_(this.userId),s=!!(r&&r.isConnected&&r.keepAlive&&r.userId===this.userId&&r.room===this),n;return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(n=this.scheduleResult.domains[0]),this._log.info(`${s?"reuse":"setup"} signal channel`),s?(r.url=e,r.backupUrl=t,r.room=this,this.signalChannel=r):(r&&r.close(),this.signalChannel=new bs({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?n:void 0}),this._customMessageManager=new Vd(this,this.signalChannel),this._customMessageManager.on("message",a=>{this.emit("custom-message",a)})),this.networkQuality||(this.networkQuality=new Ms({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(Ms.EVENT_NETWORK_QUALITY,a=>{var c;this.emit("network-quality",a),(c=this.singlePC)==null||c.detectTCPAndUDP(a)})),tt(this,this.signalChannel).add(Se.CONNECTION_STATE_CHANGED,a=>{S.emit(C.SIGNAL_CONNECTION_STATE_CHANGED,O({room:this},a)),this.emit("signal-connection-state-changed",a)}).add(Se.RECONNECT_FAILED,a=>{this.reset(),this.emit("error",a)}).add(G.PEER_JOIN,a=>{let{srcTinyId:c,userId:l,role:u}=a.data.data;this.userManager.addUser({userId:l,tinyId:c,role:u})}).add(G.PEER_LEAVE,a=>{let{userId:c,reason:l=0}=a.data.data;this.userManager.deleteUser(c,l)}).add(G.UPDATE_REMOTE_MUTE_STAT,a=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(a.data)}).add(G.CLIENT_BANNED,a=>{let c=a.data.data,{reason:l}=c;if(se.uploadEvent({log:`stat-banned:${l}`,userId:this.userId}),l==="user_time_out"){this._log.warn(`${l} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[l==="kick"?"error":"info"](`user was banned because of [${l}]`),this.reset(),this.emit("banned",{reason:l})}).add(G.SEND_SWITCH_ROOM_SUBED_REQ,a=>{if(!this.singlePC)return;let{subList:c}=a.data.data;this._log.info(`auto subscribe ${_t(c,{keysToInclude:["userId"]})}`),c.forEach(l=>{this.singlePC.autoSubscribedUserMap.set(l.userId,l)}),this.resolveSwitchRoomSubedReq()}).add(G.FALLBACK_CODEC,a=>p(this,null,function*(){var l,u,m,h,_;let c=a.data.data;((l=c.videoControlInfo)==null?void 0:l.enableH265Enc)===0&&((u=this.singlePC)==null?void 0:u.videoCodec)==="h265"&&(this._log.warn(`fallback codec enableH265Enc: ${(m=c.videoControlInfo)==null?void 0:m.enableH265Enc}`),v.addCount({key:513e3}),yield(h=this.singlePC)==null?void 0:h.switchVideoEncoder("h264"),yield(_=this.uplinkConnection)==null?void 0:_.sendMediaSettings())})),this.signalChannel.once(Se.SETUP_SUCCESS,a=>{this.tinyId=a.signalInfo.tinyId,S.emit(C.JOIN_SIGNAL_CONNECTION_END,{room:this})}),S.emit(C.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),s&&S.emit(C.JOIN_SIGNAL_CONNECTION_END,{room:this}),s})}setSignalChannel(e){this.signalChannel=e,e||Le(this)}leave(){return p(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),S.emit(C.LEAVE_SEND_CMD,{room:this}),(e=this.signalChannel)==null||e.send(Y.LEAVE_ROOM),this.switchRoomSubedReq=void 0})}clearNetworkQuality(){this.networkQuality&&(this.networkQuality.stop(),delete this.networkQuality)}closeConnections(){this.remotePublishedUserMap.forEach(e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=oe.run("ric",this.doHeartbeat.bind(this),{delay:2e3}),this.enableChorus&&this.startUpdateNTPTime())}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),oe.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return p(this,null,function*(){var n;let e=this.badCaseDetector.getMonitorFreeze(),t=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});this.badCaseDetector.resetMonitor();let r=(n=this.signalChannel)!=null&&n.isConnected?Ef(this.userId):[],s=L(O({str_sdk_version:Ls,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:r,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},t),{msg_device_info:O({uint32_terminal_type:15,str_device_name:si(),str_os_version:"",uint32_net_type:qr()},t.msg_device_info)});if(this.heartbeatReport=s,this.heartbeatCount++,S.emit(C.HEARTBEAT_REPORT,{room:this,report:s}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(Y.ON_QUALITY_REPORT,s);let a=Date.now();this._lastHeartBeatTime>0&&a-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${a-this._lastHeartBeatTime}`),this._lastHeartBeatTime=a,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",L(O({},s),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.filter(r=>r.flag!==Qd).map(({userId:r,srcTinyId:s,flag:n})=>{r===this.userId&&(this.uplinkConnection&&(this.uplinkConnection.flag=n),this.localPublishFlag!==n&&(this.localPublishFlag=n,this.emit("local-publish-flag-changed",n)));let a=this.remotePublishedUserMap.get(r);return a&&this.checkSubscribeBigSmallVideo(a),{userId:r,tinyId:s,flag:n}});e.data.mixRobotList.forEach(({userId:r,srcTinyId:s,flag:n,mixUserList:a})=>{t.unshift({userId:r,tinyId:s,flag:n,isRobot:!0,mixUserList:a})}),e.data.fakeMixUser&&(e.data.fakeMixUser.tinyId=e.data.fakeMixUser.srcTinyId,t.push(e.data.fakeMixUser)),S.emit(C.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),t.find(r=>r.userId===this.userId)||(this.localPublishFlag=0,this.emit("local-publish-flag-changed",0)),this.userManager.setRemotePublishedUserList(t)}closeUplink(e="you unpublished"){this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish().catch(()=>{}),this.uplinkConnection.close(e),this.uplinkConnection instanceof ia&&(this.uplinkConnection=null)),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:t,flag:r,isRobot:s}){let n=new(this.singlePC?H_:tm)({userId:e,tinyId:t,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:s});this.userManager.addRemotePublishedUser(n),this.installDownlinkEvents(n,e),this.emit("remote-published",n)}closeDownLinkConnection(e,t="remote user unpublished"){let r=this.remotePublishedUserMap.get(e);r&&(r.close(t),this.emit("remote-unpublished",r))}installDownlinkEvents(e,t){e.on("error",r=>{let s=r.getCode();s!==I.ICE_TRANSPORT_ERROR&&(s===I.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",r))}),e.on("connection-state-changed",r=>{this.emit("media-connection-state-changed",L(O({},r),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=oe.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){oe.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then(e=>{this.userManager.setUserList(e)}).catch(e=>{this._log.debug(`sync user list failed: ${e}`)})}getUserList(){var e;return(e=this.signalChannel)!=null&&e.isConnected?this.signalChannel.sendWaitForResponse({command:Y.GET_USER_LIST,responseCommand:G.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:t})=>{let{code:r,message:s}=t;if(r===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:c,role:l})=>({userId:a,tinyId:c,role:l}));throw H({key:F.SIGNAL_RESPONSE_FAILED,data:{signalResponse:G.USER_LIST_RES,code:r,message:s}})}):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this.signalChannel&&!this.signalChannel.isOnline||!zh)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let e=this.getAllConnections();if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(e[t].getReconnectionCount()<6)return!1;return!0}checkConnectionsToReconnect(){var e;this.singlePC?((e=this.singlePC.getPeerConnection())==null?void 0:e.connectionState)===Ce.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(r=>{if(r instanceof pt&&!r.getIsReconnecting()){let s=r.getPeerConnection();s&&s.connectionState===Ce.CLOSED&&(this._log.warn(`[${r.getUserId()}] pc is closed but not reconnect`),r.startReconnection())}})}fallbackToMPC(){return p(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),se.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(e=this.singlePC)==null||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin()),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new ia({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),t.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localMainAudioTrack,localVideoTrack:t.localMainVideoTrack,isAuxiliary:!1})),t.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localAuxAudioTrack,localVideoTrack:t.localAuxVideoTrack,isAuxiliary:!0})),t.close()}for(let t of[...this.remotePublishedUserMap.values()]){let r=new tm({userId:t.userId,tinyId:t.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:t.flag,remoteAudioTrack:t.remoteAudioTrack,remoteVideoTrack:t.remoteVideoTrack,remoteAuxiliaryTrack:t.remoteAuxiliaryTrack});this.installDownlinkEvents(r,t.userId),this.remotePublishedUserMap.set(t.userId,r),t.isMainStreamSubscribed&&(yield r.subscribe(t.subscribeState,"main")),t.isAuxStreamSubscribed&&(yield r.subscribe(t.subscribeState,"auxiliary"))}})}destroy(){this.isDestroyed||(this.signalChannel&&(this._log.info("destroying SignalChannel"),this.signalChannel.close(),this.signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new D({code:I.INVALID_OPERATION,message:H({key:F.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),oe.clearTask(this._audioVolumeIntervalId))}switchRole(e){return p(this,null,function*(){this.role!==e&&(e==="audience"&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))})}doSwitchRole(e){let t={command:Y.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:G.SWITCH_ROLE_RES,retries:1};return this._log.info(`switchRole signal data: ${JSON.stringify(t.data)}`),this.signalChannel.sendWaitForResponseWithRetry(t).then(r=>{let{code:s,message:n}=r.data;if(s!==0)throw new D({code:I.SWITCH_ROLE_FAILED,message:H({key:F.SWITCH_ROLE_FAILED,data:{message:n,code:s}})});this.role=e}).catch(r=>{throw r instanceof D&&r.getCode()===I.API_CALL_TIMEOUT&&(r=new D({code:I.SWITCH_ROLE_FAILED,message:H({key:F.SWITCH_ROLE_TIMEOUT})})),this._log.error(r),r})}_initUplinkConnection(){this.uplinkConnection=this.singlePC?new hm({userId:this.userId,tinyId:this.tinyId,room:this}):new ia({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",e=>{this.emit("media-connection-state-changed",L(O({},e),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",e=>{let t=e.getCode();t!==I.ICE_TRANSPORT_ERROR&&(t===I.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",e))})}publish(e){return p(this,null,function*(){var r;this.uplinkConnection||this._initUplinkConnection();let t=`${e.streamType} ${e.isAudio&&e.isScreen?"screen":""}${e.kind}`;this._log.info(`publish() => ${t}`),yield(r=this.singlePC)==null?void 0:r.waitForPeerConnectionConnected(),yield this.uplinkConnection.publish({localAudioTrack:e instanceof kt?e:null,localVideoTrack:e instanceof je?e:null,isAuxiliary:e.streamType==="auxiliary"||e.isScreen})})}unpublish(e){return p(this,null,function*(){if(!(this.scene==="live"&&this.role!=="anchor"||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)){try{let t=`${e.streamType} ${e.isAudio&&e.isScreen?"screen":""}${e.kind}`;this._log.info(`unpublish() => ${t}`),yield this.uplinkConnection.unpublish({localAudioTrack:e instanceof kt?e:null,localVideoTrack:e instanceof je?e:null})}catch(t){}this.localTracks.size===0&&this.closeUplink("you unpublished")}})}addTrack(e){if(!this.uplinkConnection||!e.mediaTrack)return Promise.resolve();let t=this.uplinkConnection.addTrack(e);return e.publish(this,t),t}removeTrack(e){return!this.uplinkConnection||!e.mediaTrack?Promise.resolve():(e.unpublish(),this.uplinkConnection.removeTrack(e))}replaceTrack(e){return!this.uplinkConnection||!e.mediaTrack||!nu()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{t&&S.emit(C.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return p(this,null,function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return p(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:f.VIDEO,videoType:f.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(...e){return p(this,null,function*(){if(e=e.filter(n=>!n.isSubscribed),e.length===0)return;let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let s=e.find(n=>n.mediaType===2)?"auxiliary":"main";try{let n=O({},r.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:n.audio=!0;break;case 4:n.video=!0;break;case 8:n.smallVideo=!0;break;case 2:n.auxiliary=!0;break}});let a=this._changeBigSmallRecords.get(t);a&&a.options.smallVideo&&r.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),S.emit(C.SUBSCRIBE_START,{room:this,streamType:s,remotePublishedUser:r,subscribeState:n}),this._log.info(`subscribe() => ${t} ${s} [${Nd(n)}] prev: [${Nd(r.subscribeState)}]`),yield r.subscribe(n,s),this._log.info(`subscribe ${t} ${s} done`);for(let c of e)c.mediaTrack||(yield c.waitHasMediaTrack());S.emit(C.SUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:r})}catch(n){let a=n instanceof D?n.getCode():I.UNKNOWN,c=n;throw n instanceof D?a===I.REMOTE_STREAM_NOT_EXIST&&(c=new D({code:I.API_CALL_ABORTED,message:H({key:F.API_CALL_ABORTED,data:{message:n.message,userId:t,streamType:s}})}),this._log.warn(c)):(c=new D({code:a,message:H({key:F.SUBSCRIBE_FAILED,data:{message:n.message,userId:t,streamType:s}})}),this._log.error(c)),c}})}unsubscribe(...e){return p(this,null,function*(){let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let s=e.find(n=>n.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${t} ${s}`);try{yield r.unsubscribe({remoteTracks:e,streamType:s})}catch(n){this._log.warn(`unsubscribe() => failed ${n}`)}e.forEach(n=>{n.unsubscribe(),n.mediaType===8&&n.setMediaType(4)}),S.emit(C.UNSUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:r})})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(e=2e3,t){if(e<=0){this._enableAudioVolumeEvaluation=!1,oe.clearTask(this._audioVolumeIntervalId);return}e=Math.floor(Math.max(e,100)),S.emit(C.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&oe.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=oe.run("intervalInWorker",()=>{var s;so.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];(s=this.remotePublishedUserMap)==null||s.forEach(n=>{if(n.muteState.hasAudio){!so.isRunning&&n.muteState.audioAvailable&&n.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(n):n.remoteAudioTrack.volume=0;let a=Math.floor(n.remoteAudioTrack.getAudioLevel()*100);r.push({userId:n.userId,volume:a,floatVolume:n.remoteAudioTrack.getInternalAudioLevel()})}}),this.emit("audio-volume",r)},{delay:e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return p(this,null,function*(){var n;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||this._updateAudioLevelTaskId!==-1)return;let r=(n=this.uplinkConnection.getPeerConnection())==null?void 0:n.getSenders()[0];if(!r)return;let s=Math.max(e,500);this._log.warn(`updateAudioLevelFromSenderStat ${s}`),this._updateAudioLevelTaskId=oe.run("intervalInWorker",()=>p(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack){this.stopUpdateAudioLevelFromSenderStat();return}let a=yield r.getStats();if(this._updateAudioLevelTaskId<0)return;let{localMainAudioTrack:c}=this.uplinkConnection;a.forEach(l=>{l.type==="media-source"&&l.audioLevel&&(c.volume=l.audioLevel)})}),{delay:s,backgroundTask:t})})}stopUpdateAudioLevelFromSenderStat(){var e;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),oe.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,(e=this.uplinkConnection)!=null&&e.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(e){var s;let{audioReceiver:t}=e;if(!au||!t)return;let r=(s=t.getSynchronizationSources()[0])==null?void 0:s.audioLevel;z(r)?e.remoteAudioTrack.volume=Math.min(r*2,1):t.getStats().then(n=>{n.forEach(a=>{a.type==="inbound-rtp"&&z(a.audioLevel)&&(e.remoteAudioTrack.volume=a.audioLevel)})})}getLocalAudioStats(){return p(this,null,function*(){var t;let e={};return e[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},(t=this.uplinkConnection)!=null&&t.localMainAudioTrack&&(e[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),e})}getLocalVideoStats(){return p(this,null,function*(){var t,r;let e={};return e[this.userId]=((r=(t=this.uplinkConnection)==null?void 0:t.localMainVideoTrack)==null?void 0:r.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},e})}getTransportStats(){return p(this,null,function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let r=yield this._stats.getReceiverStats(t);e.downlinksRTT[r.userId]=r.rtt}return e})}getRemoteVideoStats(e){return p(this,null,function*(){let t={};for(let[r,s]of this.remotePublishedUserMap)e==="main"&&s.muteState.hasVideo&&(t[r]=s.remoteVideoTrack.stat),e==="auxiliary"&&s.muteState.hasAuxiliary&&(t[r]=s.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return p(this,null,function*(){let e={};for(let[t,r]of this.remotePublishedUserMap)r.muteState.hasAudio&&(e[t]=r.remoteAudioTrack.stat);return e})}setTurnServer(e,t){this._log.info(`set turn server: ${JSON.stringify(e)} ${t||""}`);let r=[];Array.isArray(e)?e.forEach(s=>r.push(vt.getTurnServer(s))):vt.isPlainObject(e)&&r.push(vt.getTurnServer(e)),this._turnServers=r,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Y.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:G.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Y.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:G.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendStartPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?Y.START_PUBLISH_TENCENT_CDN:Y.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?G.START_PUBLISH_TENCENT_CDN_RES:G.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"}).catch(r=>{if(r.code!==I.API_CALL_ABORTED)throw r})}sendStopPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?Y.STOP_PUBLISH_TENCENT_CDN:Y.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?G.STOP_PUBLISH_TENCENT_CDN_RES:G.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"}).catch(r=>{if(r.code!==I.API_CALL_ABORTED)throw r})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Y.START_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:G.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Y.UPDATE_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:G.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Y.STOP_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:G.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendAbilityStatus(e){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:Y.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:G.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(r=>{})}getIceServers(e){var t,r;return this._turnServers.length>0?this._turnServers:(t=this.scheduleResult.iceServers)!=null&&t.length?this.scheduleResult.iceServers:e!=null&&e.length?e:(r=this._iceServersFromJoin)!=null&&r.length?this._iceServersFromJoin:[]}getIceTransportPolicy(){return this.forceRelay?"relay":this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=vt.getEnv();return t?(e.mainUrl=`wss://${t}.rtc.qq.com`,e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):this.proxy_unified?(e.mainUrl=`wss://${this.proxy_unified}`,e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl=`wss://${this.scheduleResult.domains[0]}`,e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl=`wss://${this.scheduleResult.domains[1]}`)),e}getSignalInfo(){var e;return((e=this.signalChannel)==null?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}reset(e=!1){this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this.signalChannel&&(e&&this.signalChannel.keepAlive&&this.signalChannel.isConnected?this.signalChannel.stopKeepAliveIn(3600):(this.signalChannel.close(),this.setSignalChannel(null))),this.localPublishFlag=0,this.heartbeatCount=0,this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return p(this,null,function*(){let{subscribeState:t,userId:r,muteState:{hasSmall:s,hasVideo:n}}=e;if(!s&&!n||!t.video&&!t.smallVideo)return;let a=this._changeBigSmallRecords.get(r);if(!a||a.isSubscribing||a.reSubscribeCount<=0)return;let{options:c,reSubscribeCount:l}=a;if(c.video&&t.video||c.smallVideo&&t.smallVideo&&s)return;let u={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:c.video,smallVideo:c.smallVideo};try{if(!s&&u.smallVideo&&(u.video=!0,u.smallVideo=!1),u.smallVideo===t.smallVideo&&u.video===t.video)return;a.isSubscribing=!0,a.reSubscribeCount=l-1,yield e.subscribe(u,"main"),e.remoteVideoTrack.setMediaType(u.smallVideo?8:4),this._log.info(`change [${r}] to ${u.smallVideo?"small":"big"} video successfully. count ${Oo-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=Oo}catch(m){this._log.info(`change [${r}] to ${u.smallVideo?"small":"big"} video failed. count ${Oo-a.reSubscribeCount}. reason: ${m}`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(r)}})}changeType(e,t){let s={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:Oo};this._changeBigSmallRecords.set(t.userId,s),this._log.info(`set [${t.userId}] video prefer type: ${e?"small":"big"}`),this.emit("subscribe-small-video-changed",{userId:t.userId,isSmall:e});let n=this.remotePublishedUserMap.get(t.userId);n&&this.checkSubscribeBigSmallVideo(n)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(q_(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!vo(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PURE_AUDIO})});this._pureAudioPushMode=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!vo(e.userDefineRecordId)){let r=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(r)===null)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!vo(e.userDefinePushArgs))if(q_(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256)t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs;else throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_USER_DEFINE_PUSH_ARGS})});OI(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){return p(this,null,function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&hi)return this.singlePC.enableInsertableStreams=!0,yield this.singlePC.waitForPeerConnectionConnected(),yield this.singlePC.startReconnection()})}sendSignalMessage(e){var t;return this.signalChannel?(t=this.signalChannel)==null?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new D({code:I.INVALID_OPERATION,message:"not join"}))}get enableCodecPipeline(){return this.videoManager.encodePipeline.length>0||this.videoManager.decodePipeline.length>0||this.audioManager.encodePipeline.length>0||this.audioManager.decodePipeline.length>0}get scriptTransformWorker(){var e;return(e=this.singlePC)==null?void 0:e.scriptTransformWorker}switchRoom(e){return p(this,null,function*(){var _;if(!this.signalChannel||!this.singlePC)return;let{roomId:t,strRoomId:r,userSig:s,privateMapKey:n}=e,a=((_=this.scheduleResult.config)==null?void 0:_.autoSubscribeCount)||(e==null?void 0:e.autoSubscribeCount)||1,c=String(this.useStringRoomId?r:t),l=[];for(let g=0;g<a;g++)l.push({audioSsrc:xt(),bigVideoSsrc:xt(),bigVideoRtxSsrc:xt(),auxVideoSsrc:xt(),auxVideoRtxSsrc:xt()});let u={currRoomId:this.roomId,targetRoomId:c,useStringRoomId:this.useStringRoomId,ability:this.singlePC.clientAbility,userSig:s,privateMapKey:n!=null?n:this.privateMapKey,subscribe:l};this.singlePC.autoSubscribedUserMap.clear(),this.singlePC.autoSubscribedSsrcGroups.clear(),this.singlePC.autoSubscribedSsrcGroups.set(c,l);let m=this.roomId;this.roomId=this.useStringRoomId?r:String(t),this.switchRoomSubedReq=new Promise(g=>{this.resolveSwitchRoomSubedReq=g,Ke(5e3).then(g)}),S.emit(C.SWITCH_ROOM_START,{room:this}),yield this.singlePC.waitForPeerConnectionConnected();let h;try{this.userManager.clear(),h=yield this.signalChannel.sendWaitForResponse({command:Y.SWITCH_ROOM,responseCommand:G.SEND_SWITCH_ROOM_RES,data:u});let{code:g,message:E}=h.data;if(g===0)this.userSig=s,vo(n)||(this.privateMapKey=n),S.emit(C.SWITCH_ROOM_SUCCESS,{room:this,currentRoomId:m,targetRoomId:c});else{this._log.error(`switch room failed. result: ${g} error: ${E}`);let A=new D({code:I.SWITCH_ROOM_FAILED,extraCode:g,message:E});throw S.emit(C.SWITCH_ROOM_FAILED,{room:this,error:A}),A}}catch(g){throw this.singlePC.autoSubscribedSsrcGroups.clear(),this.roomId=m,this.resolveSwitchRoomSubedReq(),g}})}isSwitchRoomSupported(){var t;let e="unable to use switchRoom API, fallback to exitRoom and enterRoom.";return((t=this.scheduleResult.config)==null?void 0:t.switchRoom)!==!0?(this._log.warn(`${e} Reason: this sdkAppId is not supported, please contact us [https://trtc.io/contact] to enable it.`),!1):this.scene!=="live"?(this._log.warn(`${e} Reason: the scene is not 'live'.`),!1):this.role!=="audience"?(this._log.warn(`${e} Reason: the role is not 'audience'.`),!1):this.singlePC?!0:(this._log.warn(`${e} Reason: is not using single peerConnection.`),!1)}requestRemoteFallbackToH264(){var e;(e=this.singlePC)==null||e.requestRemoteFallbackToH264()}startUpdateNTPTime(){if(!this.signalChannel)return;let e=[];for(let t=0;t<5;t++)e.push(this.updateNTPTime());return Promise.all(e).then(t=>{var c;let r=t[0].offset,s=t[0].offset;t.forEach(l=>{r=Math.min(l.offset,r),s=Math.max(l.offset,s)});let n=Math.floor(t.reduce((l,u)=>l+u.rtt,0)/t.length),a=Math.floor(t.reduce((l,u)=>l+u.offset,0)/t.length);(s-r>30||n>50)&&setTimeout(()=>this.startUpdateNTPTime(),5e3),da(a),(c=this.scriptTransformWorker)==null||c.postMessage({type:"ntp-offset",data:a}),this._log.debug(`ntp updated offset: ${a}`),this.emit("ntp-time-updated")}).catch(t=>{this._log.warn(`ntp updated failed: ${t}`)})}updateNTPTime(){let e=Date.now();return this.signalChannel.sendWaitForResponse({command:Y.UPDATE_NETWORK_TIME,responseCommand:G.UPDATE_NETWORK_TIME_RESULT,addReceiveTime:!0,data:{clientSendTime:String(e)},enableLog:!1}).then(t=>{let r=Number(t.data.data.serverSendTime),s=Number(t.data.data.serverRecvTime),n=t.data.receiveTime||Date.now(),a=(s-e+(r-n))/2;return{rtt:n-e-(s-r),offset:a}})}};M([ye(["left",J.INIT],"joined"),Mt({settings:{retries:1,timeout:0},onRetrying(e){this._log.warn(`join retry ${e}`)},onRetryFailed(e){this._log.error("join failed",e)},onError(e,t){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),Lt(!0),this.reset(),t()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),t()):(this.reset(),t())}}),e_()],Ti.prototype,"join",1),M([ye("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),t_(),Lc("leave room"),yn({fnName:"publish",validateArgs:!1}),yn({fnName:"unsubscribe",validateArgs:!1})],Ti.prototype,"leave",1),M([_i(e=>e.mediaType),$_(),Mt({settings:{retries:Hi,timeout:e=>Zt(e)},onError(e,t,r,[s]){var n;(n=e.message)!=null&&n.includes("timeout")?(this._log.warn(`publish ${s.strMediaType} timeout`,e),t()):(this._log.error(`publish ${s.strMediaType} failed: ${e}`),r(e),S.emit(C.PUBLISH_FAILED,{room:this}))}})],Ti.prototype,"publish",1),M([yn({fnName:"publish"}),_i(e=>e.mediaType),W_(),Ct(function(){var e,t;this.localTracks.size===0&&Rr()&&((t=(e=this.singlePC)==null?void 0:e.getPeerConnection())==null||t.getSenders().forEach(r=>r.track&&r.replaceTrack(null)))})],Ti.prototype,"unpublish",1),M([Oc(e=>{if(e.code!==I.API_CALL_ABORTED)throw e}),_i(e=>e.userId)],Ti.prototype,"replaceTrack",1),M([_i((...e)=>e[0].userId),Eo(),i_(),Mt({settings:{retries:Hi,timeout:e=>Zt(e)},onError(e,t,r,s){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error(`subscribe failed: ${e}`),r(e),S.emit(C.SUBSCRIBE_FAILED,{room:this,remoteTracks:s}))}})],Ti.prototype,"subscribe",1),M([yn({fnName:"subscribe",callback(...e){this.singlePC||e.forEach(t=>{let r=this.remotePublishedUserMap.get(t.userId);r&&!r.isMainStreamSubscribed&&!r.isAuxStreamSubscribed&&r.close("you unsubscribed")})}}),_i((...e)=>e[0].userId)],Ti.prototype,"unsubscribe",1);ea.create=ea._create.bind(ea,Ti);hu(30);var H4=ea;export{H4 as default};
|
|
122
|
+
`,e=new Blob([i],{type:"application/javascript"}),t=URL.createObjectURL(e);this.worker=new Worker(t),URL.revokeObjectURL(t),this.worker.onerror=r=>this._log.warn("worker error:",r.message,r.filename||"unknown",r.lineno||"unknown"),this.worker.onmessage=r=>{var l;let{type:s,trackId:n,message:a,count:c}=r.data;if(s==="black")(l=this.callbacks.get(n))==null||l();else if(s==="log")this._log.warn(a);else if(s==="blackCount"){let u=this.userIdMap.get(n);this._log.warn(`${u||n} black count: ${c}`)}}}return this.worker}start({track:i,isUplink:e,room:t,userId:r,onBlack:s}){if(this._log.debug("start detect black video",i.id),!fn()||!s||!i||typeof Worker=="undefined"){this._log.warn("black video detector not supported");return}let n=a=>{var l,u,m,h;let c;if(e)c=(u=(l=a.msg_up_stream_info)==null?void 0:l.msg_video_status)==null?void 0:u.filter(_=>_.uint32_video_stream_type===3)[0];else{let _=(m=a.msg_down_stream_info)==null?void 0:m.filter(g=>{var E;return((E=g.msg_user_info)==null?void 0:E.str_identifier)===r})[0];c=(h=_==null?void 0:_.msg_video_status)==null?void 0:h.filter(g=>g.uint32_video_stream_type===3)[0]}if(c){let _=(c.uint32_video_codec_bitrate||0)/1e3;if(this.sleep[i.id]&&this.sleep[i.id]>0){this.sleep[i.id]-=1;return}_>0&&_<10&&(this.sleep[i.id]=30,this._log.info("track bitrate",_,"start check"),this.checkOnce(i,30*1e3))}};return t.on("heartbeat-report",n),this.heartbeatListenerCleaner.set(i.id,()=>t.off("heartbeat-report",n)),this.callbacks.set(i.id,s),this.userIdMap.set(i.id,r),i.id}checkOnce(i,e){try{let t=this.getWorker();if(!t)throw new Error("Worker not available");let r=new MediaStreamTrackProcessor({track:i});t.postMessage({type:"addTrack",trackId:i.id,timeout:e,readable:r.readable},[r.readable])}catch(t){this._log.warn("check error:",t),this.stop(i.id)}}stop(i){if(i){this.worker&&this.worker.postMessage({type:"removeTrack",trackId:i}),this.callbacks.delete(i),delete this.sleep[i];let e=this.heartbeatListenerCleaner.get(i);e&&e(),this.heartbeatListenerCleaner.delete(i),this.userIdMap.delete(i)}}destroy(){this.callbacks.forEach((i,e)=>this.stop(e)),this.worker&&(this.worker.terminate(),this.worker=null)}},ur=new um;var Ud=class extends bo{constructor(e){super(L(O({},e),{isUplink:!0}));d(this,"localMainAudioTrack",null);d(this,"localMainVideoTrack",null);d(this,"localAuxAudioTrack",null);d(this,"localAuxVideoTrack",null);d(this,"_isPublishingAux",!1);d(this,"_publishingLocalAudioTrack");d(this,"_publishingLocalVideoTrack");d(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,videoDecCodec:"",audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});d(this,"_flag",0);d(this,"_checkPublishStateTimeoutId",-1);this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:r,smallVideoSsrc:s,smallVideoRtxSsrc:n,auxVideoSsrc:a,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:r||0,small:s||0,smallRtx:n||0,auxiliary:a||0,auxiliaryRtx:c||0}}get flag(){return this._flag}set flag(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}checkPublishState(e=!1){try{if(!e&&this._checkPublishStateTimeoutId>0)return;let{serverPublishState:t}=this,{publishState:r}=this._room,s=Object.keys(r).filter(n=>{if(r[n]!==t[n]&&r[n])switch(n){case"audio":return!(!this.localMainAudioTrack||!this.localMainAudioTrack.isMediaTrackActive);case"bigVideo":case"smallVideo":return!(!this.localMainVideoTrack||!this.localMainVideoTrack.isMediaTrackActive);case"auxVideo":return!(!this.localAuxVideoTrack||!this.localAuxVideoTrack.isMediaTrackActive)}return!1});if(s.length>0){if(e)v.addCount({key:521e3}),s.forEach(n=>{this._log.warn(`${n} publish failed during call ${ni()} ${si()}`),v.addEnum({key:521719,value:F_[n]})});else{this._checkPublishStateTimeoutId=oe.run("timeout",()=>this.checkPublishState(!0),{delay:10*1e3,count:1});return}oe.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}}catch(t){this._log.warn("checkPublishState failed",t)}}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get serverPublishState(){return{audio:!!(this.flag&_r),bigVideo:!!(this.flag&fr),smallVideo:!!(this.flag&Vs),auxVideo:!!(this.flag&Br)}}initialize(){this.installEvents()}close(e){var r;let t=((r=this._peerConnection)==null?void 0:r.getSenders())||[];for(let s of t)s.replaceTrack(null);super.close(e),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}installSPCEvents(){var e,t;(e=this.singlePC)!=null&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(t=this.singlePC)==null||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallSPCEvents(){var e;(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}emitConnectionStateChangedEvent(e,t){var n,a,c;let r=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:r,state:e}))),s}onVideoEncodeFailed(e){return p(this,null,function*(){if(!e||!e.isMediaTrackActive)return;let{videoCodec:t,singlePC:r}=this;if(!r)return;let s={h265:{supported:r.isH264EncodeSupported,target:"h264",log:"h265 encoder not working"},h264:{supported:r.isVP8EncodeSupported,target:"vp8",log:"h264 encoder not working"},vp8:{supported:!1,target:"vp8",log:"vp8 encoder not working, no fallback available"}};if(t==="vp9"||t==="av1")return;let n=s[t];this._log.warn(n.log),n!=null&&n.supported&&(yield r.switchVideoEncoder(n.target))})}publish(s){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){var c,l,u,m,h,_,g;if(!this.singlePC)return;if(this.installEvents(),this.installTrackMuteEvents(e,t),t&&(t.retryEncodeFailed=this.onVideoEncodeFailed.bind(this)),yield this.singlePC.waitForPeerConnectionConnected(),e&&(this._publishingLocalAudioTrack=e),t){if(!this.singlePC.isH264EncodeSupported&&!this.singlePC.isVP8EncodeSupported)throw new D({code:I.NOT_SUPPORTED_H264,message:H({key:F.NOT_SUPPORTED_H264ENCODE})});this.singlePC.isUsingH264&&!this.singlePC.isH264EncodeSupported&&this.singlePC.isVP8EncodeSupported&&(this._log.warn("h264 encoder not supported"),yield this.singlePC.switchVideoEncoder("vp8")),_e&&Yo()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn(`fallback video to defaultBigVideoProfile: ${JSON.stringify(pr)}`),t.setProfile(pr),yield t.applyProfile()),this._publishingLocalVideoTrack=t}this._isPublishingAux=r;let n;if(t&&!r&&t.small&&(n=this._room.videoManager.smallTrack),yield this._signalChannel.sendWaitForResponseWithRetry({command:Y.SPC_PUBLISH,responseCommand:G.SPC_PUBLISH_RESULT,data:L(O({},this.singlePC.uplinkSSRC),{state:this._room.publishState,muteState:this._room.muteState}),retries:3}),yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:r}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,t){this[r?"localAuxVideoTrack":"localMainVideoTrack"]=t,yield this.singlePC.setDegradationPreference(this._peerConnection.getSenders()[r?3:1],t.contentHint,t.streamType);let{scaleResolutionDownBy:E}=t;yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[r?3:1],E,t.streamType)}e&&(this[r?"localAuxAudioTrack":"localMainAudioTrack"]=e),yield this.singlePC.setBandwidth({audio:((c=this.localMainAudioTrack)==null?void 0:c.profile.bitrate)||((l=this.localAuxAudioTrack)==null?void 0:l.profile.bitrate),bigVideo:(u=this.localMainVideoTrack)==null?void 0:u.profile.bitrate,smallVideo:(h=(m=this.localMainVideoTrack)==null?void 0:m.small)==null?void 0:h.bitrate,auxVideo:(_=this.localAuxVideoTrack)==null?void 0:_.profile.bitrate}),this.sendMediaSettings(),(this._room.preferHW||(g=this._room.scheduleResult.config)!=null&&g.preferHW)&&t&&t.profile.width*t.profile.height>=1280*720&&this.singlePC.useHWEncoder(!0,r?7:2);let a=new URLSearchParams(location.search).get("profileLevelId");a&&this.singlePC.setProfileLevelId(a)})}publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:s}){if(!St())return;this._log.info("publish by transceiver");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack,c=this._peerConnection.getTransceivers(),l=[],u=[],m=(_,g,E)=>{var k;let A=c[g].sender.replaceTrack(E);u.push(g),(k=this.singlePC)!=null&&k.enableInsertableStreams&&A.then(()=>this.createEncodedStreams(c[g].sender,_)),this.initSenderTransform(c[g].sender,_),l.push(A)};a&&m(e.mediaType,0,a),n&&m(t.mediaType,s?3:1,n),t!=null&&t.small&&l.push(this.publishSmall(this._room.videoManager.smallMode,t));let h=this.singlePC.setTransceiverDirection(ne.SENDONLY,u);return l.push(h),Promise.all(l)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._room.localMainAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._room.localMainVideoTrack;case 2:return this.localAuxVideoTrack||this._room.localAuxVideoTrack;default:return null}}createEncodedStreams(e,t){var a,c;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let r=e.createEncodedStreams(),s=new AbortController;(a=this.singlePC)==null||a.addAbortController(e,s),((c=this.getTrackByMediaType(t))!=null&&c.enableEncodeFrame?r.readable.pipeThrough(new TransformStream({transform:(l,u)=>{var h,_;let m=this.getTrackByMediaType(t);if(!m||!m.encodeFrame)return u.enqueue(l);m.isAudio?u.enqueue(m.enableEncodeFrame?m.encodeFrame(l):l):u.enqueue((h=this.singlePC)!=null&&h.isUsingH264||(_=this.singlePC)!=null&&_.isUsingH265?m.encodeFrame(l,t===8):l)}}),s):r.readable).pipeTo(r.writable,s).catch(l=>{this._log.debug("encoded stream error",l),l!=="destroy"&&this._log.warn(l)})}initSenderTransform(e,t){if(!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||!ss)return;let r=t!==2,s=t===8;e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:t===1,isMain:r,isSmall:s}))}enableSmall(e){return p(this,null,function*(){e?yield this.publishSmall(this._room.videoManager.smallMode):yield this.unpublishSmall()})}publishSmall(r){return p(this,arguments,function*(e,t=this.localMainVideoTrack){var l;if(!this.singlePC)return;if(e==="canvas"&&!gc()){this._log.warn("canvas mode small stream is not supported");return}let s=this._peerConnection.getTransceivers(),{sender:n}=s[2],a=yield this.doPublishSmall(e,t),c=e==="canvas"?524700:524701;if(v.addSuccessEvent({key:c}),!a){v.addFailedEvent({key:c,error:10001});return}(l=this.singlePC)!=null&&l.enableInsertableStreams&&this.createEncodedStreams(n,8),this.initSenderTransform(n,8),yield this.singlePC.setTransceiverDirection(ne.SENDONLY,[2]),this.updateMediaSettings(),yield this.doPublishChange(),n.track&&(this._blackSmallVideoDetectionId=ur.start({track:n.track,room:this._room,isUplink:!0,userId:this.userId,onBlack:()=>{this._log.warn("small video is black");let u=e==="canvas"?524700:524701;v.addFailedEvent({key:u,error:10002}),ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}}))})}doPublishSmall(r){return p(this,arguments,function*(e,t=this.localMainVideoTrack){if(!this.singlePC)return null;this._log.info("publish small",e);let s=this._peerConnection.getTransceivers(),{sender:n}=s[2];if(e==="canvas"&&this._room.videoManager.smallTrack)return yield n.replaceTrack(this._room.videoManager.smallTrack),"canvas";if(e==="api"&&(t!=null&&t.outMediaTrack)&&(t!=null&&t.small)){yield n.replaceTrack(t==null?void 0:t.outMediaTrack);let a=n.getParameters(),c=Ho(t==null?void 0:t.profile,t==null?void 0:t.small);return this._log.info("small scaleResolutionDownBy",c),a.encodings[0].scaleResolutionDownBy=c,n.setParameters(a),"api"}return this._log.warn(`small track can not be enabled, smallMode: ${this._room.videoManager.smallMode}, smallTrack: ${!!this._room.videoManager.smallTrack}, bigVideoTrack: ${!!(t!=null&&t.outMediaTrack)}`),null})}unpublishSmall(){return p(this,null,function*(){if(!this.singlePC)return;this._log.info("unpublish small"),yield this._peerConnection.getTransceivers()[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(ne.INACTIVE,[2]),this.updateMediaSettings(),yield this.doPublishChange(),ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){var l;yield(l=this.singlePC)==null?void 0:l.waitForPeerConnectionConnected();let s=t&&t===this.localAuxVideoTrack||e&&e===this.localAuxAudioTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(s?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localMainAudioTrack&&!this.localAuxAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(s?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=L(O({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=L(O({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.singlePC.setTransceiverDirection(ne.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return p(this,null,function*(){let t={state:this._room.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponseWithRetry({command:Y.PUBLISH_STATE_CHANGE,data:t,responseCommand:G.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:Y.UNPUBLISH,commandDesc:"unpublish",responseCommand:G.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===I.API_CALL_TIMEOUT||t.getCode()===I.API_CALL_ABORTED)return Promise.resolve();throw t})}updateMediaSettings(){var s,n;this._mediaSettings.videoCodec=((s=this.singlePC)==null?void 0:s.videoCodec)||"h264",this._mediaSettings.videoDecCodec=((n=this.singlePC)==null?void 0:n.downlinkVideoCodec)||"h264";let e=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:t,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:t=this._publishingLocalVideoTrack),yi){if(e&&e.outMediaTrack){let a=e.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(t&&t.outMediaTrack){let a=t.outMediaTrack.getSettings(),{scaleResolutionDownBy:c}=t;this._mediaSettings.videoWidth=(a.width||0)/c||0,this._mediaSettings.videoHeight=(a.height||0)/c||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=t.profile.bitrate*1e3,t.small&&(this._mediaSettings.smallVideoWidth=t.small.width,this._mediaSettings.smallVideoHeight=t.small.height,this._mediaSettings.smallVideoFps=t.small.frameRate,this._mediaSettings.smallVideoBps=t.small.bitrate*1e3)}if(r&&r.outMediaTrack){let a=r.outMediaTrack.getSettings(),{scaleResolutionDownBy:c}=r;this._mediaSettings.auxVideoWidth=(a.width||0)/c||0,this._mediaSettings.auxVideoHeight=(a.height||0)/c||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=r.profile.bitrate*1e3}}else e&&e.outMediaTrack&&(this._mediaSettings.audioChannel=e.profile.channelCount,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=e.profile.sampleRate),t&&t.outMediaTrack&&(this._mediaSettings.videoWidth=t.profile.width,this._mediaSettings.videoHeight=t.profile.height,this._mediaSettings.videoFps=t.profile.frameRate,this._mediaSettings.videoBps=t.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Y.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:G.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return p(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?f.AUXILIARY:f.MAIN} stream`),yr()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return p(this,null,function*(){var s;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===f.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((s=this.localMainVideoTrack)!=null&&s.small)&&this._room.videoManager.smallTrack&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===ne.INACTIVE&&(yield this.singlePC.setTransceiverDirection(ne.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(e){return p(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?f.AUXILIARY:f.MAIN} stream`),yr()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return p(this,null,function*(){if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===f.AUDIO)yield r[0].sender.replaceTrack(null);else{let s=t?3:1;yield r[s].sender.replaceTrack(null),s===1&&this._room.videoManager.hasSmall&&(yield r[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(ne.INACTIVE,[s])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(e){return p(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders(),r=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!r||t.find(a=>a.track===r))return!1;let s=e.mediaType===2||e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${r.kind} track ${r.id} ${r.label} on ${s?f.AUXILIARY:f.MAIN} stream`),r.kind===f.AUDIO&&t[0]&&(yield t[0].replaceTrack(r)),r.kind===f.VIDEO&&(!s&&t[1]&&(yield t[1].replaceTrack(r)),s&&t[3]&&(yield t[3].replaceTrack(r))),!0})}setBandwidth(s){return p(this,arguments,function*({bandwidth:e,type:t,videoType:r}){if(this.singlePC){let n={};t===f.AUDIO?n.audio=e:r==="big"?n.bigVideo=e:r==="small"?n.smallVideo=e:n.auxVideo=e,yield this.singlePC.setBandwidth(n)}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info(`send muted state: ${JSON.stringify(this._room.muteState)}`),this._signalChannel.sendWaitForResponseWithRetry({command:Y.UPDATE_MUTE_STAT,responseCommand:G.MUTE_RESULT,data:this._room.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&S.emit(C.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=f.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===f.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===f.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===f.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===f.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Hr?(this._log.error(Je.NOT_SUPPORTED_H264ENCODE),new D({code:I.NOT_SUPPORTED_H264,message:H({key:F.NOT_SUPPORTED_H264ENCODE})})):new D({code:I.UNKNOWN,message:H({key:F.SIGNAL_RESPONSE_FAILED,data:{signalResponse:G.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return p(this,null,function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))})}};M([Ct(({localVideoTrack:e})=>{e==null||delete e.retryEncodeFailed})],Ud.prototype,"unpublish",1);var F_=(r=>(r[r.audio=1]="audio",r[r.bigVideo=2]="bigVideo",r[r.smallVideo=3]="smallVideo",r[r.auxVideo=4]="auxVideo",r))(F_||{}),hm=Ud;function B_(o){return Object.keys(o).filter(i=>o[i])}var Os=class extends bo{constructor(e){super(L(O({},e),{isUplink:!1}));d(this,"_flag",0);d(this,"isRobot",!1);d(this,"role","anchor");d(this,"remoteAudioTrack");d(this,"remoteVideoTrack");d(this,"remoteAuxiliaryTrack");d(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});d(this,"jitterBufferTimeoutId",-1);d(this,"_videoCodec");this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new gi(this._room,this),this.remoteVideoTrack=new Oi(this._room,this),this.remoteAuxiliaryTrack=new Es(this._room,this),this.initialize()}get videoCodec(){var e;return this._videoCodec||((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264"}set videoCodec(e){this._videoCodec=e}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing}}get muteState(){return Kt(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,s;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(s=this.remoteAuxiliaryTrack)==null||s.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===f.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){clearTimeout(this.jitterBufferTimeoutId),super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){this.singlePC&&(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this),this.remoteVideoTrack.on("decode-failed",this.onDecodeFailed,this))}uninstallEvents(){this.singlePC&&(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this),this.remoteVideoTrack.off("decode-failed",this.onDecodeFailed,this))}emitConnectionStateChangedEvent(e){var s,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((s=this.remoteVideoTrack)==null||s.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){var u,m;let t=e.streams[0],{track:r,receiver:s}=e;if(!t.id.includes(this.tinyId))return;let a=t.id.includes("aux")?"auxiliary":"main";this._log.debug(`ontrack ${a} ${r.kind}`);let c=f.AUDIO;r.kind===f.VIDEO&&(c=a===f.MAIN?f.VIDEO:f.AUXILIARY);let l=this.remoteAudioTrack;c===f.VIDEO?l=this.remoteVideoTrack:c===f.AUXILIARY&&(l=this.remoteAuxiliaryTrack),(u=this.singlePC)==null||u.receiverRemoteTrackMap.set(s,l),(m=this.singlePC)!=null&&m.scriptTransformWorker&&this.initReceiverTransform(s,a,r.kind===f.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(s),l.setInputMediaStreamTrack(r)}createEncodedStreams(e){if(!this.singlePC.insertableStreamsAbortMap.has(e)){let t=e.createEncodedStreams(),r=new AbortController,s={abortController:r,enqueue:n=>{var c,l,u;let a=(c=this.singlePC)==null?void 0:c.receiverRemoteTrackMap.get(e);return!a||a.kind==="video"&&!((l=this.singlePC)!=null&&l.isUsingH264)&&!((u=this.singlePC)!=null&&u.isUsingH265)?n:a.decodeFrame(n)}};t.readable.pipeThrough(new TransformStream({transform:(n,a)=>{let c=s.enqueue(n);c&&a.enqueue(c)}})).pipeTo(t.writable,r).catch(n=>{n!=="destroy"&&this._log.warn(n)}),this.singlePC.addAbortController(e,r)}}initReceiverTransform(e,t,r){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:r,userId:this.userId,streamType:t}))}subscribe(e,t){return p(this,null,function*(){var r,s;try{let n=!0;if(this._log.info(`subscribe ${t} ${B_(e)}`),this.hasSSRC){let l="subscribe_change";Object.values(e).find(u=>u===!0)||(l="unsubscribe"),yield this.sendSubscription(l,e)}else{if(yield this._room.switchRoomSubedReq,(r=this.singlePC)!=null&&r.autoSubscribedUserMap.size){let l=this.singlePC.autoSubscribedUserMap.get(this.userId);if(l){this.singlePC.autoSubscribedUserMap.delete(this.userId);let u=(s=this.singlePC.autoSubscribedSsrcGroups.get(this._room.roomId))==null?void 0:s[l.groupIndex];u&&(this.ssrc={audio:u.audioSsrc,video:u.bigVideoSsrc,videoRtx:u.bigVideoRtxSsrc,auxiliary:u.auxVideoSsrc,auxiliaryRtx:u.auxVideoRtxSsrc},n=!1)}}yield this.doSubscribe(e,n),this.checkTrackEnded(e)}let{user:a,mediaTrack:c}=this.remoteVideoTrack;e.smallVideo&&c?(v.addSuccessEvent({key:524702}),this._blackSmallVideoDetectionId=ur.start({track:c,isUplink:!1,room:this._room,userId:this.userId,onBlack:()=>{this._log.warn("small video is black, auto change to big"),this._room.changeType(!1,a),v.addFailedEvent({key:524702}),ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}})):(ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0)}catch(n){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${n.message} ${JSON.stringify(this.muteState)}`),new D({code:I.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}checkTrackEnded(e){var t,r,s;if((e.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||e.video&&((r=this.remoteVideoTrack.mediaTrack)==null?void 0:r.readyState)==="ended"||e.auxiliary&&((s=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:s.readyState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),$e&&qe<92)return;this.singlePC.startReconnection()}}unsubscribe(r){return p(this,arguments,function*({remoteTracks:e,streamType:t}){var a;if(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed){this._log.info(`${t} stream already unsubscribed`);return}let s=O({},this.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:s.audio=!1;break;case 4:s.video=!1;break;case 8:s.smallVideo=!1;break;case 2:s.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(s).find(c=>c===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${B_(s)}]`),n==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(n,s),t==="main"&&(ur.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0),n==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},s=Y.UNSUBSCRIBE,n=G.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},s=Y.SUBSCRIBE_CHANGE,n=G.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:s,data:r,responseCommand:n,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let c=new D({code:a.code,message:H({key:F.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}onSinglePCReconnected(){return p(this,null,function*(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn(`resubscribe ${JSON.stringify(this.subscribeState)}`),yield this.doSubscribe(this.subscribeState),this.remoteAudioTrack.checkDecodeResult(),this.remoteVideoTrack.checkDecodeResult(),this.remoteAuxiliaryTrack.checkDecodeResult())})}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return p(this,arguments,function*(e=this.subscribeState,t=!0){if(this.singlePC){this.singlePC.addDownlinkQueue.add(this.tinyId),yield this.singlePC.waitForPeerConnectionConnected();try{if(t||!this.hasSSRC){let r={audioSsrc:xt(),bigVideoSsrc:xt(),bigVideoRtxSsrc:xt(),auxVideoSsrc:xt(),auxVideoRtxSsrc:xt()},{audioSsrc:s,bigVideoSsrc:n,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:l}=r;this.ssrc={audio:s,video:n,videoRtx:a,auxiliary:c,auxiliaryRtx:l},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});try{let u=yield this._signalChannel.sendWaitForResponseWithRetry({command:Y.SPC_SUBSCRIBE,responseCommand:G.SPC_SUBSCRIBE_RESULT,data:{srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:!1,ssrc:r},retries:3,retryTimeout:0});if(u.data.code!==0&&u.data.code!==-10036)throw new D({code:u.data.code,message:u.data.message})}catch(u){throw yield this.removeDownlink(),u}return}this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc})}finally{if(!Sc)return;let{main:r,aux:s}=this._room.jitterBufferDelay||{},{jitterDelay:n=r,jitterDelayAux:a=s}=this._room.scheduleResult.config||{};(z(n)||z(a))&&this.setJitterBufferDelay({mainDelay:n,auxDelay:a})}}})}removeDownlink(){return p(this,null,function*(){if(!this.singlePC)return;this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId);let e=this._room.scheduleResult.config;(e!=null&&e.jitterDelay||e!=null&&e.jitterDelayAux)&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)})}setJitterBufferDelay({mainDelay:e,auxDelay:t}){if(!Sc||!this.singlePC||!this._peerConnection||gt(e)&>(t))return Promise.resolve();this._log.info(`set jitterBuffer main: ${e} aux: ${t}`);let r=this.singlePC.getReceiversByUserId(this.userId);return z(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),z(t)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=t,gt(e)&&(this.remoteAudioTrack.jitterBufferDelay=t)),new Promise(s=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:s})})}doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:s}){try{if(e===0&&t===0)return r.forEach(a=>a.jitterBufferTarget=0),s();if(r.forEach(a=>{var m;let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack||gt(e)&&a.track===this.remoteAudioTrack.outMediaTrack;if(c&>(t)||!c&>(e))return;let l=c?t||0:e,u=(a.jitterBufferTarget||0)+100;u>l||(a.jitterBufferTarget=u,this._log.debug(`set ${c?"aux ":""}${(m=a==null?void 0:a.track)==null?void 0:m.kind} jitterBuffer delay ${u} -> ${l}`))}),!r.find(a=>{let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack?t||0:e;return a.jitterBufferTarget<c}))return this._log.info(`set jitterBuffer main: ${e} aux: ${t} done`),s();this.jitterBufferTimeoutId=setTimeout(()=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:s})},1e3)}catch(n){this._log.warn(`set jitterBuffer delay error: ${n}`),clearTimeout(this.jitterBufferTimeoutId),s()}}get audioReceiver(){var e;return((e=this.singlePC)==null?void 0:e.getReceiversByUserId(this.userId)[0])||null}onDecodeFailed(){this._room.downlinkVideoCodec==="h265"&&this._room.requestRemoteFallbackToH264()}};M([ir(),Q(e=>function(...t){return new Promise((r,s)=>{let n=a=>{this.off("closed",n),s(new D({code:I.API_CALL_ABORTED,message:H({key:F.CONNECTION_ABORTED,data:a})}))};this.on("closed",n),e.apply(this,t).then(r,s).finally(()=>{this.off("closed",n)})})})],Os.prototype,"subscribe",1),M([ir()],Os.prototype,"unsubscribe",1),M([_i(()=>"jitter")],Os.prototype,"setJitterBufferDelay",1);var H_=Os;function $_(){return Q(o=>function(...i){return p(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(t=>t.outMediaTrack&&t.state==="ready"),!i.length))return;S.emit("61",{room:this});let e=o.apply(this,i);return Promise.all(i.map(t=>t.publish(this,e)))})})}function W_(){return Q(o=>function(...i){let e=o.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var G_=Ge(at());function DI(){return Math.floor(Math.random()*16383)}var Fd=class Fd extends G_.EventEmitter{constructor(e,t){super();this.room=e;this.signalChannel=t;d(this,"log");d(this,"cmdIdSeqMap",new Map);d(this,"messageMap",new Map);this.log=R.createLogger({parent:e.getLogger(),id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(G.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",r=>{[...this.messageMap.keys()].forEach(s=>{s.split("_").slice(0,-1).join("_")===r&&this.messageMap.delete(s)})})}send({cmdId:e,data:t}){let r=this.cmdIdSeqMap.get(e)||DI(),s={cmdId:e,msg:btoa(String.fromCharCode(...new Uint8Array(t))),ordered:!0,reliable:!0,streamSeq:r};this.cmdIdSeqMap.set(e,r+1),this.signalChannel.send(Y.SEND_CUSTOM_MSG,s),this.log.debug(`send custom msg: ${JSON.stringify(s)}`)}onReceiveMsg(e){let{data:t}=e.data,r=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(r){let s={userId:r,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),n=>n.charCodeAt(0)).buffer};if(t.ordered){let n=`${r}_${s.cmdId}`,a=this.messageMap.get(n);if(!a||a.lastSeq===0)a||(a={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(n,a),setTimeout(()=>this.emitMessage(s,!0),100)),a.cachedMessageMap.set(s.seq,{message:s});else if(Math.abs(a.lastSeq-s.seq)>Fd.SEQ_INTERVAL)this.messageMap.set(n,{lastSeq:s.seq,cachedMessageMap:new Map}),this.emitMessage(s);else if(s.seq>a.lastSeq){if(s.seq===a.lastSeq+1)this.emitMessage(s);else if(!a.cachedMessageMap.has(s.seq)){let c=setTimeout(()=>this.emitMessage(s,!0),5e3);a.cachedMessageMap.set(s.seq,{message:s,timeoutId:c})}}else this.log.debug(`drop message ${s.userId}-${s.cmdId}-${s.seq}`)}else this.emit("message",s)}else{this.log.warn(`receive msg from unknown user, wait peer-join tinyId: ${t.srcTinyId}`);let s=n=>{n.tinyId===t.srcTinyId&&(this.room.off("peer-join",s),this.onReceiveMsg(e))};this.room.on("peer-join",s),Ke(2e3).then(()=>this.room.off("peer-join",s))}}emitMessage(e,t=!1){var a;let r=this.messageMap.get(`${e.userId}_${e.cmdId}`),s=e;if(r){if(t){let c=[...r.cachedMessageMap.values()].sort((l,u)=>l.message.seq-u.message.seq);c[0]&&(s=c[0].message)}r.lastSeq!==0&&s.seq-r.lastSeq>1&&this.log.debug(`msg lost userId: ${s.userId} seq: ${r.lastSeq} -> ${s.seq}`),r.lastSeq=s.seq,clearTimeout((a=r.cachedMessageMap.get(s.seq))==null?void 0:a.timeoutId),r.cachedMessageMap.delete(s.seq)}this.log.debug(`receive custom msg: ${JSON.stringify(s)}`),this.emit("message",s);let n=r==null?void 0:r.cachedMessageMap.get(s.seq+1);n&&this.emitMessage(n.message)}};d(Fd,"SEQ_INTERVAL",300);var Vd=Fd;var{isString:q_,isUndefined:vo,getNetworkType:MI,isEmpty:OI}=vt,Ti=class extends Ld{constructor(e){super(e);d(this,"_businessInfo");d(this,"userManager");d(this,"_version");d(this,"_heartbeat",-1);d(this,"_lastHeartBeatTime",-1);d(this,"_stats");d(this,"_joinTimeout",-1);d(this,"_firstPublishedList",null);d(this,"_joinReject",null);d(this,"_isRelayChanged",!1);d(this,"sdpSemantics");d(this,"signalChannel",null);d(this,"uplinkConnection",null);d(this,"singlePC",null);d(this,"enableSPC",os);d(this,"_changeBigSmallRecords",new Map);d(this,"networkQuality");d(this,"_iceTransportPolicy");d(this,"forceRelay",!1);d(this,"_turnServers",[]);d(this,"_iceServersFromJoin");d(this,"_syncUserListInterval",-1);d(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160});d(this,"enableSEI",!1);d(this,"_enableAudioVolumeEvaluation",!1);d(this,"_audioVolumeIntervalId",0);d(this,"_enableMultiAuxStream",!1);d(this,"_pureAudioPushMode",!1);d(this,"_customMessageManager");d(this,"preferHW",!1);d(this,"healthDetector");d(this,"playoutDelay");d(this,"jitterBufferDelay");d(this,"_updateAudioLevelTaskId",-1);d(this,"switchRoomSubedReq");d(this,"resolveSwitchRoomSubedReq");d(this,"enableVolumeControlInIOS");this._stats=new ra(this,this._log),this.userManager=new od(this.userId,this._log),this._version=He,this.sdpSemantics=Mo,vo(e.sdpSemantics)?bi.isUnifiedPlanDefault()&&(this.sdpSemantics=gr):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${MI()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=vo(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&os,!vo(e.enableSPC)&&os&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this._initBusinessInfo(e),this.healthDetector=new P_(this)}get isMainStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isMainStreamPublished)}get isMainAudioPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.localMainAudioTrack)}get isAuxStreamPublished(){var e;return!!((e=this.uplinkConnection)!=null&&e.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex(e=>e.muteState.hasAuxiliary)>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.userMap.values()].map(e=>[e.tinyId,e.userId]))}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.videoCodec)||"h264"}get downlinkVideoCodec(){var e;return((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264"}join(e,t,r){return p(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",s=>{this.emit("peer-join",s)}),this.userManager.on("2",s=>{this.closeDownLinkConnection(s,"remote user exitRoom"),this.emit("peer-leave",s)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",n=>{var s=aa(n,[]);S.emit(C.REMOTE_PUBLISH_STATE_CHANGED,O({room:this},s)),this.emit("remote-publish-state-changed",O({},s))}),this.joinParams=e,new Promise((s,n)=>p(this,null,function*(){var a,c;this._joinReject=n;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(u){if(u instanceof D&&u.code===I.SPC_INITIALIZED_FAILED)(a=this.signalChannel)==null||a.destroy(),yield this.initialize();else return n(u)}let l=U();yield this.doJoin(e,(c=this.singlePC)==null?void 0:c.clientAbility),v.addSuccessEvent({key:521708,cost:U()-l}),s(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(l){v.addFailedEvent({key:521708,error:l}),n(l)}this._joinReject=null}))})}initSinglePC(){return p(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new jt({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",e=>this.emit("sei-message",e)),this.singlePC.on("dump",e=>this.emit("dump",e)),this.singlePC.once("error",()=>this.fallbackToMPC());try{return yield this.singlePC.initialize()}catch(e){throw this.fallbackToMPC(),new D({code:I.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((r,s)=>p(this,null,function*(){var c,l,u;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(Se.SETUP_FAILED,m=>{this.clearJoinTimeout(),S.emit(C.JOIN_SIGNAL_CONNECTION_END,{room:this,error:m}),s(m)}),he((l=(c=this.scheduleResult)==null?void 0:c.config)==null?void 0:l.singlePC)&&os&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),t&&this.playoutDelay&&(t.playoutDelay=this.playoutDelay);let n={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:e.role,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:Ll(),netType:qr(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0,isChorus:!!this.enableChorus,enableNtpAudioFrame:!!this.enableChorus&&pn()};this._log.debug(`join room signal data: ${JSON.stringify(n)}`);let a=5e3;(u=this.scheduleResult.config)!=null&&u.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(a=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{s(new D({code:I.JOIN_ROOM_FAILED,message:H({key:F.JOIN_ROOM_TIMEOUT})}))},a),S.emit(C.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?Y.SPC_JOIN_ROOM:Y.JOIN_ROOM,n),this.signalChannel.once(G.JOIN_ROOM_RESULT,m=>p(this,null,function*(){this.clearJoinTimeout();let{code:h,message:_,data:g,tinyId:E}=m.data;S.emit(C.JOIN_RECEIVED_CMD_RES,{room:this,code:h}),h===0?(this._log.info("Join room success, start heartbeat"),E&&(this.tinyId=E),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=g.publishers,this._iceServersFromJoin=g.iceServer?[g.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then(()=>{var A;(A=this.singlePC)==null||A.connect(L(O({},g.ability),{useVp8:g.ability.useVp8||!!e.useVp8,useH265:g.ability.useH265&&!!e.useH265})).catch(()=>{})}),r()):(this._log.error(`Join room failed result: ${h} error: ${_}`),s(new D({code:I.JOIN_ROOM_FAILED,extraCode:h,message:H({key:F.JOIN_ROOM_FAILED,data:{error:_,code:h}})})))}))}))}reJoin(){return p(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this.joinParams.roomId}`);let e,t=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,t.push(this.initSinglePC().then(r=>(e=r,r)))),this.signalChannel&&(this.signalChannel.close(),t.push(this.signalChannel.connect())),yield Promise.all(t),yield this.doJoin(L(O({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),e),this._log.warn("reJoin success"),se.logSuccessEvent({userId:this.userId,eventType:Ze.REJOIN}),this.singlePC){let r=s=>{var n;s.state==="CONNECTED"&&((n=this.singlePC)==null||n.off(Li.CONNECTION_STATE_CHANGED,r),this.uplinkConnection instanceof hm&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(a=>{a.installEvents(),a.onSinglePCReconnected()}))};this.singlePC.on(Li.CONNECTION_STATE_CHANGED,r),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof ia&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(e){this._log.warn(`reJoin fail ${e}`),this.reset(),se.logFailedEvent({userId:this.userId,eventType:Ze.REJOIN,error:e}),this.emit("error",new D({code:I.JOIN_ROOM_FAILED,message:H({key:F.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}})}initialize(){return p(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),r=this.signalChannel||s_(this.userId),s=!!(r&&r.isConnected&&r.keepAlive&&r.userId===this.userId&&r.room===this),n;return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(n=this.scheduleResult.domains[0]),this._log.info(`${s?"reuse":"setup"} signal channel`),s?(r.url=e,r.backupUrl=t,r.room=this,this.signalChannel=r):(r&&r.close(),this.signalChannel=new bs({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?n:void 0}),this._customMessageManager=new Vd(this,this.signalChannel),this._customMessageManager.on("message",a=>{this.emit("custom-message",a)})),this.networkQuality||(this.networkQuality=new Ms({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(Ms.EVENT_NETWORK_QUALITY,a=>{var c;this.emit("network-quality",a),(c=this.singlePC)==null||c.detectTCPAndUDP(a)})),tt(this,this.signalChannel).add(Se.CONNECTION_STATE_CHANGED,a=>{S.emit(C.SIGNAL_CONNECTION_STATE_CHANGED,O({room:this},a)),this.emit("signal-connection-state-changed",a)}).add(Se.RECONNECT_FAILED,a=>{this.reset(),this.emit("error",a)}).add(G.PEER_JOIN,a=>{let{srcTinyId:c,userId:l,role:u}=a.data.data;this.userManager.addUser({userId:l,tinyId:c,role:u})}).add(G.PEER_LEAVE,a=>{let{userId:c,reason:l=0}=a.data.data;this.userManager.deleteUser(c,l)}).add(G.UPDATE_REMOTE_MUTE_STAT,a=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(a.data)}).add(G.CLIENT_BANNED,a=>{let c=a.data.data,{reason:l}=c;if(se.uploadEvent({log:`stat-banned:${l}`,userId:this.userId}),l==="user_time_out"){this._log.warn(`${l} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[l==="kick"?"error":"info"](`user was banned because of [${l}]`),this.reset(),this.emit("banned",{reason:l})}).add(G.SEND_SWITCH_ROOM_SUBED_REQ,a=>{if(!this.singlePC)return;let{subList:c}=a.data.data;this._log.info(`auto subscribe ${_t(c,{keysToInclude:["userId"]})}`),c.forEach(l=>{this.singlePC.autoSubscribedUserMap.set(l.userId,l)}),this.resolveSwitchRoomSubedReq()}).add(G.FALLBACK_CODEC,a=>p(this,null,function*(){var l,u,m,h,_;let c=a.data.data;((l=c.videoControlInfo)==null?void 0:l.enableH265Enc)===0&&((u=this.singlePC)==null?void 0:u.videoCodec)==="h265"&&(this._log.warn(`fallback codec enableH265Enc: ${(m=c.videoControlInfo)==null?void 0:m.enableH265Enc}`),v.addCount({key:513e3}),yield(h=this.singlePC)==null?void 0:h.switchVideoEncoder("h264"),yield(_=this.uplinkConnection)==null?void 0:_.sendMediaSettings())})),this.signalChannel.once(Se.SETUP_SUCCESS,a=>{this.tinyId=a.signalInfo.tinyId,S.emit(C.JOIN_SIGNAL_CONNECTION_END,{room:this})}),S.emit(C.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),s&&S.emit(C.JOIN_SIGNAL_CONNECTION_END,{room:this}),s})}setSignalChannel(e){this.signalChannel=e,e||Le(this)}leave(){return p(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),S.emit(C.LEAVE_SEND_CMD,{room:this}),(e=this.signalChannel)==null||e.send(Y.LEAVE_ROOM),this.switchRoomSubedReq=void 0})}clearNetworkQuality(){this.networkQuality&&(this.networkQuality.stop(),delete this.networkQuality)}closeConnections(){this.remotePublishedUserMap.forEach(e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=oe.run("ric",this.doHeartbeat.bind(this),{delay:2e3}),this.enableChorus&&this.startUpdateNTPTime())}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),oe.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return p(this,null,function*(){var n;let e=this.badCaseDetector.getMonitorFreeze(),t=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});this.badCaseDetector.resetMonitor();let r=(n=this.signalChannel)!=null&&n.isConnected?Ef(this.userId):[],s=L(O({str_sdk_version:Ls,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:r,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},t),{msg_device_info:O({uint32_terminal_type:15,str_device_name:si(),str_os_version:"",uint32_net_type:qr()},t.msg_device_info)});if(this.heartbeatReport=s,this.heartbeatCount++,S.emit(C.HEARTBEAT_REPORT,{room:this,report:s}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(Y.ON_QUALITY_REPORT,s);let a=Date.now();this._lastHeartBeatTime>0&&a-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${a-this._lastHeartBeatTime}`),this._lastHeartBeatTime=a,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",L(O({},s),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.filter(r=>r.flag!==Qd).map(({userId:r,srcTinyId:s,flag:n})=>{r===this.userId&&(this.uplinkConnection&&(this.uplinkConnection.flag=n),this.localPublishFlag!==n&&(this.localPublishFlag=n,this.emit("local-publish-flag-changed",n)));let a=this.remotePublishedUserMap.get(r);return a&&this.checkSubscribeBigSmallVideo(a),{userId:r,tinyId:s,flag:n}});e.data.mixRobotList.forEach(({userId:r,srcTinyId:s,flag:n,mixUserList:a})=>{t.unshift({userId:r,tinyId:s,flag:n,isRobot:!0,mixUserList:a})}),e.data.fakeMixUser&&(e.data.fakeMixUser.tinyId=e.data.fakeMixUser.srcTinyId,t.push(e.data.fakeMixUser)),S.emit(C.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),t.find(r=>r.userId===this.userId)||(this.localPublishFlag=0,this.emit("local-publish-flag-changed",0)),this.userManager.setRemotePublishedUserList(t)}closeUplink(e="you unpublished"){this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish().catch(()=>{}),this.uplinkConnection.close(e),this.uplinkConnection instanceof ia&&(this.uplinkConnection=null)),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:t,flag:r,isRobot:s}){let n=new(this.singlePC?H_:tm)({userId:e,tinyId:t,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:s});this.userManager.addRemotePublishedUser(n),this.installDownlinkEvents(n,e),this.emit("remote-published",n)}closeDownLinkConnection(e,t="remote user unpublished"){let r=this.remotePublishedUserMap.get(e);r&&(r.close(t),this.emit("remote-unpublished",r))}installDownlinkEvents(e,t){e.on("error",r=>{let s=r.getCode();s!==I.ICE_TRANSPORT_ERROR&&(s===I.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",r))}),e.on("connection-state-changed",r=>{this.emit("media-connection-state-changed",L(O({},r),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=oe.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){oe.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then(e=>{this.userManager.setUserList(e)}).catch(e=>{this._log.debug(`sync user list failed: ${e}`)})}getUserList(){var e;return(e=this.signalChannel)!=null&&e.isConnected?this.signalChannel.sendWaitForResponse({command:Y.GET_USER_LIST,responseCommand:G.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:t})=>{let{code:r,message:s}=t;if(r===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:c,role:l})=>({userId:a,tinyId:c,role:l}));throw H({key:F.SIGNAL_RESPONSE_FAILED,data:{signalResponse:G.USER_LIST_RES,code:r,message:s}})}):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this.signalChannel&&!this.signalChannel.isOnline||!zh)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let e=this.getAllConnections();if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(e[t].getReconnectionCount()<6)return!1;return!0}checkConnectionsToReconnect(){var e;this.singlePC?((e=this.singlePC.getPeerConnection())==null?void 0:e.connectionState)===Ce.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(r=>{if(r instanceof pt&&!r.getIsReconnecting()){let s=r.getPeerConnection();s&&s.connectionState===Ce.CLOSED&&(this._log.warn(`[${r.getUserId()}] pc is closed but not reconnect`),r.startReconnection())}})}fallbackToMPC(){return p(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),se.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(e=this.singlePC)==null||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin()),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new ia({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),t.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localMainAudioTrack,localVideoTrack:t.localMainVideoTrack,isAuxiliary:!1})),t.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localAuxAudioTrack,localVideoTrack:t.localAuxVideoTrack,isAuxiliary:!0})),t.close()}for(let t of[...this.remotePublishedUserMap.values()]){let r=new tm({userId:t.userId,tinyId:t.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:t.flag,remoteAudioTrack:t.remoteAudioTrack,remoteVideoTrack:t.remoteVideoTrack,remoteAuxiliaryTrack:t.remoteAuxiliaryTrack});this.installDownlinkEvents(r,t.userId),this.remotePublishedUserMap.set(t.userId,r),t.isMainStreamSubscribed&&(yield r.subscribe(t.subscribeState,"main")),t.isAuxStreamSubscribed&&(yield r.subscribe(t.subscribeState,"auxiliary"))}})}destroy(){this.isDestroyed||(this.signalChannel&&(this._log.info("destroying SignalChannel"),this.signalChannel.close(),this.signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new D({code:I.INVALID_OPERATION,message:H({key:F.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),oe.clearTask(this._audioVolumeIntervalId))}switchRole(e){return p(this,null,function*(){this.role!==e&&(e==="audience"&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))})}doSwitchRole(e){let t={command:Y.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:G.SWITCH_ROLE_RES,retries:1};return this._log.info(`switchRole signal data: ${JSON.stringify(t.data)}`),this.signalChannel.sendWaitForResponseWithRetry(t).then(r=>{let{code:s,message:n}=r.data;if(s!==0)throw new D({code:I.SWITCH_ROLE_FAILED,message:H({key:F.SWITCH_ROLE_FAILED,data:{message:n,code:s}})});this.role=e}).catch(r=>{throw r instanceof D&&r.getCode()===I.API_CALL_TIMEOUT&&(r=new D({code:I.SWITCH_ROLE_FAILED,message:H({key:F.SWITCH_ROLE_TIMEOUT})})),this._log.error(r),r})}_initUplinkConnection(){this.uplinkConnection=this.singlePC?new hm({userId:this.userId,tinyId:this.tinyId,room:this}):new ia({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",e=>{this.emit("media-connection-state-changed",L(O({},e),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",e=>{let t=e.getCode();t!==I.ICE_TRANSPORT_ERROR&&(t===I.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",e))})}publish(e){return p(this,null,function*(){var r;this.uplinkConnection||this._initUplinkConnection();let t=`${e.streamType} ${e.isAudio&&e.isScreen?"screen":""}${e.kind}`;this._log.info(`publish() => ${t}`),yield(r=this.singlePC)==null?void 0:r.waitForPeerConnectionConnected(),yield this.uplinkConnection.publish({localAudioTrack:e instanceof kt?e:null,localVideoTrack:e instanceof je?e:null,isAuxiliary:e.streamType==="auxiliary"||e.isScreen})})}unpublish(e){return p(this,null,function*(){if(!(this.scene==="live"&&this.role!=="anchor"||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)){try{let t=`${e.streamType} ${e.isAudio&&e.isScreen?"screen":""}${e.kind}`;this._log.info(`unpublish() => ${t}`),yield this.uplinkConnection.unpublish({localAudioTrack:e instanceof kt?e:null,localVideoTrack:e instanceof je?e:null})}catch(t){}this.localTracks.size===0&&this.closeUplink("you unpublished")}})}addTrack(e){if(!this.uplinkConnection||!e.mediaTrack)return Promise.resolve();let t=this.uplinkConnection.addTrack(e);return e.publish(this,t),t}removeTrack(e){return!this.uplinkConnection||!e.mediaTrack?Promise.resolve():(e.unpublish(),this.uplinkConnection.removeTrack(e))}replaceTrack(e){return!this.uplinkConnection||!e.mediaTrack||!nu()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{t&&S.emit(C.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return p(this,null,function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return p(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:f.VIDEO,videoType:f.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(...e){return p(this,null,function*(){if(e=e.filter(n=>!n.isSubscribed),e.length===0)return;let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let s=e.find(n=>n.mediaType===2)?"auxiliary":"main";try{let n=O({},r.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:n.audio=!0;break;case 4:n.video=!0;break;case 8:n.smallVideo=!0;break;case 2:n.auxiliary=!0;break}});let a=this._changeBigSmallRecords.get(t);a&&a.options.smallVideo&&r.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),S.emit(C.SUBSCRIBE_START,{room:this,streamType:s,remotePublishedUser:r,subscribeState:n}),this._log.info(`subscribe() => ${t} ${s} [${Nd(n)}] prev: [${Nd(r.subscribeState)}]`),yield r.subscribe(n,s),this._log.info(`subscribe ${t} ${s} done`);for(let c of e)c.mediaTrack||(yield c.waitHasMediaTrack());S.emit(C.SUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:r})}catch(n){let a=n instanceof D?n.getCode():I.UNKNOWN,c=n;throw n instanceof D?a===I.REMOTE_STREAM_NOT_EXIST&&(c=new D({code:I.API_CALL_ABORTED,message:H({key:F.API_CALL_ABORTED,data:{message:n.message,userId:t,streamType:s}})}),this._log.warn(c)):(c=new D({code:a,message:H({key:F.SUBSCRIBE_FAILED,data:{message:n.message,userId:t,streamType:s}})}),this._log.error(c)),c}})}unsubscribe(...e){return p(this,null,function*(){let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let s=e.find(n=>n.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${t} ${s}`);try{yield r.unsubscribe({remoteTracks:e,streamType:s})}catch(n){this._log.warn(`unsubscribe() => failed ${n}`)}e.forEach(n=>{n.unsubscribe(),n.mediaType===8&&n.setMediaType(4)}),S.emit(C.UNSUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:r})})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(e=2e3,t){if(e<=0){this._enableAudioVolumeEvaluation=!1,oe.clearTask(this._audioVolumeIntervalId);return}e=Math.floor(Math.max(e,100)),S.emit(C.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&oe.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=oe.run("intervalInWorker",()=>{var s;so.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];(s=this.remotePublishedUserMap)==null||s.forEach(n=>{if(n.muteState.hasAudio){!so.isRunning&&n.muteState.audioAvailable&&n.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(n):n.remoteAudioTrack.volume=0;let a=Math.floor(n.remoteAudioTrack.getAudioLevel()*100);r.push({userId:n.userId,volume:a,floatVolume:n.remoteAudioTrack.getInternalAudioLevel()})}}),this.emit("audio-volume",r)},{delay:e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return p(this,null,function*(){var n;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||this._updateAudioLevelTaskId!==-1)return;let r=(n=this.uplinkConnection.getPeerConnection())==null?void 0:n.getSenders()[0];if(!r)return;let s=Math.max(e,500);this._log.warn(`updateAudioLevelFromSenderStat ${s}`),this._updateAudioLevelTaskId=oe.run("intervalInWorker",()=>p(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack){this.stopUpdateAudioLevelFromSenderStat();return}let a=yield r.getStats();if(this._updateAudioLevelTaskId<0)return;let{localMainAudioTrack:c}=this.uplinkConnection;a.forEach(l=>{l.type==="media-source"&&l.audioLevel&&(c.volume=l.audioLevel)})}),{delay:s,backgroundTask:t})})}stopUpdateAudioLevelFromSenderStat(){var e;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),oe.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,(e=this.uplinkConnection)!=null&&e.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(e){var s;let{audioReceiver:t}=e;if(!au||!t)return;let r=(s=t.getSynchronizationSources()[0])==null?void 0:s.audioLevel;z(r)?e.remoteAudioTrack.volume=Math.min(r*2,1):t.getStats().then(n=>{n.forEach(a=>{a.type==="inbound-rtp"&&z(a.audioLevel)&&(e.remoteAudioTrack.volume=a.audioLevel)})})}getLocalAudioStats(){return p(this,null,function*(){var t;let e={};return e[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},(t=this.uplinkConnection)!=null&&t.localMainAudioTrack&&(e[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),e})}getLocalVideoStats(){return p(this,null,function*(){var t,r;let e={};return e[this.userId]=((r=(t=this.uplinkConnection)==null?void 0:t.localMainVideoTrack)==null?void 0:r.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},e})}getTransportStats(){return p(this,null,function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let r=yield this._stats.getReceiverStats(t);e.downlinksRTT[r.userId]=r.rtt}return e})}getRemoteVideoStats(e){return p(this,null,function*(){let t={};for(let[r,s]of this.remotePublishedUserMap)e==="main"&&s.muteState.hasVideo&&(t[r]=s.remoteVideoTrack.stat),e==="auxiliary"&&s.muteState.hasAuxiliary&&(t[r]=s.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return p(this,null,function*(){let e={};for(let[t,r]of this.remotePublishedUserMap)r.muteState.hasAudio&&(e[t]=r.remoteAudioTrack.stat);return e})}setTurnServer(e,t){this._log.info(`set turn server: ${JSON.stringify(e)} ${t||""}`);let r=[];Array.isArray(e)?e.forEach(s=>r.push(vt.getTurnServer(s))):vt.isPlainObject(e)&&r.push(vt.getTurnServer(e)),this._turnServers=r,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Y.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:G.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Y.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:G.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendStartPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?Y.START_PUBLISH_TENCENT_CDN:Y.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?G.START_PUBLISH_TENCENT_CDN_RES:G.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"}).catch(r=>{if(r.code!==I.API_CALL_ABORTED)throw r})}sendStopPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?Y.STOP_PUBLISH_TENCENT_CDN:Y.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?G.STOP_PUBLISH_TENCENT_CDN_RES:G.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"}).catch(r=>{if(r.code!==I.API_CALL_ABORTED)throw r})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Y.START_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:G.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Y.UPDATE_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:G.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Y.STOP_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:G.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"}).catch(t=>{if(t.code!==I.API_CALL_ABORTED)throw t})}sendAbilityStatus(e){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:Y.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:G.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(r=>{})}getIceServers(e){var t,r;return this._turnServers.length>0?this._turnServers:(t=this.scheduleResult.iceServers)!=null&&t.length?this.scheduleResult.iceServers:e!=null&&e.length?e:(r=this._iceServersFromJoin)!=null&&r.length?this._iceServersFromJoin:[]}getIceTransportPolicy(){return this.forceRelay?"relay":this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=vt.getEnv();return t?(e.mainUrl=`wss://${t}.rtc.qq.com`,e.backupUrl=e.mainUrl):this.proxy_ws?(e.mainUrl=this.proxy_ws,e.backupUrl=e.mainUrl):this.proxy_unified?(e.mainUrl=`wss://${this.proxy_unified}`,e.backupUrl=e.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(e.mainUrl=`wss://${this.scheduleResult.domains[0]}`,e.backupUrl=e.mainUrl,this.scheduleResult.domains[1]&&(e.backupUrl=`wss://${this.scheduleResult.domains[1]}`)),e}getSignalInfo(){var e;return((e=this.signalChannel)==null?void 0:e.getSignalInfo())||{clientIp:"",relayIp:""}}reset(e=!1){this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this.signalChannel&&(e&&this.signalChannel.keepAlive&&this.signalChannel.isConnected?this.signalChannel.stopKeepAliveIn(3600):(this.signalChannel.close(),this.setSignalChannel(null))),this.localPublishFlag=0,this.heartbeatCount=0,this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}}checkSubscribeBigSmallVideo(e){return p(this,null,function*(){let{subscribeState:t,userId:r,muteState:{hasSmall:s,hasVideo:n}}=e;if(!s&&!n||!t.video&&!t.smallVideo)return;let a=this._changeBigSmallRecords.get(r);if(!a||a.isSubscribing||a.reSubscribeCount<=0)return;let{options:c,reSubscribeCount:l}=a;if(c.video&&t.video||c.smallVideo&&t.smallVideo&&s)return;let u={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:c.video,smallVideo:c.smallVideo};try{if(!s&&u.smallVideo&&(u.video=!0,u.smallVideo=!1),u.smallVideo===t.smallVideo&&u.video===t.video)return;a.isSubscribing=!0,a.reSubscribeCount=l-1,yield e.subscribe(u,"main"),e.remoteVideoTrack.setMediaType(u.smallVideo?8:4),this._log.info(`change [${r}] to ${u.smallVideo?"small":"big"} video successfully. count ${Oo-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=Oo}catch(m){this._log.info(`change [${r}] to ${u.smallVideo?"small":"big"} video failed. count ${Oo-a.reSubscribeCount}. reason: ${m}`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(r)}})}changeType(e,t){let s={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:Oo};this._changeBigSmallRecords.set(t.userId,s),this._log.info(`set [${t.userId}] video prefer type: ${e?"small":"big"}`),this.emit("subscribe-small-video-changed",{userId:t.userId,isSmall:e});let n=this.remotePublishedUserMap.get(t.userId);n&&this.checkSubscribeBigSmallVideo(n)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(q_(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!vo(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_PURE_AUDIO})});this._pureAudioPushMode=e.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!vo(e.userDefineRecordId)){let r=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(r)===null)throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!vo(e.userDefinePushArgs))if(q_(e.userDefinePushArgs)&&String(e.userDefinePushArgs)&&String(e.userDefinePushArgs).length<=256)t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=e.userDefinePushArgs;else throw new D({code:I.INVALID_PARAMETER,message:H({key:F.INVALID_USER_DEFINE_PUSH_ARGS})});OI(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){return p(this,null,function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&hi)return this.singlePC.enableInsertableStreams=!0,yield this.singlePC.waitForPeerConnectionConnected(),yield this.singlePC.startReconnection()})}sendSignalMessage(e){var t;return this.signalChannel?(t=this.signalChannel)==null?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new D({code:I.INVALID_OPERATION,message:"not join"}))}get enableCodecPipeline(){return this.videoManager.encodePipeline.length>0||this.videoManager.decodePipeline.length>0||this.audioManager.encodePipeline.length>0||this.audioManager.decodePipeline.length>0}get scriptTransformWorker(){var e;return(e=this.singlePC)==null?void 0:e.scriptTransformWorker}switchRoom(e){return p(this,null,function*(){var _;if(!this.signalChannel||!this.singlePC)return;let{roomId:t,strRoomId:r,userSig:s,privateMapKey:n}=e,a=((_=this.scheduleResult.config)==null?void 0:_.autoSubscribeCount)||(e==null?void 0:e.autoSubscribeCount)||1,c=String(this.useStringRoomId?r:t),l=[];for(let g=0;g<a;g++)l.push({audioSsrc:xt(),bigVideoSsrc:xt(),bigVideoRtxSsrc:xt(),auxVideoSsrc:xt(),auxVideoRtxSsrc:xt()});let u={currRoomId:this.roomId,targetRoomId:c,useStringRoomId:this.useStringRoomId,ability:this.singlePC.clientAbility,userSig:s,privateMapKey:n!=null?n:this.privateMapKey,subscribe:l};this.singlePC.autoSubscribedUserMap.clear(),this.singlePC.autoSubscribedSsrcGroups.clear(),this.singlePC.autoSubscribedSsrcGroups.set(c,l);let m=this.roomId;this.roomId=this.useStringRoomId?r:String(t),this.switchRoomSubedReq=new Promise(g=>{this.resolveSwitchRoomSubedReq=g,Ke(5e3).then(g)}),S.emit(C.SWITCH_ROOM_START,{room:this}),yield this.singlePC.waitForPeerConnectionConnected();let h;try{this.userManager.clear(),h=yield this.signalChannel.sendWaitForResponse({command:Y.SWITCH_ROOM,responseCommand:G.SEND_SWITCH_ROOM_RES,data:u});let{code:g,message:E}=h.data;if(g===0)this.userSig=s,vo(n)||(this.privateMapKey=n),S.emit(C.SWITCH_ROOM_SUCCESS,{room:this,currentRoomId:m,targetRoomId:c});else{this._log.error(`switch room failed. result: ${g} error: ${E}`);let A=new D({code:I.SWITCH_ROOM_FAILED,extraCode:g,message:E});throw S.emit(C.SWITCH_ROOM_FAILED,{room:this,error:A}),A}}catch(g){throw this.singlePC.autoSubscribedSsrcGroups.clear(),this.roomId=m,this.resolveSwitchRoomSubedReq(),g}})}isSwitchRoomSupported(){var t;let e="unable to use switchRoom API, fallback to exitRoom and enterRoom.";return((t=this.scheduleResult.config)==null?void 0:t.switchRoom)!==!0?(this._log.warn(`${e} Reason: this sdkAppId is not supported, please contact us [https://trtc.io/contact] to enable it.`),!1):this.scene!=="live"?(this._log.warn(`${e} Reason: the scene is not 'live'.`),!1):this.role!=="audience"?(this._log.warn(`${e} Reason: the role is not 'audience'.`),!1):this.singlePC?!0:(this._log.warn(`${e} Reason: is not using single peerConnection.`),!1)}requestRemoteFallbackToH264(){var e;(e=this.singlePC)==null||e.requestRemoteFallbackToH264()}startUpdateNTPTime(){if(!this.signalChannel)return;let e=[];for(let t=0;t<5;t++)e.push(this.updateNTPTime());return Promise.all(e).then(t=>{var c;let r=t[0].offset,s=t[0].offset;t.forEach(l=>{r=Math.min(l.offset,r),s=Math.max(l.offset,s)});let n=Math.floor(t.reduce((l,u)=>l+u.rtt,0)/t.length),a=Math.floor(t.reduce((l,u)=>l+u.offset,0)/t.length);(s-r>30||n>50)&&setTimeout(()=>this.startUpdateNTPTime(),5e3),da(a),(c=this.scriptTransformWorker)==null||c.postMessage({type:"ntp-offset",data:a}),this._log.debug(`ntp updated offset: ${a}`),this.emit("ntp-time-updated")}).catch(t=>{this._log.warn(`ntp updated failed: ${t}`)})}updateNTPTime(){let e=Date.now();return this.signalChannel.sendWaitForResponse({command:Y.UPDATE_NETWORK_TIME,responseCommand:G.UPDATE_NETWORK_TIME_RESULT,addReceiveTime:!0,data:{clientSendTime:String(e)},enableLog:!1}).then(t=>{let r=Number(t.data.data.serverSendTime),s=Number(t.data.data.serverRecvTime),n=t.data.receiveTime||Date.now(),a=(s-e+(r-n))/2;return{rtt:n-e-(s-r),offset:a}})}};M([ye(["left",J.INIT],"joined"),Mt({settings:{retries:1,timeout:0},onRetrying(e){this._log.warn(`join retry ${e}`)},onRetryFailed(e){this._log.error("join failed",e)},onError(e,t){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),Lt(!0),this.reset(),t()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),t()):(this.reset(),t())}}),e_()],Ti.prototype,"join",1),M([ye("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),t_(),Lc("leave room"),yn({fnName:"publish",validateArgs:!1}),yn({fnName:"unsubscribe",validateArgs:!1})],Ti.prototype,"leave",1),M([_i(e=>e.mediaType),$_(),Mt({settings:{retries:Hi,timeout:e=>Zt(e)},onError(e,t,r,[s]){var n;(n=e.message)!=null&&n.includes("timeout")?(this._log.warn(`publish ${s.strMediaType} timeout`,e),t()):(this._log.error(`publish ${s.strMediaType} failed: ${e}`),r(e),S.emit(C.PUBLISH_FAILED,{room:this}))}})],Ti.prototype,"publish",1),M([yn({fnName:"publish"}),_i(e=>e.mediaType),W_(),Ct(function(){var e,t;this.localTracks.size===0&&Rr()&&((t=(e=this.singlePC)==null?void 0:e.getPeerConnection())==null||t.getSenders().forEach(r=>r.track&&r.replaceTrack(null)))})],Ti.prototype,"unpublish",1),M([Oc(e=>{if(e.code!==I.API_CALL_ABORTED)throw e}),_i(e=>e.userId)],Ti.prototype,"replaceTrack",1),M([_i((...e)=>e[0].userId),Eo(),i_(),Mt({settings:{retries:Hi,timeout:e=>Zt(e)},onError(e,t,r,s){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error(`subscribe failed: ${e}`),r(e),S.emit(C.SUBSCRIBE_FAILED,{room:this,remoteTracks:s}))}})],Ti.prototype,"subscribe",1),M([yn({fnName:"subscribe",callback(...e){this.singlePC||e.forEach(t=>{let r=this.remotePublishedUserMap.get(t.userId);r&&!r.isMainStreamSubscribed&&!r.isAuxStreamSubscribed&&r.close("you unsubscribed")})}}),_i((...e)=>e[0].userId)],Ti.prototype,"unsubscribe",1);ea.create=ea._create.bind(ea,Ti);hu(30);var W4=ea;export{W4 as default};
|