trtc-sdk-v5 5.8.2-beta.2 → 5.8.2-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/plugins/cdn-streaming/package.json +1 -1
- package/plugins/cross-room/cross-room.esm.js +1 -1
- package/plugins/cross-room/cross-room.iife.js +1 -1
- package/plugins/cross-room/package.json +1 -1
- package/plugins/debug/package.json +1 -1
- package/plugins/device-detector/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/virtual-background/package.json +1 -1
- package/plugins/video-effect/watermark/package.json +1 -1
- package/trtc.esm.js +26 -26
- package/trtc.js +1 -1
package/trtc.esm.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
var Bh=Object.create;var Yr=Object.defineProperty,$h=Object.defineProperties,Hd=Object.getOwnPropertyDescriptor,Fh=Object.getOwnPropertyDescriptors,Hh=Object.getOwnPropertyNames,To=Object.getOwnPropertySymbols,Gd=Object.getPrototypeOf,ca=Object.prototype.hasOwnProperty,Wd=Object.prototype.propertyIsEnumerable,Gh=Reflect.get;var Kr=Math.pow,aa=(r,i,e)=>i in r?Yr(r,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[i]=e,N=(r,i)=>{for(var e in i||(i={}))ca.call(i,e)&&aa(r,e,i[e]);if(To)for(var e of To(i))Wd.call(i,e)&&aa(r,e,i[e]);return r},P=(r,i)=>$h(r,Fh(i));var Jd=(r,i)=>{var e={};for(var t in r)ca.call(r,t)&&i.indexOf(t)<0&&(e[t]=r[t]);if(r!=null&&To)for(var t of To(r))i.indexOf(t)<0&&Wd.call(r,t)&&(e[t]=r[t]);return e};var Jt=(r,i)=>()=>(i||r((i={exports:{}}).exports,i),i.exports),Zr=(r,i)=>{for(var e in i)Yr(r,e,{get:i[e],enumerable:!0})},Wh=(r,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let s of Hh(i))!ca.call(r,s)&&s!==e&&Yr(r,s,{get:()=>i[s],enumerable:!(t=Hd(i,s))||t.enumerable});return r};var Se=(r,i,e)=>(e=r!=null?Bh(Gd(r)):{},Wh(i||!r||!r.__esModule?Yr(e,"default",{value:r,enumerable:!0}):e,r));var y=(r,i,e,t)=>{for(var s=t>1?void 0:t?Hd(i,e):i,o=r.length-1,n;o>=0;o--)(n=r[o])&&(s=(t?n(i,e,s):n(s))||s);return t&&s&&Yr(i,e,s),s};var u=(r,i,e)=>(aa(r,typeof i!="symbol"?i+"":i,e),e);var Ie=(r,i,e)=>Gh(Gd(r),e,i);var _=(r,i,e)=>new Promise((t,s)=>{var o=c=>{try{a(e.next(c))}catch(d){s(d)}},n=c=>{try{a(e.throw(c))}catch(d){s(d)}},a=c=>c.done?t(c.value):Promise.resolve(c.value).then(o,n);a((e=e.apply(r,i)).next())});var Ne=Jt((nf,da)=>{"use strict";var Jh=Object.prototype.hasOwnProperty,xe="~";function es(){}Object.create&&(es.prototype=Object.create(null),new es().__proto__||(xe=!1));function jh(r,i,e){this.fn=r,this.context=i,this.once=e||!1}function jd(r,i,e,t,s){if(typeof e!="function")throw new TypeError("The listener must be a function");var o=new jh(e,t||r,s),n=xe?xe+i:i;return r._events[n]?r._events[n].fn?r._events[n]=[r._events[n],o]:r._events[n].push(o):(r._events[n]=o,r._eventsCount++),r}function So(r,i){--r._eventsCount===0?r._events=new es:delete r._events[i]}function be(){this._events=new es,this._eventsCount=0}be.prototype.eventNames=function(){var i=[],e,t;if(this._eventsCount===0)return i;for(t in e=this._events)Jh.call(e,t)&&i.push(xe?t.slice(1):t);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i};be.prototype.listeners=function(i){var e=xe?xe+i:i,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var s=0,o=t.length,n=new Array(o);s<o;s++)n[s]=t[s].fn;return n};be.prototype.listenerCount=function(i){var e=xe?xe+i:i,t=this._events[e];return t?t.fn?1:t.length:0};be.prototype.emit=function(i,e,t,s,o,n){var a=xe?xe+i:i;if(!this._events[a])return!1;var c=this._events[a],d=arguments.length,l,p;if(c.fn){switch(c.once&&this.removeListener(i,c.fn,void 0,!0),d){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,s),!0;case 5:return c.fn.call(c.context,e,t,s,o),!0;case 6:return c.fn.call(c.context,e,t,s,o,n),!0}for(p=1,l=new Array(d-1);p<d;p++)l[p-1]=arguments[p];c.fn.apply(c.context,l)}else{var m=c.length,f;for(p=0;p<m;p++)switch(c[p].once&&this.removeListener(i,c[p].fn,void 0,!0),d){case 1:c[p].fn.call(c[p].context);break;case 2:c[p].fn.call(c[p].context,e);break;case 3:c[p].fn.call(c[p].context,e,t);break;case 4:c[p].fn.call(c[p].context,e,t,s);break;default:if(!l)for(f=1,l=new Array(d-1);f<d;f++)l[f-1]=arguments[f];c[p].fn.apply(c[p].context,l)}}return!0};be.prototype.on=function(i,e,t){return jd(this,i,e,t,!1)};be.prototype.once=function(i,e,t){return jd(this,i,e,t,!0)};be.prototype.removeListener=function(i,e,t,s){var o=xe?xe+i:i;if(!this._events[o])return this;if(!e)return So(this,o),this;var n=this._events[o];if(n.fn)n.fn===e&&(!s||n.once)&&(!t||n.context===t)&&So(this,o);else{for(var a=0,c=[],d=n.length;a<d;a++)(n[a].fn!==e||s&&!n[a].once||t&&n[a].context!==t)&&c.push(n[a]);c.length?this._events[o]=c.length===1?c[0]:c:So(this,o)}return this};be.prototype.removeAllListeners=function(i){var e;return i?(e=xe?xe+i:i,this._events[e]&&So(this,e)):(this._events=new es,this._eventsCount=0),this};be.prototype.off=be.prototype.removeListener;be.prototype.addListener=be.prototype.on;be.prefixed=xe;be.EventEmitter=be;typeof da!="undefined"&&(da.exports=be)});var za=Jt((bE,Cu)=>{var Au=Cu.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(r){return r.encoding?"rtpmap:%d %s/%s/%s":r.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(r){return r.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(r){return r.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(r){return"extmap:%d"+(r.direction?"/%s":"%v")+(r["encrypt-uri"]?" %s":"%v")+" %s"+(r.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(r){return r.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(r){var i="candidate:%s %d %s %d %s %d typ %s";return i+=r.raddr!=null?" raddr %s rport %d":"%v%v",i+=r.tcptype!=null?" tcptype %s":"%v",r.generation!=null&&(i+=" generation %d"),i+=r["network-id"]!=null?" network-id %d":"%v",i+=r["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(r){var i="ssrc:%d";return r.attribute!=null&&(i+=" %s",r.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(r){return r.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(r){return r.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(r){return"imageattr:%s %s %s"+(r.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(r){return"simulcast:%s %s"+(r.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(r){return"ts-refclk:%s"+(r.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(r){var i="mediaclk:";return i+=r.id!=null?"id=%s %s":"%v%s",i+=r.mediaClockValue!=null?"=%s":"",i+=r.rateNumerator!=null?" rate=%s":"",i+=r.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(Au).forEach(function(r){var i=Au[r];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var bu=Jt(ei=>{var vr=function(r){return String(Number(r))===r?Number(r):r},ep=function(r,i,e,t){if(t&&!e)i[t]=vr(r[1]);else for(var s=0;s<e.length;s+=1)r[s+1]!=null&&(i[e[s]]=vr(r[s+1]))},tp=function(r,i,e){var t=r.name&&r.names;r.push&&!i[r.push]?i[r.push]=[]:t&&!i[r.name]&&(i[r.name]={});var s=r.push?{}:t?i[r.name]:i;ep(e.match(r.reg),s,r.names,r.name),r.push&&i[r.push].push(s)},Ru=za(),ip=RegExp.prototype.test.bind(/^([a-z])=(.*)/);ei.parse=function(r){var i={},e=[],t=i;return r.split(/(\r\n|\r|\n)/).filter(ip).forEach(function(s){var o=s[0],n=s.slice(2);o==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(Ru[o]||[]).length;a+=1){var c=Ru[o][a];if(c.reg.test(n))return tp(c,t,n)}}),i.media=e,i};var yu=function(r,i){var e=i.split(/=(.+)/,2);return e.length===2?r[e[0]]=vr(e[1]):e.length===1&&i.length>1&&(r[e[0]]=void 0),r};ei.parseParams=function(r){return r.split(/;\s?/).reduce(yu,{})};ei.parseFmtpConfig=ei.parseParams;ei.parsePayloads=function(r){return r.toString().split(" ").map(Number)};ei.parseRemoteCandidates=function(r){for(var i=[],e=r.split(" ").map(vr),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};ei.parseImageAttributes=function(r){return r.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(yu,{})})};ei.parseSimulcastStreamList=function(r){return r.split(";").map(function(i){return i.split(",").map(function(e){var t,s=!1;return e[0]!=="~"?t=vr(e):(t=vr(e.substring(1,e.length)),s=!0),{scid:t,paused:s}})})}});var vu=Jt((vE,Nu)=>{var Ya=za(),rp=/%[sdv%]/g,sp=function(r){var i=1,e=arguments,t=e.length;return r.replace(rp,function(s){if(i>=t)return s;var o=e[i];switch(i+=1,s){case"%%":return"%";case"%s":return String(o);case"%d":return Number(o);case"%v":return""}})},ks=function(r,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,s=[r+"="+t];if(i.names)for(var o=0;o<i.names.length;o+=1){var n=i.names[o];i.name?s.push(e[i.name][n]):s.push(e[i.names[o]])}else s.push(e[i.name]);return sp.apply(null,s)},op=["v","o","s","i","u","e","p","c","b","t","r","z","a"],np=["i","c","b","a"];Nu.exports=function(r,i){i=i||{},r.version==null&&(r.version=0),r.name==null&&(r.name=" "),r.media.forEach(function(o){o.payloads==null&&(o.payloads="")});var e=i.outerOrder||op,t=i.innerOrder||np,s=[];return e.forEach(function(o){Ya[o].forEach(function(n){n.name in r&&r[n.name]!=null?s.push(ks(o,n,r)):n.push in r&&r[n.push]!=null&&r[n.push].forEach(function(a){s.push(ks(o,n,a))})})}),r.media.forEach(function(o){s.push(ks("m",Ya.m[0],o)),t.forEach(function(n){Ya[n].forEach(function(a){a.name in o&&o[a.name]!=null?s.push(ks(n,a,o)):a.push in o&&o[a.push]!=null&&o[a.push].forEach(function(c){s.push(ks(n,a,c))})})})}),s.join(`\r
|
|
1
|
+
var Bh=Object.create;var Kr=Object.defineProperty,$h=Object.defineProperties,Wd=Object.getOwnPropertyDescriptor,Fh=Object.getOwnPropertyDescriptors,Hh=Object.getOwnPropertyNames,So=Object.getOwnPropertySymbols,Jd=Object.getPrototypeOf,da=Object.prototype.hasOwnProperty,jd=Object.prototype.propertyIsEnumerable,Gh=Reflect.get;var Zr=Math.pow,ca=(r,i,e)=>i in r?Kr(r,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[i]=e,N=(r,i)=>{for(var e in i||(i={}))da.call(i,e)&&ca(r,e,i[e]);if(So)for(var e of So(i))jd.call(i,e)&&ca(r,e,i[e]);return r},P=(r,i)=>$h(r,Fh(i));var qd=(r,i)=>{var e={};for(var t in r)da.call(r,t)&&i.indexOf(t)<0&&(e[t]=r[t]);if(r!=null&&So)for(var t of So(r))i.indexOf(t)<0&&jd.call(r,t)&&(e[t]=r[t]);return e};var jt=(r,i)=>()=>(i||r((i={exports:{}}).exports,i),i.exports),es=(r,i)=>{for(var e in i)Kr(r,e,{get:i[e],enumerable:!0})},Wh=(r,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let s of Hh(i))!da.call(r,s)&&s!==e&&Kr(r,s,{get:()=>i[s],enumerable:!(t=Wd(i,s))||t.enumerable});return r};var Se=(r,i,e)=>(e=r!=null?Bh(Jd(r)):{},Wh(i||!r||!r.__esModule?Kr(e,"default",{value:r,enumerable:!0}):e,r));var y=(r,i,e,t)=>{for(var s=t>1?void 0:t?Wd(i,e):i,o=r.length-1,n;o>=0;o--)(n=r[o])&&(s=(t?n(i,e,s):n(s))||s);return t&&s&&Kr(i,e,s),s};var l=(r,i,e)=>(ca(r,typeof i!="symbol"?i+"":i,e),e);var Ie=(r,i,e)=>Gh(Jd(r),e,i);var _=(r,i,e)=>new Promise((t,s)=>{var o=c=>{try{a(e.next(c))}catch(d){s(d)}},n=c=>{try{a(e.throw(c))}catch(d){s(d)}},a=c=>c.done?t(c.value):Promise.resolve(c.value).then(o,n);a((e=e.apply(r,i)).next())});var Ne=jt((nf,la)=>{"use strict";var Jh=Object.prototype.hasOwnProperty,xe="~";function ts(){}Object.create&&(ts.prototype=Object.create(null),new ts().__proto__||(xe=!1));function jh(r,i,e){this.fn=r,this.context=i,this.once=e||!1}function Xd(r,i,e,t,s){if(typeof e!="function")throw new TypeError("The listener must be a function");var o=new jh(e,t||r,s),n=xe?xe+i:i;return r._events[n]?r._events[n].fn?r._events[n]=[r._events[n],o]:r._events[n].push(o):(r._events[n]=o,r._eventsCount++),r}function Io(r,i){--r._eventsCount===0?r._events=new ts:delete r._events[i]}function be(){this._events=new ts,this._eventsCount=0}be.prototype.eventNames=function(){var i=[],e,t;if(this._eventsCount===0)return i;for(t in e=this._events)Jh.call(e,t)&&i.push(xe?t.slice(1):t);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i};be.prototype.listeners=function(i){var e=xe?xe+i:i,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var s=0,o=t.length,n=new Array(o);s<o;s++)n[s]=t[s].fn;return n};be.prototype.listenerCount=function(i){var e=xe?xe+i:i,t=this._events[e];return t?t.fn?1:t.length:0};be.prototype.emit=function(i,e,t,s,o,n){var a=xe?xe+i:i;if(!this._events[a])return!1;var c=this._events[a],d=arguments.length,u,p;if(c.fn){switch(c.once&&this.removeListener(i,c.fn,void 0,!0),d){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,s),!0;case 5:return c.fn.call(c.context,e,t,s,o),!0;case 6:return c.fn.call(c.context,e,t,s,o,n),!0}for(p=1,u=new Array(d-1);p<d;p++)u[p-1]=arguments[p];c.fn.apply(c.context,u)}else{var m=c.length,f;for(p=0;p<m;p++)switch(c[p].once&&this.removeListener(i,c[p].fn,void 0,!0),d){case 1:c[p].fn.call(c[p].context);break;case 2:c[p].fn.call(c[p].context,e);break;case 3:c[p].fn.call(c[p].context,e,t);break;case 4:c[p].fn.call(c[p].context,e,t,s);break;default:if(!u)for(f=1,u=new Array(d-1);f<d;f++)u[f-1]=arguments[f];c[p].fn.apply(c[p].context,u)}}return!0};be.prototype.on=function(i,e,t){return Xd(this,i,e,t,!1)};be.prototype.once=function(i,e,t){return Xd(this,i,e,t,!0)};be.prototype.removeListener=function(i,e,t,s){var o=xe?xe+i:i;if(!this._events[o])return this;if(!e)return Io(this,o),this;var n=this._events[o];if(n.fn)n.fn===e&&(!s||n.once)&&(!t||n.context===t)&&Io(this,o);else{for(var a=0,c=[],d=n.length;a<d;a++)(n[a].fn!==e||s&&!n[a].once||t&&n[a].context!==t)&&c.push(n[a]);c.length?this._events[o]=c.length===1?c[0]:c:Io(this,o)}return this};be.prototype.removeAllListeners=function(i){var e;return i?(e=xe?xe+i:i,this._events[e]&&Io(this,e)):(this._events=new ts,this._eventsCount=0),this};be.prototype.off=be.prototype.removeListener;be.prototype.addListener=be.prototype.on;be.prefixed=xe;be.EventEmitter=be;typeof la!="undefined"&&(la.exports=be)});var Ya=jt((yE,Rl)=>{var Cl=Rl.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(r){return r.encoding?"rtpmap:%d %s/%s/%s":r.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(r){return r.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(r){return r.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(r){return"extmap:%d"+(r.direction?"/%s":"%v")+(r["encrypt-uri"]?" %s":"%v")+" %s"+(r.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(r){return r.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(r){var i="candidate:%s %d %s %d %s %d typ %s";return i+=r.raddr!=null?" raddr %s rport %d":"%v%v",i+=r.tcptype!=null?" tcptype %s":"%v",r.generation!=null&&(i+=" generation %d"),i+=r["network-id"]!=null?" network-id %d":"%v",i+=r["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(r){var i="ssrc:%d";return r.attribute!=null&&(i+=" %s",r.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(r){return r.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(r){return r.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(r){return"imageattr:%s %s %s"+(r.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(r){return"simulcast:%s %s"+(r.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(r){return"ts-refclk:%s"+(r.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(r){var i="mediaclk:";return i+=r.id!=null?"id=%s %s":"%v%s",i+=r.mediaClockValue!=null?"=%s":"",i+=r.rateNumerator!=null?" rate=%s":"",i+=r.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(Cl).forEach(function(r){var i=Cl[r];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var Nl=jt(ti=>{var Or=function(r){return String(Number(r))===r?Number(r):r},ep=function(r,i,e,t){if(t&&!e)i[t]=Or(r[1]);else for(var s=0;s<e.length;s+=1)r[s+1]!=null&&(i[e[s]]=Or(r[s+1]))},tp=function(r,i,e){var t=r.name&&r.names;r.push&&!i[r.push]?i[r.push]=[]:t&&!i[r.name]&&(i[r.name]={});var s=r.push?{}:t?i[r.name]:i;ep(e.match(r.reg),s,r.names,r.name),r.push&&i[r.push].push(s)},yl=Ya(),ip=RegExp.prototype.test.bind(/^([a-z])=(.*)/);ti.parse=function(r){var i={},e=[],t=i;return r.split(/(\r\n|\r|\n)/).filter(ip).forEach(function(s){var o=s[0],n=s.slice(2);o==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(yl[o]||[]).length;a+=1){var c=yl[o][a];if(c.reg.test(n))return tp(c,t,n)}}),i.media=e,i};var bl=function(r,i){var e=i.split(/=(.+)/,2);return e.length===2?r[e[0]]=Or(e[1]):e.length===1&&i.length>1&&(r[e[0]]=void 0),r};ti.parseParams=function(r){return r.split(/;\s?/).reduce(bl,{})};ti.parseFmtpConfig=ti.parseParams;ti.parsePayloads=function(r){return r.toString().split(" ").map(Number)};ti.parseRemoteCandidates=function(r){for(var i=[],e=r.split(" ").map(Or),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};ti.parseImageAttributes=function(r){return r.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(bl,{})})};ti.parseSimulcastStreamList=function(r){return r.split(";").map(function(i){return i.split(",").map(function(e){var t,s=!1;return e[0]!=="~"?t=Or(e):(t=Or(e.substring(1,e.length)),s=!0),{scid:t,paused:s}})})}});var Dl=jt((NE,vl)=>{var Ka=Ya(),rp=/%[sdv%]/g,sp=function(r){var i=1,e=arguments,t=e.length;return r.replace(rp,function(s){if(i>=t)return s;var o=e[i];switch(i+=1,s){case"%%":return"%";case"%s":return String(o);case"%d":return Number(o);case"%v":return""}})},Ls=function(r,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,s=[r+"="+t];if(i.names)for(var o=0;o<i.names.length;o+=1){var n=i.names[o];i.name?s.push(e[i.name][n]):s.push(e[i.names[o]])}else s.push(e[i.name]);return sp.apply(null,s)},op=["v","o","s","i","u","e","p","c","b","t","r","z","a"],np=["i","c","b","a"];vl.exports=function(r,i){i=i||{},r.version==null&&(r.version=0),r.name==null&&(r.name=" "),r.media.forEach(function(o){o.payloads==null&&(o.payloads="")});var e=i.outerOrder||op,t=i.innerOrder||np,s=[];return e.forEach(function(o){Ka[o].forEach(function(n){n.name in r&&r[n.name]!=null?s.push(Ls(o,n,r)):n.push in r&&r[n.push]!=null&&r[n.push].forEach(function(a){s.push(Ls(o,n,a))})})}),r.media.forEach(function(o){s.push(Ls("m",Ka.m[0],o)),t.forEach(function(n){Ka[n].forEach(function(a){a.name in o&&o[a.name]!=null?s.push(Ls(n,a,o)):a.push in o&&o[a.push]!=null&&o[a.push].forEach(function(c){s.push(Ls(n,a,c))})})})}),s.join(`\r
|
|
2
2
|
`)+`\r
|
|
3
|
-
`}});var Du=Jt(ti=>{var Bi=bu(),ap=vu();ti.write=ap;ti.parse=Bi.parse;ti.parseParams=Bi.parseParams;ti.parseFmtpConfig=Bi.parseFmtpConfig;ti.parsePayloads=Bi.parsePayloads;ti.parseRemoteCandidates=Bi.parseRemoteCandidates;ti.parseImageAttributes=Bi.parseImageAttributes;ti.parseSimulcastStreamList=Bi.parseSimulcastStreamList});var Ad=Jt((eO,Kl)=>{var Yl=Kl.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(r){return r.encoding?"rtpmap:%d %s/%s/%s":r.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(r){return r.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(r){return r.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(r){return"extmap:%d"+(r.direction?"/%s":"%v")+(r["encrypt-uri"]?" %s":"%v")+" %s"+(r.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(r){return r.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(r){var i="candidate:%s %d %s %d %s %d typ %s";return i+=r.raddr!=null?" raddr %s rport %d":"%v%v",i+=r.tcptype!=null?" tcptype %s":"%v",r.generation!=null&&(i+=" generation %d"),i+=r["network-id"]!=null?" network-id %d":"%v",i+=r["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(r){var i="ssrc:%d";return r.attribute!=null&&(i+=" %s",r.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(r){return r.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(r){return r.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(r){return"imageattr:%s %s %s"+(r.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(r){return"simulcast:%s %s"+(r.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(r){return"ts-refclk:%s"+(r.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(r){var i="mediaclk:";return i+=r.id!=null?"id=%s %s":"%v%s",i+=r.mediaClockValue!=null?"=%s":"",i+=r.rateNumerator!=null?" rate=%s":"",i+=r.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(Yl).forEach(function(r){var i=Yl[r];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var th=Jt(ci=>{var qr=function(r){return String(Number(r))===r?Number(r):r},M_=function(r,i,e,t){if(t&&!e)i[t]=qr(r[1]);else for(var s=0;s<e.length;s+=1)r[s+1]!=null&&(i[e[s]]=qr(r[s+1]))},k_=function(r,i,e){var t=r.name&&r.names;r.push&&!i[r.push]?i[r.push]=[]:t&&!i[r.name]&&(i[r.name]={});var s=r.push?{}:t?i[r.name]:i;M_(e.match(r.reg),s,r.names,r.name),r.push&&i[r.push].push(s)},Zl=Ad(),L_=RegExp.prototype.test.bind(/^([a-z])=(.*)/);ci.parse=function(r){var i={},e=[],t=i;return r.split(/(\r\n|\r|\n)/).filter(L_).forEach(function(s){var o=s[0],n=s.slice(2);o==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(Zl[o]||[]).length;a+=1){var c=Zl[o][a];if(c.reg.test(n))return k_(c,t,n)}}),i.media=e,i};var eh=function(r,i){var e=i.split(/=(.+)/,2);return e.length===2?r[e[0]]=qr(e[1]):e.length===1&&i.length>1&&(r[e[0]]=void 0),r};ci.parseParams=function(r){return r.split(/;\s?/).reduce(eh,{})};ci.parseFmtpConfig=ci.parseParams;ci.parsePayloads=function(r){return r.toString().split(" ").map(Number)};ci.parseRemoteCandidates=function(r){for(var i=[],e=r.split(" ").map(qr),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};ci.parseImageAttributes=function(r){return r.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(eh,{})})};ci.parseSimulcastStreamList=function(r){return r.split(";").map(function(i){return i.split(",").map(function(e){var t,s=!1;return e[0]!=="~"?t=qr(e):(t=qr(e.substring(1,e.length)),s=!0),{scid:t,paused:s}})})}});var rh=Jt((iO,ih)=>{var Cd=Ad(),x_=/%[sdv%]/g,P_=function(r){var i=1,e=arguments,t=e.length;return r.replace(x_,function(s){if(i>=t)return s;var o=e[i];switch(i+=1,s){case"%%":return"%";case"%s":return String(o);case"%d":return Number(o);case"%v":return""}})},so=function(r,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,s=[r+"="+t];if(i.names)for(var o=0;o<i.names.length;o+=1){var n=i.names[o];i.name?s.push(e[i.name][n]):s.push(e[i.names[o]])}else s.push(e[i.name]);return P_.apply(null,s)},w_=["v","o","s","i","u","e","p","c","b","t","r","z","a"],V_=["i","c","b","a"];ih.exports=function(r,i){i=i||{},r.version==null&&(r.version=0),r.name==null&&(r.name=" "),r.media.forEach(function(o){o.payloads==null&&(o.payloads="")});var e=i.outerOrder||w_,t=i.innerOrder||V_,s=[];return e.forEach(function(o){Cd[o].forEach(function(n){n.name in r&&r[n.name]!=null?s.push(so(o,n,r)):n.push in r&&r[n.push]!=null&&r[n.push].forEach(function(a){s.push(so(o,n,a))})})}),r.media.forEach(function(o){s.push(so("m",Cd.m[0],o)),t.forEach(function(n){Cd[n].forEach(function(a){a.name in o&&o[a.name]!=null?s.push(so(n,a,o)):a.push in o&&o[a.push]!=null&&o[a.push].forEach(function(c){s.push(so(n,a,c))})})})}),s.join(`\r
|
|
3
|
+
`}});var Ol=jt(ii=>{var Fi=Nl(),ap=Dl();ii.write=ap;ii.parse=Fi.parse;ii.parseParams=Fi.parseParams;ii.parseFmtpConfig=Fi.parseFmtpConfig;ii.parsePayloads=Fi.parsePayloads;ii.parseRemoteCandidates=Fi.parseRemoteCandidates;ii.parseImageAttributes=Fi.parseImageAttributes;ii.parseSimulcastStreamList=Fi.parseSimulcastStreamList});var Rd=jt((eO,Ku)=>{var Yu=Ku.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(r){return r.encoding?"rtpmap:%d %s/%s/%s":r.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(r){return r.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(r){return r.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(r){return"extmap:%d"+(r.direction?"/%s":"%v")+(r["encrypt-uri"]?" %s":"%v")+" %s"+(r.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(r){return r.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(r){var i="candidate:%s %d %s %d %s %d typ %s";return i+=r.raddr!=null?" raddr %s rport %d":"%v%v",i+=r.tcptype!=null?" tcptype %s":"%v",r.generation!=null&&(i+=" generation %d"),i+=r["network-id"]!=null?" network-id %d":"%v",i+=r["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(r){var i="ssrc:%d";return r.attribute!=null&&(i+=" %s",r.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(r){return r.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(r){return r.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(r){return"imageattr:%s %s %s"+(r.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(r){return"simulcast:%s %s"+(r.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(r){return"ts-refclk:%s"+(r.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(r){var i="mediaclk:";return i+=r.id!=null?"id=%s %s":"%v%s",i+=r.mediaClockValue!=null?"=%s":"",i+=r.rateNumerator!=null?" rate=%s":"",i+=r.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(Yu).forEach(function(r){var i=Yu[r];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var th=jt(li=>{var Xr=function(r){return String(Number(r))===r?Number(r):r},M_=function(r,i,e,t){if(t&&!e)i[t]=Xr(r[1]);else for(var s=0;s<e.length;s+=1)r[s+1]!=null&&(i[e[s]]=Xr(r[s+1]))},k_=function(r,i,e){var t=r.name&&r.names;r.push&&!i[r.push]?i[r.push]=[]:t&&!i[r.name]&&(i[r.name]={});var s=r.push?{}:t?i[r.name]:i;M_(e.match(r.reg),s,r.names,r.name),r.push&&i[r.push].push(s)},Zu=Rd(),L_=RegExp.prototype.test.bind(/^([a-z])=(.*)/);li.parse=function(r){var i={},e=[],t=i;return r.split(/(\r\n|\r|\n)/).filter(L_).forEach(function(s){var o=s[0],n=s.slice(2);o==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(Zu[o]||[]).length;a+=1){var c=Zu[o][a];if(c.reg.test(n))return k_(c,t,n)}}),i.media=e,i};var eh=function(r,i){var e=i.split(/=(.+)/,2);return e.length===2?r[e[0]]=Xr(e[1]):e.length===1&&i.length>1&&(r[e[0]]=void 0),r};li.parseParams=function(r){return r.split(/;\s?/).reduce(eh,{})};li.parseFmtpConfig=li.parseParams;li.parsePayloads=function(r){return r.toString().split(" ").map(Number)};li.parseRemoteCandidates=function(r){for(var i=[],e=r.split(" ").map(Xr),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};li.parseImageAttributes=function(r){return r.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(eh,{})})};li.parseSimulcastStreamList=function(r){return r.split(";").map(function(i){return i.split(",").map(function(e){var t,s=!1;return e[0]!=="~"?t=Xr(e):(t=Xr(e.substring(1,e.length)),s=!0),{scid:t,paused:s}})})}});var rh=jt((iO,ih)=>{var yd=Rd(),x_=/%[sdv%]/g,P_=function(r){var i=1,e=arguments,t=e.length;return r.replace(x_,function(s){if(i>=t)return s;var o=e[i];switch(i+=1,s){case"%%":return"%";case"%s":return String(o);case"%d":return Number(o);case"%v":return""}})},oo=function(r,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,s=[r+"="+t];if(i.names)for(var o=0;o<i.names.length;o+=1){var n=i.names[o];i.name?s.push(e[i.name][n]):s.push(e[i.names[o]])}else s.push(e[i.name]);return P_.apply(null,s)},w_=["v","o","s","i","u","e","p","c","b","t","r","z","a"],V_=["i","c","b","a"];ih.exports=function(r,i){i=i||{},r.version==null&&(r.version=0),r.name==null&&(r.name=" "),r.media.forEach(function(o){o.payloads==null&&(o.payloads="")});var e=i.outerOrder||w_,t=i.innerOrder||V_,s=[];return e.forEach(function(o){yd[o].forEach(function(n){n.name in r&&r[n.name]!=null?s.push(oo(o,n,r)):n.push in r&&r[n.push]!=null&&r[n.push].forEach(function(a){s.push(oo(o,n,a))})})}),r.media.forEach(function(o){s.push(oo("m",yd.m[0],o)),t.forEach(function(n){yd[n].forEach(function(a){a.name in o&&o[a.name]!=null?s.push(oo(n,a,o)):a.push in o&&o[a.push]!=null&&o[a.push].forEach(function(c){s.push(oo(n,a,c))})})})}),s.join(`\r
|
|
4
4
|
`)+`\r
|
|
5
|
-
`}});var Rd=Jt(di=>{var ir=th(),U_=rh();di.write=U_;di.parse=ir.parse;di.parseParams=ir.parseParams;di.parseFmtpConfig=ir.parseFmtpConfig;di.parsePayloads=ir.parsePayloads;di.parseRemoteCandidates=ir.parseRemoteCandidates;di.parseImageAttributes=ir.parseImageAttributes;di.parseSimulcastStreamList=ir.parseSimulcastStreamList});import Sw from"webrtc-adapter";var Gl=Se(Ne());var qd=(O=>(O[O.INVALID_PARAMETER=4096]="INVALID_PARAMETER",O[O.INVALID_OPERATION=4097]="INVALID_OPERATION",O[O.NOT_SUPPORTED=4098]="NOT_SUPPORTED",O[O.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",O[O.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",O[O.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",O[O.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",O[O.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",O[O.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",O[O.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",O[O.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",O[O.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",O[O.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",O[O.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",O[O.CLIENT_BANNED=16448]="CLIENT_BANNED",O[O.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",O[O.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",O[O.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",O[O.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",O[O.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",O[O.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",O[O.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",O[O.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",O[O.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",O[O.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",O[O.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",O[O.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",O[O.API_CALL_ABORTED=16461]="API_CALL_ABORTED",O[O.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",O[O.UNKNOWN=65535]="UNKNOWN",O))(qd||{}),A=qd;var qh=function(r){for(let i in A)if(A[i]===r)return i;return"UNKNOWN"},ua=class extends Error{constructor({name:e="RtcError",message:t,code:s=A.UNKNOWN,extraCode:o=0,constraint:n}){let a=`<${qh(s)} 0x${s.toString(16)}>`,c=`${t}${n?` constraint: ${n}`:""}${t!=null&&t.includes(a)?"":` ${a}`}`;super(c);u(this,"code");u(this,"extraCode");u(this,"message");u(this,"originMessage");u(this,"name");u(this,"constraint");this.code=s,this.extraCode=o,this.name=e,this.message=c,this.constraint=n,this.originMessage=t}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},b=ua;var Xd=new Date().getTime(),la=0,Qd=function(r){Xd=r,la=Xd-new Date().getTime();let i=new Date;i.setTime(r),I.info(`baseTime from server: ${i} offset: ${la}`)},ts=function(){return new Date().getTime()+la},Io=function(){let r=new Date;return r.setTime(ts()),r.toLocaleString()};var we={};Zr(we,{bytes2ms:()=>Vm,convertObjectNumberToInt:()=>Ko,copyProperties:()=>wm,deepClone:()=>yr,deepMerge:()=>Kt,delay:()=>Zo,fibonacci:()=>Rr,formatedTime:()=>jm,getAbilityConfigUrl:()=>lu,getConstructorName:()=>zo,getContainerFromElement:()=>Wm,getEnv:()=>Pm,getInternalVersion:()=>Fm,getLoggerUrl:()=>Si,getMuteStateFromFlag:()=>Ai,getNetworkType:()=>pu,getNumNetworkType:()=>br,getReconnectionTimeout:()=>kt,getStringByteLength:()=>Yo,getTurnServer:()=>Gm,getUint32Version:()=>ja,getValueType:()=>fe,getViewListFromView:()=>Ds,glog:()=>gu,ipv4ToUint32:()=>vs,isArray:()=>he,isAudioWorkletSupported:()=>$m,isBoolean:()=>de,isConstructor:()=>Ns,isEmpty:()=>Ga,isFunction:()=>W,isLangChinese:()=>Nt,isMediaStreamTrack:()=>Bm,isNumber:()=>ee,isObject:()=>mt,isOverseaSdkAppId:()=>Cs,isPlainObject:()=>Je,isPortrait:()=>Ja,isPromise:()=>bs,isRemoteTrack:()=>_t,isString:()=>Y,isUndefined:()=>T,loadImage:()=>Os,ms2bytes:()=>Um,ms2samples:()=>Eu,performanceNow:()=>x,promiseAny:()=>Rs,samples2ms:()=>fu,setNetworkType:()=>Ha,stringify:()=>pt,stringifyIncludeValue:()=>Wa,throttlePromise:()=>qa});var Ra={};Zr(Ra,{AUDIO_MUTE_BIT:()=>No,AUDIO_STAT_BIT:()=>mi,AUX_STAT_BIT:()=>xi,AUX_STREAM_MSID:()=>fa,BACKEND_ENV:()=>bo,BASE_DOC_URL:()=>Ct,BASE_HOST:()=>zd,CAPABILITIES_KEYS:()=>Oo,CLASS_NAME:()=>pm,CLOUD_CONSOLE_URL:()=>Yh,DATA_FREEZE_TIMING:()=>Do,DOC_URL:()=>Kh,DTLS_STATE_UNKNOWN:()=>nt,ENV_NAME:()=>jt,EXCHANGE_SDP_TIMEOUT:()=>Ia,INTERVAL:()=>Vi,IS_WORKER:()=>cr,IS_WORKLET:()=>rs,KIBANA_EVENT:()=>Ve,LOCAL_STREAM_PUBLISH_STATE:()=>Zd,LOGGER_CMD_TYPE:()=>li,LOGGER_DOMAIN:()=>ma,LOGGER_DOMAIN_OVERSEA:()=>pa,LOG_LEVEL:()=>ot,LOG_LEVEL_NAME:()=>fm,MAIN_STREAM_MSID:()=>ns,MICROPHONE_COMMUNICATIONS:()=>_m,MICROPHONE_DEFAULT:()=>wi,NAME:()=>h,NETWORK_TYPE:()=>Ao,NOT_SUPPORTED_H264:()=>Pi,PAUSED_RETRY_COUNT:()=>Aa,PEERCONNECTION_CONNECTING_TIMEOUT:()=>as,PEER_CONNECTION_STATE:()=>se,PEER_LEAVE_REASON:()=>Ca,RAF:()=>ds,RECOVER_CAPTURE_INTERVAL:()=>lr,REMOTE_STREAM_TYPE_AUX:()=>ga,REMOTE_STREAM_TYPE_MAIN:()=>Ea,RENDER_FREEZE_TIMING:()=>um,RIC:()=>_i,SCHEDULE_DOMAIN:()=>at,SCHEDULE_TIMEOUT:()=>mm,SDP_SEMANTICS_PLAN_B:()=>dr,SDP_SEMANTICS_UNIFIED_PLAN:()=>pi,SECOND_HOST:()=>Qh,SIGNAL_PING_PONG_INTERVAL:()=>em,SIGNAL_PING_TIMEOUT:()=>Zh,SIGNAL_RECONNECTION_COUNT:()=>cm,SMALL_STAT_BIT:()=>os,SPEAKER_DEFAULT:()=>cs,STORAGE_EXPIRES_TIME:()=>Co,STREAM_TYPE_BIG:()=>lm,STREAM_TYPE_SMALL:()=>hm,SUBSCRIBE_SMALL_RETRY_COUNT:()=>ur,SYNC_USER_LIST_INTERVAL:()=>dm,Scene:()=>Rt,Switch:()=>Yd,THIRD_HOST:()=>zh,TIMEOUT:()=>fi,TRANSPORT_DIRECTION:()=>z,TRTC_ERROR_ASSISTANCE:()=>_a,TRTC_QUALITY_BAD:()=>om,TRTC_QUALITY_DISCONNECTED:()=>am,TRTC_QUALITY_EXCELLENT:()=>im,TRTC_QUALITY_GOOD:()=>rm,TRTC_QUALITY_POOR:()=>sm,TRTC_QUALITY_UNKNOWN:()=>tm,TRTC_QUALITY_VERY_BAD:()=>nm,UPDATE_OFFER_TIMEOUT:()=>Sa,VIDEO_MUTE_BIT:()=>vo,VIDEO_STAT_BIT:()=>hi,audioProfileMap:()=>Ro,getRetryCount:()=>qt,getScriptDir:()=>Xh,innerVersion:()=>is,loggerProxy:()=>ss,screenProfileMap:()=>yo,setLoggerProxy:()=>Li,setRetryCount:()=>Ta,setVersion:()=>ha,version:()=>Re,videoProfileMap:()=>Ze});var is="4.15.00.1600",Re="5.0.0";function ha(r){Re=r;let[i,e,t]=r.split(".").map(s=>parseInt(s,10));is=`${i}.${Math.min(15,e)}.${Math.min(15,t)}.${e.toString().padStart(2,"0")}${t.toString().padStart(2,"0")}`}var cr=typeof importScripts!="undefined",rs=typeof registerProcessor!="undefined",Xh=()=>{let r=cr?self.location.href:document.currentScript.src;return r.substring(0,r.lastIndexOf("/")+1)},ss="",Li=r=>ss=r,zd="web.sdk.qcloud.com",Qh="web.sdk.tencent.cn",zh="web.sdk.cloud.tencent.cn",Yh="https://console.cloud.tencent.com/trtc",Ct=`https://${zd}/trtc/webrtc/v5/doc`,Kh=`${Ct}/zh-cn/`,ma="https://yun.tim.qq.com",pa="https://apisgp.my-imcloud.com",_a="trtc_error_assistance",li={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},jt={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},ot=(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))(ot||{}),Zh=18e3,em=2e3,Ao={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},Co=7*24*3600*1e3,Yd=(s=>(s.USEAINS="useAINS",s.ENABLEDEBUG="enableDebug",s.USEV2="useV2",s.USEWT="useWt",s))(Yd||{}),Ro={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}},Ze={"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}},yo={"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}},h={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",LOADEDDATA:"loadeddata",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"},z={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},bo={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Rt=(e=>(e.LIVE="live",e.RTC="rtc",e))(Rt||{}),hi=1,os=2,xi=4,mi=8,No=64,vo=16,ns="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",fa="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",Ea=h.MAIN,ga=h.AUXILIARY,tm=0,im=1,rm=2,sm=3,om=4,nm=5,am=6,nt="unknown",se={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Kd=1/0;function Ta(r){Kd=r}function qt(){return Kd}var cm=30,Ve={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"},dm=1e4,Sa=1e4,Ia=1e4,pi="unified-plan",dr="plan-b",Pi=1028,Zd=(t=>(t[t.UNPUBLISH=-1]="UNPUBLISH",t[t.PUBLISHING=0]="PUBLISHING",t[t.PUBLISHED=1]="PUBLISHED",t))(Zd||{}),Do=500,um=1e3,lm=h.BIG,hm=h.SMALL,as=10*1e3,at={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_OLD:"schedule.rtc.tencentcloud.com",BACKUP_OVERSEA_OLD:"schedule-ecdn.rtc.tencentcloud.com"},mm=2e3,pm={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},Aa=5,wi="default",cs=wi,_m="communications",fm=Object.keys(ot),Ca=["normal leave","timeout leave","kick","role change"],ur=10,lr=2e3,_i="ric",ds="raf",Vi="interval",fi="timeout",Oo=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"];function Xt({url:r,body:i,method:e,timeout:t}){let s=new XMLHttpRequest;return new Promise((o,n)=>{s.onreadystatechange=()=>{if(s.readyState===4)if(s.status>=200&&s.status<300)try{let a=JSON.parse(s.response);o({data:a})}catch(a){o({data:s.response})}else n({status:s.status,statusText:s.statusText||"request failed!"})},s.timeout=t||5e3,s.open(e||"POST",r,!0),s.send(i)})}function ya(r){return _(this,null,function*(){let i=x(),e=JSON.stringify(r);try{if(!CompressionStream||e.length<=2800)return e;let s=new Blob([e],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),a=yield(yield(yield new Response(s)).blob()).arrayBuffer();return I.debug(`compressJSON ${e.length} -> ${a.byteLength} ${x()-i}ms`),a}catch(t){return e}})}var ct=1e8;var M={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"},Ae={AVOID_REPEATED_CALL(r){return`previous ${r.name}() is ongoing, please avoid repeated calls.`},INVALID_PARAMETER_REQUIRED({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:r,rule:i,fnName:e,value:t}){let s=`${r||i.name}`,o="";return Array.isArray(i.type)?o=i.type.join("|"):o=i.type,`'${s}' must be type of ${o} when calling ${e}(), received type: ${fe(t)}.`},INVALID_PARAMETER_EMPTY({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:r,rule:i,fnName:e,value:t}){let s=`${r||i.name}`,o=`${i.instanceOf.name||i.instanceOf}`;return`'${s}' must be instanceof ${o} when calling ${e}(), received type: ${fe(t)}.`},INVALID_PARAMETER_RANGE({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_MIN({key:r,rule:i,fnName:e,value:t}){return`the min value of ${r||i.name} is ${i.min}, received: ${t}.`},INVALID_PARAMETER_MAX({key:r,rule:i,fnName:e,value:t}){return`the max value of ${r||i.name} is ${i.max}, received: ${t}.`},API_CALL_TIMEOUT(r){return`${r.commandDesc||r.command} timeout observed.`},SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED(r){return`SignalChannel setup failure: (errorCode: ${r.errorCode}, errorMsg: ${r.errorMsg} }).`},ERROR_MESSAGE(r){let i=`${r.type} failed`;return r.message&&(i=`${i}: ${r.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(r){return`exchange sdp failed ${r.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(r){return`'${r}' must be validate string when useStringRoomId is true.`},INVALID_ROOMID_INTEGER(r){return`'${r}' 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:r,code:i}){return`Failed to join room - ${r} code: ${i}`},REJOIN_ROOM_FAILED(r){return`reJoin room: ${r.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(r){return`duplicate ${r} stream publishing, please unpublish your prev ${r} 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:r,userId:i,streamType:e}){return`failed to subscribe ${i} ${e} stream, reason: ${r}.`},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(r){return`switchRole failed, errCode: ${r.code} errMsg: ${r.message}.`},CLIENT_BANNED(r){return`client was banned because of ${r.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(r){return`startPublishCDNStream failed, errMsg: ${r.message}.`},STOP_PUBLISH_CDN_FAILED(r){return`stopPublishCDNStream failed, errMsg: ${r.message}.`},INVALID_STREAM_ID(r){return`'${r}' 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(r){return`cannot replace ${r.kind} track because stream has not ${r.kind} track`},NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED(r){return`startMixTranscode failed, errMsg: ${r.message}.`},STOP_MIX_TRANSCODE_FAILED(r){return`stopMixTranscode failed, errMsg: ${r.message}.`},MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO({key:r,rule:i,fnName:e,value:t}){return`'${r||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(r){return`'${r}' 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:r,fnName:i})=>`'${r}' is not found in the document object when calling ${i}().`,INVALID_ELEMENT_ID_TYPE:({key:r,fnName:i,type:e})=>`the element corresponding to '${r}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`,PLAY_FAILED:r=>`${r.media} play failed\uFF0Cbrowser exception: ${r.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(r){return`${r}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(r){return`${r.signalResponse} failed, response code is ${r.code} , errMsg: ${r.message}.`},CATCH_HANDLER_ERROR({name:r,event:i}){return`an error was caught in ${r}.on('${i}', handler), please check your code in 'handler'.`},API_NOT_EXIST({name:r}){return`experimental api ${r} does not exist.`},REPEAT_JOIN:r=>"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:r}){return`failed to call ${r}() because client was destroyed.`},SEI_NOT_SUPPORT:r=>`not support to sendSEIMessage${r===!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:r,name:i,timesInSecond:e,maxSizeInSecond:t})=>`api ${i} call ${r?"size":"times"} is over ${r?`${t} bytes`:e} in a second.`,CONNECTION_ABORTED(r){return`connection aborted due to: ${r}`},API_CALL_ABORTED(r){let i;return r.message.includes("REMOTE_STREAM_NOT_EXIST")?i=`Subscribe ${r.userId} ${r.streamType} stream aborted, reason: remote user ${r.userId} unpublished stream.`:i=`API aborted, reason: ${r.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:r=>`'streamType' is required when 'userId' is not '*', calling ${r}()`};var Ar={};Zr(Ar,{ANDROID_VERSION:()=>va,CHROME_MAJOR_VERSION:()=>ht,CHROME_VERSION:()=>Xo,EDGE_VERSION:()=>ko,EDG_MAJOR_VERSION:()=>Oa,EDG_VERSION:()=>Lo,FIREFOX_MAJOR_VERSION:()=>Da,FIREFOX_VERSION:()=>Mo,HUAWEI_VERSION:()=>Wo,IE_VERSION:()=>Im,IOS_MAIN_VERSION:()=>Ss,IOS_VERSION:()=>Ti,IPADQQB_VERSION:()=>Fo,IS_ANDROID:()=>pe,IS_ANDROID_WEBVIEW:()=>La,IS_ANY_SAFARI:()=>Ir,IS_CHROME:()=>Sr,IS_CHROME_OS:()=>su,IS_CHROMIUM_BASE:()=>Pe,IS_EDG:()=>pr,IS_EDGE:()=>mr,IS_ELECTRON:()=>Cm,IS_FIREFOX:()=>ie,IS_HEADLESS_CHROME:()=>ka,IS_HUAWEI:()=>Rm,IS_HUAWEIBROWSER:()=>gs,IS_IE:()=>ru,IS_IE8:()=>Sm,IS_IOS:()=>We,IS_IOS_13_OR_14:()=>Pa,IS_IOS_15_1:()=>xa,IS_IPAD:()=>us,IS_IPADQQB:()=>fs,IS_IPAD_PRO:()=>Na,IS_IPHONE:()=>Ui,IS_IPOD:()=>iu,IS_LINUX:()=>Ho,IS_LOCAL:()=>zt,IS_MAC:()=>bt,IS_MACQQB:()=>_s,IS_MIBROWSER:()=>Es,IS_MQQB:()=>Er,IS_NATIVE_ANDROID:()=>Tm,IS_OLD_ANDROID:()=>gm,IS_OPPOBROWSER:()=>gr,IS_SAFARI:()=>Ue,IS_SAFARI_15_1:()=>ym,IS_SAMSUNGBROWSER:()=>Ts,IS_SOGOU:()=>hs,IS_SOGOUM:()=>ls,IS_TBS:()=>lt,IS_UCBROWSER:()=>Ma,IS_VIVOBROWSER:()=>Tr,IS_WECHAT:()=>_r,IS_WIN:()=>Ei,IS_WQQB:()=>ps,IS_WX:()=>Am,IS_X5MQQB:()=>fr,IS_XWEB:()=>ms,MACQQB_VERSION:()=>$o,MI_VERSION:()=>Go,MQQB_VERSION:()=>hr,OPPO_VERSION:()=>jo,SAFARI_VERSION:()=>gi,SAMSUNG_VERSION:()=>Jo,SOGOUM_VERSION:()=>xo,SOGOU_VERSION:()=>Po,TBS_VERSION:()=>wo,UA_DATA_STRING:()=>dt,USER_AGENT:()=>ut,VIVO_VERSION:()=>qo,WECHAT_VERSION:()=>Uo,WQQB_VERSION:()=>Bo,XWEB_VERSION:()=>Vo,browserInfo:()=>yt,getBrowserInfo:()=>ou,getChromeMajorVersion:()=>Qt,getDeviceModel:()=>wa,getOSName:()=>Qo,getOSString:()=>As,getOSType:()=>bm,getTerminalType:()=>Va,getUserAgentData:()=>Is,isLocalStorageEnabled:()=>Yt});var ut=typeof navigator=="undefined"?"":navigator.userAgent,X=r=>new RegExp(r,"i").test(ut),Ee=r=>{if(X(r)){let i=new RegExp(`${r}\\/([\\d.]+)`),e=ut.match(i);if(e&&e[1])return e[1]}return""},ba=r=>{if(X(r)){let i=new RegExp(`${r}\\/(\\d+)`),e=ut.match(i);if(e&&e[1])return parseFloat(e[1])}return NaN},eu=/AppleWebKit\/([\d.]+)/i.exec(ut),Em=eu?parseFloat(eu[1]):NaN,us=X("iPad"),Na=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&X("Macintosh"),Ui=X("iPhone")&&!us,iu=X("iPod"),We=Ui||us||iu||Na,pe=X("Android"),va=function(){if(pe){let r=ut.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(r){let i=r[1]&&parseFloat(r[1]),e=r[2]&&parseFloat(r[2]);if(i&&e)return parseFloat(`${r[1]}.${r[2]}`);if(i)return i}}return NaN}(),gm=pe&&X("webkit")&&va<2.3,Tm=pe&&va<5&&Em<537,ie=X("Firefox"),Mo=Ee("Firefox"),Da=ba("Firefox"),mr=X("Edge"),ko=Ee("Edge"),pr=X("Edg"),Lo=Ee("Edg"),Oa=ba("Edg"),ls=X("SogouMobileBrowser"),xo=Ee("SogouMobileBrowser"),hs=X("MetaSr\\s"),Po=Ee("MetaSr\\s"),lt=X("TBS"),wo=Ee("TBS"),ms=X("XWEB"),Vo=Ee("XWEB"),Sm=X("MSIE\\s8\\.0"),ru=X("MSIE\\/\\d+"),Im=function(){if(ru){let r=/MSIE\s(\d+)\.\d/.exec(ut),i=r&&parseFloat(r[1]);return!i&&/Trident\/7.0/i.test(ut)&&/rv:11.0/.test(ut)&&(i=11),i}return NaN}(),_r=X("(micromessenger|webbrowser)"),Uo=Ee("MicroMessenger"),fr=!lt&&X("MQQBrowser")&&X("COVC"),Er=!lt&&X("MQQBrowser")&&!X("COVC"),hr=Er||fr?Ee("MQQBrowser"):"",ps=!lt&&X(" QQBrowser"),Bo=Ee(" QQBrowser"),_s=!lt&&X("QQBrowserLite"),$o=Ee("QQBrowserLite"),fs=!lt&&X("MQBHD"),Fo=Ee("MQBHD"),Ei=X("Windows"),bt=!We&&X("MAC OS X"),Ho=!pe&&X("Linux"),su=X("CrOS"),Am=X("MicroMessenger"),Ma=X("UCBrowser"),Cm=X("Electron"),Es=X("MiuiBrowser"),Go=Ee("MiuiBrowser"),gs=X("HuaweiBrowser"),Rm=X("Huawei"),Wo=Ee("HuaweiBrowser"),Ts=X("SamsungBrowser"),Jo=Ee("SamsungBrowser"),gr=X("HeyTapBrowser"),jo=Ee("HeyTapBrowser"),Tr=X("VivoBrowser"),qo=Ee("VivoBrowser"),Qt=()=>ba("Chrome"),Pe=X("Chrome"),Sr=!mr&&!hs&&!ls&&!lt&&!ms&&!pr&&!ps&&!Es&&!gs&&!Ts&&!gr&&!Tr&&Pe,ka=X("HeadlessChrome"),ht=Qt(),Xo=Ee("Chrome"),Ue=!Pe&&!Er&&!fr&&!_s&&!fs&&X("Safari"),Ir=Ue||We,gi=Ee("Version"),La=/Android.*(wv|.0.0.0)/.test(ut),Ti=(()=>{if(Na)return gi;if(We){let r=ut.match(/OS (\d+)_(\d+)/i);if(r&&r[1]){let i=r[1];return r[2]&&(i+=`.${r[2]}`),i}}return""})(),Ss=Number(Ti.split(".")[0]),ym=gi==="15.1",xa=Ti==="15.1",Pa=(()=>{let r=Number(Ti.split(".")[0]);return r===14||r===13})(),zt=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",Yt=(()=>{let r;return()=>{if(typeof r=="undefined")try{r=!!window.localStorage}catch(i){r=!1}return r}})(),yt=ou();function ou(){let r=new Map([[ie,["Firefox",Mo]],[pr,["Edg",Lo]],[Sr,["Chrome",Xo]],[Ue,["Safari",gi]],[lt,["TBS",wo]],[ms,["XWEB",Vo]],[_r&&Ui,["WeChat",Uo]],[ps,["QQ(Win)",Bo]],[Er,["QQ(Mobile)",hr]],[fr,["QQ(Mobile X5)",hr]],[_s,["QQ(Mac)",$o]],[fs,["QQ(iPad)",Fo]],[Es,["MI",Go]],[gs,["HW",Wo]],[Ts,["Samsung",Jo]],[gr,["OPPO",jo]],[Tr,["VIVO",qo]],[mr,["EDGE",ko]],[ls,["SogouMobile",xo]],[hs,["Sogou",Po]]]),i="unknown",e="unknown";return r.has(!0)&&([i,e]=r.get(!0)),{name:i,version:e}}var te=null,dt="";function Is(){return _(this,null,function*(){if(te)return te;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return te=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),te&&!dt&&(dt=`UAData: ${te.platform}/${te.platformVersion}`,te.architecture&&te.bitness&&(dt+=` ${te.architecture}/${te.bitness}`),te.mobile&&(dt+=" mobile"),te.model&&(dt+=` model: ${te.model}`),te.fullVersionList&&(dt+=` ${te.fullVersionList.filter(r=>r.brand!=="Not/A)Brand").map(r=>`${r.brand}/${r.version}`).join(",")}`)),te}catch(r){return null}})}function wa(){return(te==null?void 0:te.model)||""}var tu=new Map([[pe,"Android"],[We,"iOS"],[Ei,"Windows"],[bt,"MacOS"],[Ho,"Linux"],[su,"ChromeOS"]]),Qo=function(){return tu.get(!0)?tu.get(!0):te?te.platform:"unknown"},As=()=>{let r=Qo();return r+=`/${yt.name}/${Ue?yt.version:yt.version.split(".")[0]}`,te!=null&&te.platformVersion&&(r+=`/${te.platformVersion}`),te!=null&&te.architecture&&(r+=`/${te.architecture}`),r};function Va(){return pe?4:Ui?2:us?3:bt?12:Ei?5:Ho?13:1}function bm(){return pe?"Android":Ui?"iPhone":us?"iPad":bt?"Mac":Ei?"Windows":Ho?"Linux":"unknown"}var nu=(r,i)=>i?`${Ct}/${r}/${i}`:`${Ct}/${r}/index.html`;var Nm=()=>{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 r=localStorage==null?void 0:localStorage.getItem(_a);if(r){r=JSON.parse(r);let i=document.createElement("script");i.type="text/javascript",i.text=r.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 L(r){let{key:i,data:e,link:t,addDocLink:s=!0}=r,o="",n="",a="";W(Ae[i])?o=Ae[i](e):Y(Ae[i])&&(o=Ae[i]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:d}=Nm();t?a=`${t.className}.html#${t.fnName}`:d&&d[i]&&(W(d[i])?a=d[i](e):Y(d[i])&&(a=d[i]));let l=o;return Nt()&&(c&&c[i]&&(W(c[i])?n=c[i](e):Y(c[i])&&(n=c[i])),n&&(s?l=`${n}
|
|
6
|
-
\u8BF7\u67E5\u770B\u6587\u6863: ${
|
|
5
|
+
`}});var bd=jt(ui=>{var sr=th(),U_=rh();ui.write=U_;ui.parse=sr.parse;ui.parseParams=sr.parseParams;ui.parseFmtpConfig=sr.parseFmtpConfig;ui.parsePayloads=sr.parsePayloads;ui.parseRemoteCandidates=sr.parseRemoteCandidates;ui.parseImageAttributes=sr.parseImageAttributes;ui.parseSimulcastStreamList=sr.parseSimulcastStreamList});import Sw from"webrtc-adapter";var Gu=Se(Ne());var Qd=(O=>(O[O.INVALID_PARAMETER=4096]="INVALID_PARAMETER",O[O.INVALID_OPERATION=4097]="INVALID_OPERATION",O[O.NOT_SUPPORTED=4098]="NOT_SUPPORTED",O[O.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",O[O.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",O[O.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",O[O.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",O[O.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",O[O.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",O[O.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",O[O.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",O[O.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",O[O.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",O[O.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",O[O.CLIENT_BANNED=16448]="CLIENT_BANNED",O[O.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",O[O.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",O[O.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",O[O.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",O[O.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",O[O.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",O[O.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",O[O.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",O[O.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",O[O.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",O[O.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",O[O.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",O[O.API_CALL_ABORTED=16461]="API_CALL_ABORTED",O[O.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",O[O.UNKNOWN=65535]="UNKNOWN",O))(Qd||{}),A=Qd;var qh=function(r){for(let i in A)if(A[i]===r)return i;return"UNKNOWN"},ua=class extends Error{constructor({name:e="RtcError",message:t,code:s=A.UNKNOWN,extraCode:o=0,constraint:n}){let a=`<${qh(s)} 0x${s.toString(16)}>`,c=`${t}${n?` constraint: ${n}`:""}${t!=null&&t.includes(a)?"":` ${a}`}`;super(c);l(this,"code");l(this,"extraCode");l(this,"message");l(this,"originMessage");l(this,"name");l(this,"constraint");this.code=s,this.extraCode=o,this.name=e,this.message=c,this.constraint=n,this.originMessage=t}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},b=ua;var zd=new Date().getTime(),ha=0,Yd=function(r){zd=r,ha=zd-new Date().getTime();let i=new Date;i.setTime(r),I.info(`baseTime from server: ${i} offset: ${ha}`)},is=function(){return new Date().getTime()+ha},Ao=function(){let r=new Date;return r.setTime(is()),r.toLocaleString()};var we={};es(we,{bytes2ms:()=>Bm,convertObjectNumberToInt:()=>Zo,copyProperties:()=>Um,deepClone:()=>Nr,deepMerge:()=>ei,delay:()=>en,fibonacci:()=>br,formatedTime:()=>Xm,getAbilityConfigUrl:()=>_l,getConstructorName:()=>Yo,getContainerFromElement:()=>jm,getEnv:()=>Vm,getInternalVersion:()=>Gm,getLoggerUrl:()=>Ai,getMuteStateFromFlag:()=>Ri,getNetworkType:()=>gl,getNumNetworkType:()=>vr,getReconnectionTimeout:()=>Lt,getStringByteLength:()=>Ko,getTurnServer:()=>Jm,getUint32Version:()=>qa,getValueType:()=>fe,getViewListFromView:()=>Os,glog:()=>Al,ipv4ToUint32:()=>Ds,isArray:()=>he,isAudioWorkletSupported:()=>Hm,isBoolean:()=>de,isConstructor:()=>vs,isEmpty:()=>Wa,isFunction:()=>K,isLangChinese:()=>Nt,isMediaStreamTrack:()=>Fm,isNumber:()=>ee,isObject:()=>pt,isOverseaSdkAppId:()=>Rs,isPlainObject:()=>Je,isPortrait:()=>ja,isPromise:()=>Ns,isRemoteTrack:()=>ft,isString:()=>z,isUndefined:()=>T,loadImage:()=>Ms,ms2bytes:()=>$m,ms2samples:()=>Il,performanceNow:()=>x,promiseAny:()=>ys,samples2ms:()=>Sl,setNetworkType:()=>Ga,stringify:()=>_t,stringifyIncludeValue:()=>Ja,throttlePromise:()=>Xa});var ya={};es(ya,{AUDIO_MUTE_BIT:()=>vo,AUDIO_STAT_BIT:()=>_i,AUX_STAT_BIT:()=>wi,AUX_STREAM_MSID:()=>Ea,BACKEND_ENV:()=>No,BASE_DOC_URL:()=>Ct,BASE_HOST:()=>Kd,CAPABILITIES_KEYS:()=>Mo,CLASS_NAME:()=>pm,CLOUD_CONSOLE_URL:()=>Yh,DATA_FREEZE_TIMING:()=>Oo,DOC_URL:()=>Kh,DTLS_STATE_UNKNOWN:()=>at,ENV_NAME:()=>qt,EXCHANGE_SDP_TIMEOUT:()=>Aa,INTERVAL:()=>Bi,IS_WORKER:()=>lr,IS_WORKLET:()=>ss,KIBANA_EVENT:()=>Ve,LOCAL_STREAM_PUBLISH_STATE:()=>tl,LOGGER_CMD_TYPE:()=>mi,LOGGER_DOMAIN:()=>pa,LOGGER_DOMAIN_OVERSEA:()=>_a,LOG_LEVEL:()=>nt,LOG_LEVEL_NAME:()=>fm,MAIN_STREAM_MSID:()=>as,MICROPHONE_COMMUNICATIONS:()=>_m,MICROPHONE_DEFAULT:()=>Ui,NAME:()=>h,NETWORK_TYPE:()=>Co,NOT_SUPPORTED_H264:()=>Vi,PAUSED_RETRY_COUNT:()=>Ca,PEERCONNECTION_CONNECTING_TIMEOUT:()=>cs,PEER_CONNECTION_STATE:()=>se,PEER_LEAVE_REASON:()=>Ra,RAF:()=>ls,RECOVER_CAPTURE_INTERVAL:()=>mr,REMOTE_STREAM_TYPE_AUX:()=>Ta,REMOTE_STREAM_TYPE_MAIN:()=>ga,RENDER_FREEZE_TIMING:()=>lm,RIC:()=>Ei,SCHEDULE_DOMAIN:()=>ct,SCHEDULE_TIMEOUT:()=>mm,SDP_SEMANTICS_PLAN_B:()=>ur,SDP_SEMANTICS_UNIFIED_PLAN:()=>fi,SECOND_HOST:()=>Qh,SIGNAL_PING_PONG_INTERVAL:()=>em,SIGNAL_PING_TIMEOUT:()=>Zh,SIGNAL_RECONNECTION_COUNT:()=>cm,SMALL_STAT_BIT:()=>ns,SPEAKER_DEFAULT:()=>ds,STORAGE_EXPIRES_TIME:()=>Ro,STREAM_TYPE_BIG:()=>um,STREAM_TYPE_SMALL:()=>hm,SUBSCRIBE_SMALL_RETRY_COUNT:()=>hr,SYNC_USER_LIST_INTERVAL:()=>dm,Scene:()=>Rt,Switch:()=>Zd,THIRD_HOST:()=>zh,TIMEOUT:()=>gi,TRANSPORT_DIRECTION:()=>Q,TRTC_ERROR_ASSISTANCE:()=>fa,TRTC_QUALITY_BAD:()=>om,TRTC_QUALITY_DISCONNECTED:()=>am,TRTC_QUALITY_EXCELLENT:()=>im,TRTC_QUALITY_GOOD:()=>rm,TRTC_QUALITY_POOR:()=>sm,TRTC_QUALITY_UNKNOWN:()=>tm,TRTC_QUALITY_VERY_BAD:()=>nm,UPDATE_OFFER_TIMEOUT:()=>Ia,VIDEO_MUTE_BIT:()=>Do,VIDEO_STAT_BIT:()=>pi,audioProfileMap:()=>yo,getRetryCount:()=>Xt,getScriptDir:()=>Xh,innerVersion:()=>rs,loggerProxy:()=>os,screenProfileMap:()=>bo,setLoggerProxy:()=>Pi,setRetryCount:()=>Sa,setVersion:()=>ma,version:()=>Re,videoProfileMap:()=>Ze});var rs="4.15.00.1600",Re="5.0.0";function ma(r){Re=r;let[i,e,t]=r.split(".").map(s=>parseInt(s,10));rs=`${i}.${Math.min(15,e)}.${Math.min(15,t)}.${e.toString().padStart(2,"0")}${t.toString().padStart(2,"0")}`}var lr=typeof importScripts!="undefined",ss=typeof registerProcessor!="undefined",Xh=()=>{let r=lr?self.location.href:document.currentScript.src;return r.substring(0,r.lastIndexOf("/")+1)},os="",Pi=r=>os=r,Kd="web.sdk.qcloud.com",Qh="web.sdk.tencent.cn",zh="web.sdk.cloud.tencent.cn",Yh="https://console.cloud.tencent.com/trtc",Ct=`https://${Kd}/trtc/webrtc/v5/doc`,Kh=`${Ct}/zh-cn/`,pa="https://yun.tim.qq.com",_a="https://apisgp.my-imcloud.com",fa="trtc_error_assistance",mi={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},qt={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},nt=(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))(nt||{}),Zh=18e3,em=2e3,Co={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},Ro=7*24*3600*1e3,Zd=(s=>(s.USEAINS="useAINS",s.ENABLEDEBUG="enableDebug",s.USEV2="useV2",s.USEWT="useWt",s))(Zd||{}),yo={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}},Ze={"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}},bo={"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}},h={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",LOADEDDATA:"loadeddata",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"},Q={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},No={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Rt=(e=>(e.LIVE="live",e.RTC="rtc",e))(Rt||{}),pi=1,ns=2,wi=4,_i=8,vo=64,Do=16,as="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",Ea="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",ga=h.MAIN,Ta=h.AUXILIARY,tm=0,im=1,rm=2,sm=3,om=4,nm=5,am=6,at="unknown",se={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},el=1/0;function Sa(r){el=r}function Xt(){return el}var cm=30,Ve={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"},dm=1e4,Ia=1e4,Aa=1e4,fi="unified-plan",ur="plan-b",Vi=1028,tl=(t=>(t[t.UNPUBLISH=-1]="UNPUBLISH",t[t.PUBLISHING=0]="PUBLISHING",t[t.PUBLISHED=1]="PUBLISHED",t))(tl||{}),Oo=500,lm=1e3,um=h.BIG,hm=h.SMALL,cs=10*1e3,ct={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_OLD:"schedule.rtc.tencentcloud.com",BACKUP_OVERSEA_OLD:"schedule-ecdn.rtc.tencentcloud.com"},mm=2e3,pm={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},Ca=5,Ui="default",ds=Ui,_m="communications",fm=Object.keys(nt),Ra=["normal leave","timeout leave","kick","role change"],hr=10,mr=2e3,Ei="ric",ls="raf",Bi="interval",gi="timeout",Mo=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"];function Qt({url:r,body:i,method:e,timeout:t}){let s=new XMLHttpRequest;return new Promise((o,n)=>{s.onreadystatechange=()=>{if(s.readyState===4)if(s.status>=200&&s.status<300)try{let a=JSON.parse(s.response);o({data:a})}catch(a){o({data:s.response})}else n({status:s.status,statusText:s.statusText||"request failed!"})},s.timeout=t||5e3,s.open(e||"POST",r,!0),s.send(i)})}function ba(r){return _(this,null,function*(){let i=x(),e=JSON.stringify(r);try{if(!CompressionStream||e.length<=2800)return e;let s=new Blob([e],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),a=yield(yield(yield new Response(s)).blob()).arrayBuffer();return I.debug(`compressJSON ${e.length} -> ${a.byteLength} ${x()-i}ms`),a}catch(t){return e}})}var dt=1e8;var M={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"},Ae={AVOID_REPEATED_CALL(r){return`previous ${r.name}() is ongoing, please avoid repeated calls.`},INVALID_PARAMETER_REQUIRED({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:r,rule:i,fnName:e,value:t}){let s=`${r||i.name}`,o="";return Array.isArray(i.type)?o=i.type.join("|"):o=i.type,`'${s}' must be type of ${o} when calling ${e}(), received type: ${fe(t)}.`},INVALID_PARAMETER_EMPTY({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:r,rule:i,fnName:e,value:t}){let s=`${r||i.name}`,o=`${i.instanceOf.name||i.instanceOf}`;return`'${s}' must be instanceof ${o} when calling ${e}(), received type: ${fe(t)}.`},INVALID_PARAMETER_RANGE({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_MIN({key:r,rule:i,fnName:e,value:t}){return`the min value of ${r||i.name} is ${i.min}, received: ${t}.`},INVALID_PARAMETER_MAX({key:r,rule:i,fnName:e,value:t}){return`the max value of ${r||i.name} is ${i.max}, received: ${t}.`},API_CALL_TIMEOUT(r){return`${r.commandDesc||r.command} timeout observed.`},SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED(r){return`SignalChannel setup failure: (errorCode: ${r.errorCode}, errorMsg: ${r.errorMsg} }).`},ERROR_MESSAGE(r){let i=`${r.type} failed`;return r.message&&(i=`${i}: ${r.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(r){return`exchange sdp failed ${r.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(r){return`'${r}' must be validate string when useStringRoomId is true.`},INVALID_ROOMID_INTEGER(r){return`'${r}' 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:r,code:i}){return`Failed to join room - ${r} code: ${i}`},REJOIN_ROOM_FAILED(r){return`reJoin room: ${r.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(r){return`duplicate ${r} stream publishing, please unpublish your prev ${r} 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:r,userId:i,streamType:e}){return`failed to subscribe ${i} ${e} stream, reason: ${r}.`},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(r){return`switchRole failed, errCode: ${r.code} errMsg: ${r.message}.`},CLIENT_BANNED(r){return`client was banned because of ${r.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(r){return`startPublishCDNStream failed, errMsg: ${r.message}.`},STOP_PUBLISH_CDN_FAILED(r){return`stopPublishCDNStream failed, errMsg: ${r.message}.`},INVALID_STREAM_ID(r){return`'${r}' 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(r){return`cannot replace ${r.kind} track because stream has not ${r.kind} track`},NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED(r){return`startMixTranscode failed, errMsg: ${r.message}.`},STOP_MIX_TRANSCODE_FAILED(r){return`stopMixTranscode failed, errMsg: ${r.message}.`},MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO({key:r,rule:i,fnName:e,value:t}){return`'${r||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(r){return`'${r}' 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:r,fnName:i})=>`'${r}' is not found in the document object when calling ${i}().`,INVALID_ELEMENT_ID_TYPE:({key:r,fnName:i,type:e})=>`the element corresponding to '${r}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`,PLAY_FAILED:r=>`${r.media} play failed\uFF0Cbrowser exception: ${r.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(r){return`${r}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(r){return`${r.signalResponse} failed, response code is ${r.code} , errMsg: ${r.message}.`},CATCH_HANDLER_ERROR({name:r,event:i}){return`an error was caught in ${r}.on('${i}', handler), please check your code in 'handler'.`},API_NOT_EXIST({name:r}){return`experimental api ${r} does not exist.`},REPEAT_JOIN:r=>"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:r}){return`failed to call ${r}() because client was destroyed.`},SEI_NOT_SUPPORT:r=>`not support to sendSEIMessage${r===!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:r,name:i,timesInSecond:e,maxSizeInSecond:t})=>`api ${i} call ${r?"size":"times"} is over ${r?`${t} bytes`:e} in a second.`,CONNECTION_ABORTED(r){return`connection aborted due to: ${r}`},API_CALL_ABORTED(r){let i;return r.message.includes("REMOTE_STREAM_NOT_EXIST")?i=`Subscribe ${r.userId} ${r.streamType} stream aborted, reason: remote user ${r.userId} unpublished stream.`:i=`API aborted, reason: ${r.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:r=>`'streamType' is required when 'userId' is not '*', calling ${r}()`};var Rr={};es(Rr,{ANDROID_VERSION:()=>Da,CHROME_MAJOR_VERSION:()=>mt,CHROME_VERSION:()=>Qo,EDGE_VERSION:()=>Lo,EDG_MAJOR_VERSION:()=>Ma,EDG_VERSION:()=>xo,FIREFOX_MAJOR_VERSION:()=>Oa,FIREFOX_VERSION:()=>ko,HUAWEI_VERSION:()=>Jo,IE_VERSION:()=>Im,IOS_MAIN_VERSION:()=>Is,IOS_VERSION:()=>Ii,IPADQQB_VERSION:()=>Ho,IS_ANDROID:()=>pe,IS_ANDROID_WEBVIEW:()=>xa,IS_ANY_SAFARI:()=>Cr,IS_CHROME:()=>Ar,IS_CHROME_OS:()=>nl,IS_CHROMIUM_BASE:()=>Pe,IS_EDG:()=>fr,IS_EDGE:()=>_r,IS_ELECTRON:()=>Cm,IS_FIREFOX:()=>ie,IS_HEADLESS_CHROME:()=>La,IS_HUAWEI:()=>Rm,IS_HUAWEIBROWSER:()=>Ts,IS_IE:()=>ol,IS_IE8:()=>Sm,IS_IOS:()=>We,IS_IOS_13_OR_14:()=>wa,IS_IOS_15_1:()=>Pa,IS_IPAD:()=>us,IS_IPADQQB:()=>Es,IS_IPAD_PRO:()=>va,IS_IPHONE:()=>$i,IS_IPOD:()=>sl,IS_LINUX:()=>Go,IS_LOCAL:()=>Yt,IS_MAC:()=>bt,IS_MACQQB:()=>fs,IS_MIBROWSER:()=>gs,IS_MQQB:()=>Tr,IS_NATIVE_ANDROID:()=>Tm,IS_OLD_ANDROID:()=>gm,IS_OPPOBROWSER:()=>Sr,IS_SAFARI:()=>Ue,IS_SAFARI_15_1:()=>ym,IS_SAMSUNGBROWSER:()=>Ss,IS_SOGOU:()=>ms,IS_SOGOUM:()=>hs,IS_TBS:()=>ht,IS_UCBROWSER:()=>ka,IS_VIVOBROWSER:()=>Ir,IS_WECHAT:()=>Er,IS_WIN:()=>Ti,IS_WQQB:()=>_s,IS_WX:()=>Am,IS_X5MQQB:()=>gr,IS_XWEB:()=>ps,MACQQB_VERSION:()=>Fo,MI_VERSION:()=>Wo,MQQB_VERSION:()=>pr,OPPO_VERSION:()=>qo,SAFARI_VERSION:()=>Si,SAMSUNG_VERSION:()=>jo,SOGOUM_VERSION:()=>Po,SOGOU_VERSION:()=>wo,TBS_VERSION:()=>Vo,UA_DATA_STRING:()=>lt,USER_AGENT:()=>ut,VIVO_VERSION:()=>Xo,WECHAT_VERSION:()=>Bo,WQQB_VERSION:()=>$o,XWEB_VERSION:()=>Uo,browserInfo:()=>yt,getBrowserInfo:()=>al,getChromeMajorVersion:()=>zt,getDeviceModel:()=>Va,getOSName:()=>zo,getOSString:()=>Cs,getOSType:()=>bm,getTerminalType:()=>Ua,getUserAgentData:()=>As,isLocalStorageEnabled:()=>Kt});var ut=typeof navigator=="undefined"?"":navigator.userAgent,q=r=>new RegExp(r,"i").test(ut),Ee=r=>{if(q(r)){let i=new RegExp(`${r}\\/([\\d.]+)`),e=ut.match(i);if(e&&e[1])return e[1]}return""},Na=r=>{if(q(r)){let i=new RegExp(`${r}\\/(\\d+)`),e=ut.match(i);if(e&&e[1])return parseFloat(e[1])}return NaN},il=/AppleWebKit\/([\d.]+)/i.exec(ut),Em=il?parseFloat(il[1]):NaN,us=q("iPad"),va=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&q("Macintosh"),$i=q("iPhone")&&!us,sl=q("iPod"),We=$i||us||sl||va,pe=q("Android"),Da=function(){if(pe){let r=ut.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(r){let i=r[1]&&parseFloat(r[1]),e=r[2]&&parseFloat(r[2]);if(i&&e)return parseFloat(`${r[1]}.${r[2]}`);if(i)return i}}return NaN}(),gm=pe&&q("webkit")&&Da<2.3,Tm=pe&&Da<5&&Em<537,ie=q("Firefox"),ko=Ee("Firefox"),Oa=Na("Firefox"),_r=q("Edge"),Lo=Ee("Edge"),fr=q("Edg"),xo=Ee("Edg"),Ma=Na("Edg"),hs=q("SogouMobileBrowser"),Po=Ee("SogouMobileBrowser"),ms=q("MetaSr\\s"),wo=Ee("MetaSr\\s"),ht=q("TBS"),Vo=Ee("TBS"),ps=q("XWEB"),Uo=Ee("XWEB"),Sm=q("MSIE\\s8\\.0"),ol=q("MSIE\\/\\d+"),Im=function(){if(ol){let r=/MSIE\s(\d+)\.\d/.exec(ut),i=r&&parseFloat(r[1]);return!i&&/Trident\/7.0/i.test(ut)&&/rv:11.0/.test(ut)&&(i=11),i}return NaN}(),Er=q("(micromessenger|webbrowser)"),Bo=Ee("MicroMessenger"),gr=!ht&&q("MQQBrowser")&&q("COVC"),Tr=!ht&&q("MQQBrowser")&&!q("COVC"),pr=Tr||gr?Ee("MQQBrowser"):"",_s=!ht&&q(" QQBrowser"),$o=Ee(" QQBrowser"),fs=!ht&&q("QQBrowserLite"),Fo=Ee("QQBrowserLite"),Es=!ht&&q("MQBHD"),Ho=Ee("MQBHD"),Ti=q("Windows"),bt=!We&&q("MAC OS X"),Go=!pe&&q("Linux"),nl=q("CrOS"),Am=q("MicroMessenger"),ka=q("UCBrowser"),Cm=q("Electron"),gs=q("MiuiBrowser"),Wo=Ee("MiuiBrowser"),Ts=q("HuaweiBrowser"),Rm=q("Huawei"),Jo=Ee("HuaweiBrowser"),Ss=q("SamsungBrowser"),jo=Ee("SamsungBrowser"),Sr=q("HeyTapBrowser"),qo=Ee("HeyTapBrowser"),Ir=q("VivoBrowser"),Xo=Ee("VivoBrowser"),zt=()=>Na("Chrome"),Pe=q("Chrome"),Ar=!_r&&!ms&&!hs&&!ht&&!ps&&!fr&&!_s&&!gs&&!Ts&&!Ss&&!Sr&&!Ir&&Pe,La=q("HeadlessChrome"),mt=zt(),Qo=Ee("Chrome"),Ue=!Pe&&!Tr&&!gr&&!fs&&!Es&&q("Safari"),Cr=Ue||We,Si=Ee("Version"),xa=/Android.*(wv|.0.0.0)/.test(ut),Ii=(()=>{if(va)return Si;if(We){let r=ut.match(/OS (\d+)_(\d+)/i);if(r&&r[1]){let i=r[1];return r[2]&&(i+=`.${r[2]}`),i}}return""})(),Is=Number(Ii.split(".")[0]),ym=Si==="15.1",Pa=Ii==="15.1",wa=(()=>{let r=Number(Ii.split(".")[0]);return r===14||r===13})(),Yt=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",Kt=(()=>{let r;return()=>{if(typeof r=="undefined")try{r=!!window.localStorage}catch(i){r=!1}return r}})(),yt=al();function al(){let r=new Map([[ie,["Firefox",ko]],[fr,["Edg",xo]],[Ar,["Chrome",Qo]],[Ue,["Safari",Si]],[ht,["TBS",Vo]],[ps,["XWEB",Uo]],[Er&&$i,["WeChat",Bo]],[_s,["QQ(Win)",$o]],[Tr,["QQ(Mobile)",pr]],[gr,["QQ(Mobile X5)",pr]],[fs,["QQ(Mac)",Fo]],[Es,["QQ(iPad)",Ho]],[gs,["MI",Wo]],[Ts,["HW",Jo]],[Ss,["Samsung",jo]],[Sr,["OPPO",qo]],[Ir,["VIVO",Xo]],[_r,["EDGE",Lo]],[hs,["SogouMobile",Po]],[ms,["Sogou",wo]]]),i="unknown",e="unknown";return r.has(!0)&&([i,e]=r.get(!0)),{name:i,version:e}}var te=null,lt="";function As(){return _(this,null,function*(){if(te)return te;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return te=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),te&&!lt&&(lt=`UAData: ${te.platform}/${te.platformVersion}`,te.architecture&&te.bitness&&(lt+=` ${te.architecture}/${te.bitness}`),te.mobile&&(lt+=" mobile"),te.model&&(lt+=` model: ${te.model}`),te.fullVersionList&&(lt+=` ${te.fullVersionList.filter(r=>r.brand!=="Not/A)Brand").map(r=>`${r.brand}/${r.version}`).join(",")}`)),te}catch(r){return null}})}function Va(){return(te==null?void 0:te.model)||""}var rl=new Map([[pe,"Android"],[We,"iOS"],[Ti,"Windows"],[bt,"MacOS"],[Go,"Linux"],[nl,"ChromeOS"]]),zo=function(){return rl.get(!0)?rl.get(!0):te?te.platform:"unknown"},Cs=()=>{let r=zo();return r+=`/${yt.name}/${Ue?yt.version:yt.version.split(".")[0]}`,te!=null&&te.platformVersion&&(r+=`/${te.platformVersion}`),te!=null&&te.architecture&&(r+=`/${te.architecture}`),r};function Ua(){return pe?4:$i?2:us?3:bt?12:Ti?5:Go?13:1}function bm(){return pe?"Android":$i?"iPhone":us?"iPad":bt?"Mac":Ti?"Windows":Go?"Linux":"unknown"}var cl=(r,i)=>i?`${Ct}/${r}/${i}`:`${Ct}/${r}/index.html`;var Nm=()=>{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 r=localStorage==null?void 0:localStorage.getItem(fa);if(r){r=JSON.parse(r);let i=document.createElement("script");i.type="text/javascript",i.text=r.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 L(r){let{key:i,data:e,link:t,addDocLink:s=!0}=r,o="",n="",a="";K(Ae[i])?o=Ae[i](e):z(Ae[i])&&(o=Ae[i]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:d}=Nm();t?a=`${t.className}.html#${t.fnName}`:d&&d[i]&&(K(d[i])?a=d[i](e):z(d[i])&&(a=d[i]));let u=o;return Nt()&&(c&&c[i]&&(K(c[i])?n=c[i](e):z(c[i])&&(n=c[i])),n&&(s?u=`${n}
|
|
6
|
+
\u8BF7\u67E5\u770B\u6587\u6863: ${cl("zh-cn",a)}
|
|
7
7
|
|
|
8
|
-
`:
|
|
8
|
+
`:u=`${n}
|
|
9
9
|
|
|
10
|
-
`,
|
|
11
|
-
Refer to: ${
|
|
12
|
-
`),
|
|
13
|
-
${t.stack}`)),this.sendRequest(
|
|
14
|
-
`));function Mt(r){de(r)&&r!==$a&&($a=r,I.info(`setIsNeedToSchedule ${r}`))}g.on("28",()=>Mt(!0));g.on("63",()=>Mt(!0));g.on("84",()=>Mt(!0));g.on("201",r=>{r.state==="RECONNECTING"&&Mt(!0)});g.on("202",r=>{r.state==="RECONNECTING"&&Mt(!0)});function km(r,i,e){let t={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let s=performance.getEntriesByType("resource"),o=Cr(r,h.MAIN),n=Cr(r,h.BACKUP);for(let a of s)if(a.startTime>=e&&(a.name===o||a.name===n)&&a.transferSize>0){let c=a.name===o?h.MAIN:h.BACKUP,d=Math.round(a.duration),l=Math.round(a.domainLookupStart-a.startTime),p=a.redirectStart>0?Math.round(a.redirectEnd-a.redirectStart):0,m=a.fetchStart>0?Math.round(a.domainLookupStart-a.fetchStart):0,f=Math.round(a.domainLookupEnd-a.domainLookupStart),R=Math.round(a.requestStart-a.secureConnectionStart),C=Math.round(a.secureConnectionStart-a.connectStart),v=Math.round(a.responseStart-a.requestStart),U=Math.round(a.responseEnd-a.responseStart),Ge=[f,R,C,v,U];Z.uploadEvent({log:`stat-schedule-net:${d}(${l}(${p}->${m})->${Ge.join("->")}) ${c}`,userId:i}),t=P(N({},t),{totalCost:d,local:l,dns:f,tcp:C,tls:R,request:v,response:U});break}}catch(s){I.error("getScheduleDetailCost error",s)}return t}function uu(d){return _(this,arguments,function*({userId:r,sdkAppId:i,useStringRoomId:e,roomId:t,userSig:s,version:o,frameWorkType:n,role:a,latencyLevel:c}){if(!$a&&Ba)return{isCached:!0,result:Ba};let l={delta:0,count:[1,1],msg:[],detail:[]};try{let p=new FormData;p.append("userId",String(r)),p.append("sdkAppId",String(i)),p.append("isStrGroupId",String(e)),p.append("groupId",String(t)),p.append("sdkVersion",o),p.append("userSig",String(s)),a&&p.append("role",String(a)),c&&p.append("latencyLevel",String(c)),n&&p.append("frameWorkType",String(n));let m=x(),f=yield xm(p,l,i);f.config&&(f.config.loggerDomain&&Li(f.config.loggerDomain),de(f.config.scheduleCache)&&Mt(!f.config.scheduleCache)),l.delta=x()-m;let R=km(Number(i),r,m);return Ba=f,{isCached:!1,result:f,detailCost:R}}catch(p){let m=he(p)?p[0]:p,f=ee(m.code)?m.code:0,R=`schedule failed${m.message?`: ${m.message}`:""}`,C=new b({code:A.SCHEDULE_FAILED,extraCode:f,message:L({key:M.JOIN_ROOM_FAILED,data:{error:R,code:f}})});throw I.error(R,f),C}})}var Ii={main:"",backup:""};function Fa(r){he(r)?(Ii.main=r[0],Ii.backup=r[1]):Ii.main=r}function Cr(r,i=h.MAIN,e=!1){return`https://${Ii[i]||hu(r,i,e)}/api/v1/config`}function lu(r,i=h.MAIN){return`https://${Ii[i]||hu(r,i)}/api/v1/trtcAutoConf`}function hu(r,i=h.MAIN,e=!1){if(Cs(r))return i===h.MAIN?at.MAIN_OVERSEA:at.BACKUP_OVERSEA;let t;return Cs(r)?e?t=i===h.MAIN?at.MAIN_OVERSEA_OLD:at.BACKUP_OVERSEA_OLD:t=i===h.MAIN?at.MAIN_OVERSEA:at.BACKUP_OVERSEA:t=i===h.MAIN?at.MAIN:at.BACKUP,t}function Lm(r,i,e){return new Promise((t,s)=>{Xt({url:r,body:i,timeout:e.timeout}).then(o=>{o.data.code===0?t(o.data.data):s({code:o.data.code,message:o.data.msg})}).catch(s)})}var du=(r,i)=>vt({retryFunction:Lm,settings:{retries:3,timeout:0},onError:i,onRetrying:r});function xm(r,i,e){return new Promise((t,s)=>{let o=null;Rs([du(n=>i.count[0]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:d})=>{i.msg[0]=n.message,o||(c>=2&&(d[0]=Cr(e,h.MAIN,!0)),a())})(Cr(e,h.MAIN),r,{get timeout(){return Rr(2+i.count[0])*1e3}}),du(n=>i.count[1]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:d})=>{i.msg[1]=n.message,o||(c>=2&&(d[0]=Cr(e,h.BACKUP,!0)),a())})(Cr(e,h.BACKUP),r,{get timeout(){return Rr(2+i.count[1])*1e3}})]).then(n=>{o=n,t(o)}).catch(s)})}var Pm=function(){return new URLSearchParams(location.search).get("trtc_env")||""},Cs=r=>Number(r)<14e8,Si=function(r,i){let e;ss?e=ss:e=Cs(r)?pa:ma;let t=Math.floor(Math.random()*Kr(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${t}&sdkappid=${r}&cmdtype=${i}`},ys="unknown";function pu(){if(ys!=="unknown")return ys;let{userAgent:r,connection:i}=navigator,e=(r.match(/NetType\/\S+/)||[])[0]||"";e=e.toLowerCase().replace("nettype/",""),e==="3gnet"&&(e="3g");let t=i&&i.type&&i.type.toLowerCase(),s=i&&i.effectiveType&&i.effectiveType.toLowerCase();return s==="slow-2"&&(s="2g"),t&&(ys=_u(t,s)),ys}function _u(r,i){if(Ao[r])return r;switch(r){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function Ha(r){ys=_u(r)}function br(){return Ao[pu()]}function wm(r,i){for(let e of Reflect.ownKeys(i))if(e!=="constructor"&&e!=="prototype"&&e!=="name"){let t=Object.getOwnPropertyDescriptor(i,e)||"";Object.defineProperty(r,e,t)}return r}function Vm(r,i=48e3){return fu(r/4,i)}function fu(r,i=48e3){return r*1e3/i}function Um(r,i=48e3){return Eu(r,i)*4}function Eu(r,i=48e3){return r*i/1e3}var gu=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},Nt=()=>{let r=navigator.language;return r=r.substring(0,2),r==="zh"},Je=function(r){if(!r||typeof r!="object"||Object.prototype.toString.call(r)!="[object Object]")return!1;let i=Object.getPrototypeOf(r);if(i===null)return!0;let e=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function Rr(r,i=1,e=1){return r<=1?e:Rr(r-1,e,i+e)}function kt(r){return r>8?30*1e3:Rr(r)*1e3}function fe(r){return Reflect.apply(Object.prototype.toString,r,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var W=r=>typeof r=="function",T=r=>typeof r=="undefined",Y=r=>typeof r=="string",ee=r=>typeof r=="number",de=r=>typeof r=="boolean",mt=r=>fe(r)==="object",he=r=>fe(r)==="array",Bm=r=>fe(r)==="MediaStreamTrack".toLowerCase(),_t=r=>r.isRemote,bs=r=>fe(r)==="promise",Ns=r=>W(r)&&r.prototype.constructor===r,zo=r=>Ns(r)?r.prototype.constructor.name:"",$m=typeof AudioWorkletNode!="undefined";function Rs(r){return new Promise((i,e)=>{let t=[];r.forEach(s=>{s.then(i).catch(o=>{t.push(o),t.length===r.length&&e(t)})})})}function x(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var mu=r=>+r<10?`0${r}`:r,Fm=r=>{let i=r.match(/^\d+\.\d+\.\d+/)[0];if(!i)return r;let e=i.split("."),t=mu(e[1])+mu(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${t}`},Hm=Object.prototype.hasOwnProperty,{toString:iE}=Object.prototype;function Ga(r){if(r==null)return!0;if(typeof r=="boolean")return!1;if(typeof r=="number")return r===0;if(typeof r=="string"||typeof r=="function"||Array.isArray(r))return r.length===0;if(r instanceof Error)return r.message==="";if(Je(r))switch(Object.prototype.toString.call(r)){case"[object File]":case"[object Map]":case"[object Set]":return r.size===0;case"[object Object]":{for(let i in r)if(Hm.call(r,i))return!1;return!0}}return!1}function Ai(r,i){return{userId:i,hasAudio:!!(r&mi),hasVideo:!!(r&hi),hasAuxiliary:!!(r&xi),hasSmall:!!(r&os),audioMuted:!!(r&No),videoMuted:!!(r&vo),audioAvailable:!!(r&mi)&&!(r&No),videoAvailable:!!(r&hi)&&!(r&vo)}}function Gm(r){let i={urls:`turn:${r.url}`};return!T(r.username)&&!T(r.credential)&&(i.username=r.username,i.credential=r.credential,i.credentialType="password",T(r.credentialType)||(i.credentialType=r.credentialType)),i}function vs(r,i=!0){if(!Y(r))return 0;let e=r.split(".");return i?(Number(e[0])<<24|Number(e[1])<<16|Number(e[2])<<8|Number(e[3]))>>>0:(Number(e[3])<<24|Number(e[2])<<16|Number(e[1])<<8|Number(e[0]))>>>0}var Kt=function(r,i,e,t){if(!(mt(r)&&mt(i)))return 0;let s=0,o=Object.keys(i),n;for(let a=0,c=o.length;a<c;a++)if(n=o[a],!(T(i[n])||e&&e.includes(n)))if(mt(r[n])&&mt(i[n]))s+=Kt(r[n],i[n],e,t);else{if(t&&t.includes(i[n]))continue;r[n]!==i[n]&&(r[n]=yr(i[n]),s+=1)}return s};function yr(r){if(he(r)){let i=[];return r.forEach((e,t)=>{i[t]=yr(e)}),i}if(mt(r)){let i={};return Object.keys(r).forEach(e=>{i[e]=yr(r[e])}),i}return r}var Ds=r=>{let i=[];if(he(r))i=[...r];else if(Y(r)){let e=document.getElementById(r);e&&i.push(e)}else r&&i.push(r);return i},Wm=r=>Y(r)?document.getElementById(r):r,Jm=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"}),jm=()=>Jm.format(new Date);function pt(r,{keysToInclude:i,keysToExclude:e}){try{if(he(r))return`[${r.map(n=>pt(n,{keysToInclude:i,keysToExclude:e})).join(",")}]`;if(!Je(r)||!he(i)&&!he(e))return JSON.stringify(r);let t={},s=new Set(i),o=new Set(e);return Object.keys(r).forEach(n=>{(o.size===0&&s.has(n)||s.size===0&&!o.has(n))&&(t[n]=Je(r[n])||he(r[n])?JSON.parse(pt(r[n],{keysToExclude:e,keysToInclude:i})):r[n])}),JSON.stringify(t)}catch(t){return"{}"}}function Wa(r,i=!1){let e=[];return Object.keys(r).forEach(t=>{i===r[t]&&e.push(t)}),pt(r,{keysToInclude:e})}function Yo(r){return r.replace(/[\u4e00-\u9fa5]/g,"aa").length}var Ja=()=>{var r,i,e,t;return(r=window.screen)!=null&&r.orientation?!!((t=(e=(i=window.screen)==null?void 0:i.orientation)==null?void 0:e.type)!=null&&t.includes("portrait")):window.orientation===0||window.orientation===180},Os=r=>_(void 0,null,function*(){return new Promise((i,e)=>{let t;if(Y(r))t=new Image,t.crossOrigin="anonymous",t.src=r;else if(t=r,t.complete){i(t);return}t.onload=()=>i(t),t.onerror=e})}),ja=r=>{let i=r.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]<<0},Ko=r=>(Object.keys(r).forEach(i=>{ee(r[i])&&(i.startsWith("uint")||i.startsWith("int"))?r[i]=Math.floor(r[i]):(Je(r[i])||he(r[i]))&&Ko(r[i])}),r);function Zo(r){return new Promise(i=>setTimeout(i,r))}var qa=(r,i)=>{let e=null;return function(...t){return e||(e=r.apply(i||this,t),e.finally(()=>e=null),e)}};var qm=Object.prototype.hasOwnProperty;var Tu=r=>typeof r=="function",Zt=r=>typeof r=="undefined";var Su=r=>typeof r=="boolean";var Xm=function(r){if(!r||typeof r!="object"||Object.prototype.toString.call(r)!="[object Object]")return!1;let i=Object.getPrototypeOf(r);if(i===null)return!0;let e=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function Iu(r){if(r==null)return!0;if(typeof r=="boolean")return!1;if(typeof r=="number")return r===0;if(typeof r=="string"||typeof r=="function"||Array.isArray(r))return r.length===0;if(r instanceof Error)return r.message==="";if(Xm(r))switch(Object.prototype.toString.call(r)){case"[object File]":case"[object Map]":case"[object Set]":return r.size===0;case"[object Object]":{for(let i in r)if(qm.call(r,i))return!1;return!0}}return!1}var Nr=class{constructor(i){u(this,"userId");u(this,"remoteUserId");u(this,"id");u(this,"sdkAppId");u(this,"type");u(this,"isLocal");this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=Su(i.isLocal)?i.isLocal:!0,this.type=this.isLocal?"":i.type}createChild(i){return Object.setPrototypeOf(i,this)}setUserId(i){this.userId=i}setSdkAppId(i){this.sdkAppId=i}log(i,e){let t=this.isLocal?this.userId:this.remoteUserId;e.unshift(`[${this.isLocal?"\u2191":"\u2193"}${this.type&&this.type!=="main"?"*":""}${this.id}${t?`|${t}`:""}]`),I.log(i,e,Zt(this.userId)||Iu(this.userId),this.userId,this.sdkAppId)}info(...i){this.log(2,i)}debug(...i){this.log(1,i)}warn(...i){this.log(3,i)}error(...i){this.log(4,i)}};var E=Dt;var Qm="%cTRTC%c%s",zm="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",Ym="display: inline",Km=!(We||pe||ka),Xa=class{constructor(){u(this,"_isEnableUploadLog",!0);u(this,"_localJoinedUser",new Map);u(this,"_queue",[]);u(this,"_timeoutId",-1);u(this,"_logLevel",1);u(this,"_logLevelToUpload",2);!cr&&!rs&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){g.on(E.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var e;((e=i==null?void 0:i.config)==null?void 0:e.logLevelToUpload)&&ot[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),g.on(E.JOIN_SUCCESS,({room:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),g.once(E.JOIN_FAILED,()=>{this.startUpload()}),g.on(E.LEAVE_SUCCESS,({room:i})=>{this.deleteJoinedUser(i.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(i){this._localJoinedUser.set(i.userId,i),this.startUpload()}deleteJoinedUser(i){this._localJoinedUser.delete(i)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),2e3)}getLogsToUpload(){let i={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return i;let e=0;for(;e<this._queue.length&&e!==50;e++){let t=this._queue[e];if(t.forAllJoinedClients)this._localJoinedUser.forEach(({userId:s,sdkAppId:o})=>{i.map.has(s)?i.map.get(s).logs.push(t):i.map.set(s,{userId:s,sdkAppId:o,logs:[t]})});else if(Y(t.userId)&&ee(t.sdkAppId)){let{userId:s,sdkAppId:o}=t;i.map.has(s)?i.map.get(s).logs.push(t):i.map.set(s,{userId:s,sdkAppId:o,logs:[t]})}}return i.map.size>0&&(i.splicedQueue=this._queue.splice(0,e)),i}upload(){return _(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:i,splicedQueue:e}=this.getLogsToUpload();if(i.size===0)return;try{let s=[...i.values()];for(let o=0;o<s.length;o++){let{userId:n,sdkAppId:a,logs:c}=s[o];yield this.uploadLogWithRetry(JSON.stringify({timestamp:Io(),sdkAppId:String(a),userId:n,version:Re,log:c.map(d=>d.log).join(`
|
|
15
|
-
`)}),a),c.forEach(d=>d.uploaded=!0)}}catch(s){}let t=e.filter(s=>!s.uploaded);t.length>0&&(this._queue=t.concat(this._queue))})}uploadLogWithRetry(i,e){return vt({retryFunction:()=>Xt({url:Si(e,li.LOG),body:i,timeout:5e3}),settings:{retries:3,timeout:1e3},onError:({retry:t})=>{t()}})()}getPrefix(i){let e=new Date;e.setTime(ts());let t=String(e.getMilliseconds());return"padStart"in String.prototype&&(t=t.toString().padStart(3,"0")),`[${e.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${t}] <${ot[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){T(ot[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(Y(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch(e){return""}}log(i,e,t=!0,s,o){var c;e.unshift(this.getPrefix(i));let n={log:e.reduce((d,l)=>`${d} ${this.logChunkToString(l)}`.trim(),""),level:i,userId:s,sdkAppId:o,forAllJoinedClients:t};if(g.emit(E.LOG,{log:n}),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push(n),i<this._logLevel)return;let a=((c=ot[i])==null?void 0:c.toLowerCase())||"info";Km?console[a](Qm,zm,Ym,...e):console[a](...e)}debug(...i){this.log(1,i)}info(...i){this.log(2,i)}warn(...i){this.log(3,i)}error(...i){this.log(4,i)}createLogger(i){return new Nr(i)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;ot[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}},I=new Xa;var Zm=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let i=Math.random()*16|0;return(r=="x"?i:i&3|8).toString(16)})},Ms=Zm;var Qa=class{constructor(){u(this,"_prefix","TRTC");u(this,"_queue",new Map);this.checkStorage()}getRealKey(i){return`${this._prefix}_${i}`}checkStorage(){if(!Yt())return;setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(t=>{if(t.startsWith(this._prefix)){let s=localStorage.getItem(t);if(!s)return!1;let o=JSON.parse(s);if(o&&o.expiresIn<Date.now())return!0}return!1}).forEach(t=>localStorage.removeItem(t))}doFlush(){if(!!Yt())try{for(let[i,e]of this._queue)localStorage.setItem(i,JSON.stringify(e))}catch(i){I.warn(i)}}getItem(i){if(!Yt())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){I.warn(e)}}setItem(i,e){if(!!Yt())try{let t={expiresIn:Date.now()+Co,value:e};this._queue.set(this.getRealKey(i),t)}catch(t){I.warn(t)}}deleteItem(i){if(!Yt())return!1;try{return i=this.getRealKey(i),this._queue.delete(i),localStorage.removeItem(i),!0}catch(e){return I.warn(e),!1}}clear(){if(!!Yt())try{localStorage.clear()}catch(i){I.warn(i)}}},en=new Qa;var ft={};Zr(ft,{HTTPS_API:()=>mp,IS_GET_CAPABILITIES_SUPPORTED:()=>ic,IS_GET_SETTINGS_SUPPORTED:()=>xt,IS_INSERTABLE_STREAM_SUPPORTED:()=>Or,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>yi,IS_SEI_SUPPORTED:()=>Fi,IS_SPC_SUPPORTED:()=>Dr,basis:()=>Ep,checkSystemRequirementsInternal:()=>on,decodeSupportStatus:()=>sn,encodeSupportStatus:()=>Za,getBrowserInfo:()=>dp,getDisplayResolution:()=>ku,isAddTransceiverSupported:()=>tt,isBrowserSupported:()=>ec,isGetReceiversSupported:()=>$i,isGetSendersSupported:()=>Ri,isGetTransceiversSupported:()=>Lt,isGetUserMediaSupported:()=>Lu,isMediaDevicesSupported:()=>rn,isMediaSessionSupported:()=>wu,isMediaStreamTrackProcessorSupported:()=>up,isReplaceTrackSupported:()=>tc,isSIMDSupported:()=>fp,isScreenCaptureApiAvailable:()=>Ls,isSelectedCandidatePair:()=>Ci,isSetParametersSupported:()=>Ps,isSmallStreamAPISupported:()=>Pu,isSmallStreamSupported:()=>xs,isStopTransceiverSupported:()=>_p,isTRTCSupported:()=>lp,isUnifiedPlanDefault:()=>pp,isUsedInHttpProtocol:()=>ii,isWebAudioSupported:()=>xu,isWebCodecSupported:()=>nn,isWebCodecsSupported:()=>Mu,isWebRTCSupported:()=>rc,isWebTransportSupported:()=>Vu});var Ka=Se(Du(),1);var K={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},cp=new Map([[ie,["Firefox",Mo]],[pr,["Edg",Lo]],[Sr,["Chrome",Xo]],[Ue,["Safari",gi]],[lt,["TBS",wo]],[ms,["XWEB",Vo]],[_r&&Ui,["WeChat",Uo]],[ps,["QQ(Win)",Bo]],[Er,["QQ(Mobile)",hr]],[fr,["QQ(Mobile X5)",hr]],[_s,["QQ(Mac)",$o]],[fs,["QQ(iPad)",Fo]],[Es,["MI",Go]],[gs,["HW",Wo]],[Ts,["Samsung",Jo]],[gr,["OPPO",jo]],[Tr,["VIVO",qo]],[mr,["EDGE",ko]],[ls,["SogouMobile",xo]],[hs,["Sogou",Po]]]);function dp(){let r=cp.get(!0),i=r?r[0]:"unknown",e=r?r[1]:"unknown";return{browserName:i,browserVersion:e}}var ec=function(){return!(Ma||mr||pr&&Oa<80||ie&&Da<56)},Mu=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every(i=>i in window)},rn=function(){if(!navigator.mediaDevices)return ii()||I.error(Ae.NOT_SUPPORTED_MEDIA),!1;let r=["getUserMedia","enumerateDevices"];return r.filter(i=>i in navigator.mediaDevices).length===r.length},Ou=!1;function ii(){return location.protocol==="http:"&&!zt?(Ou||I.error(L({key:M.NOT_SUPPORTED_HTTP})),Ou=!0,!0):!1}var up=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},Za=function(){return _(this,null,function*(){if(K.detail.isH264EncodeSupported&&K.detail.isVp8EncodeSupported)return{isH264EncodeSupported:K.detail.isH264EncodeSupported,isVp8EncodeSupported:K.detail.isVp8EncodeSupported};let r,i=!1,e=!1;try{let t=new RTCPeerConnection,s=document.createElement(h.CANVAS);s.getContext("2d");let o=s.captureStream(0);return t.addTrack(o.getVideoTracks()[0],o),r=yield t.createOffer(),r.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),r.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),t.close(),K.detail.isH264EncodeSupported=i,K.detail.isVp8EncodeSupported=e,{isH264EncodeSupported:K.detail.isH264EncodeSupported,isVp8EncodeSupported:K.detail.isVp8EncodeSupported}}catch(t){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}})},sn=function(){return _(this,null,function*(){if(K.detail.isH264DecodeSupported&&K.detail.isVp8DecodeSupported)return{isH264DecodeSupported:K.detail.isH264DecodeSupported,isVp8DecodeSupported:K.detail.isVp8DecodeSupported};let r,i=!1,e=!1;try{let t=new RTCPeerConnection;return r=yield t.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),r.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),r.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),t.close(),{isH264DecodeSupported:i,isVp8DecodeSupported:e}}catch(t){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}})},on=qa(()=>_(void 0,null,function*(){if(K.result&&K.detail.isH264EncodeSupported&&K.detail.isVp8EncodeSupported&&K.detail.isH264DecodeSupported&&K.detail.isVp8DecodeSupported)return K;let r=ec(),i=rc(),e=Mu(),t=rn(),{isH264EncodeSupported:s,isVp8EncodeSupported:o}=yield Za(),{isH264DecodeSupported:n,isVp8DecodeSupported:a}=yield sn();if(!s||!o){let c=yield Za();I.warn(`detect encode again h264:${s} vp8:${o} result: ${JSON.stringify(c)}`),s=c.isH264EncodeSupported,o=c.isVp8EncodeSupported}if(s&&n&&(gr||Tr||La)&&!lt&&Qt()<79){let{encode:c,decode:d}=yield hp();s=c,n=d}return K.result=r&&i&&t&&(s||o)&&(n||a),K.detail.isBrowserSupported=r,K.detail.isWebRTCSupported=i,K.detail.isWebCodecsSupported=e,K.detail.isMediaDevicesSupported=t,K.detail.isScreenShareSupported=Ls(),K.detail.isSmallStreamSupported=xs(),K.detail.isH264EncodeSupported=s,K.detail.isVp8EncodeSupported=o,K.detail.isH264DecodeSupported=n,K.detail.isVp8DecodeSupported=a,K.result||I.error(`${navigator.userAgent} ${Wa(K.detail,!1)}`),gp(),K})),lp=function(){return K.result},Ls=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},tn=null;function hp(){return _(this,null,function*(){return tn||(tn=new Promise(r=>_(this,null,function*(){let i={encode:!1,decode:!1},e=()=>{};try{I.warn("detectH264Supported start");let t=document.createElement("canvas"),s=t.getContext("2d");t.width=320,t.height=240;let o=setInterval(()=>{s.fillText("test",Math.floor(Math.random()*320),Math.floor(Math.random()*240))},66),n=-1,a=-1;e=()=>{clearInterval(n),clearInterval(o),clearTimeout(a),d.close(),l.close(),c.getTracks().forEach(C=>C.stop())},a=setTimeout(()=>{e(),r(i)},2*1e3);let c=t.captureStream(),d=new RTCPeerConnection({}),l=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});d.addEventListener("icecandidate",C=>l.addIceCandidate(C.candidate)),l.addEventListener("icecandidate",C=>d.addIceCandidate(C.candidate)),d.addTrack(c.getVideoTracks()[0],c);let p=yield d.createOffer();yield d.setLocalDescription(p),yield l.setRemoteDescription(p);let m=yield l.createAnswer(),f=Ka.default.parse(m.sdp),R=f.media[0].rtp.findIndex(C=>C.codec==="H264");f.media[0].rtp=[f.media[0].rtp[R]],f.media[0].fmtp=f.media[0].fmtp.filter(C=>C.payload===f.media[0].rtp[0].payload),f.media[0].rtcpFb&&(f.media[0].rtcpFb=f.media[0].rtcpFb.filter(C=>C.payload===f.media[0].rtp[0].payload)),m.sdp=Ka.default.write(f),yield l.setLocalDescription(m),yield d.setRemoteDescription(m),n=setInterval(()=>_(this,null,function*(){i.encode&&i.decode&&(e(),r(i));let C=yield d.getSenders()[0].getStats(),v=yield l.getReceivers()[0].getStats();i.encode||C.forEach(U=>{U.type==="outbound-rtp"&&U.mediaType===h.VIDEO&&U.bytesSent>0&&(i.encode=!0)}),i.decode||v.forEach(U=>{U.type==="inbound-rtp"&&U.mediaType===h.VIDEO&&U.bytesReceived>0&&(i.decode=!0)})}),100)}catch(t){e(),I.warn(t),r(i)}})).then(r=>((!r.encode||!r.decode)&&I.warn(`detectH264Supported encode: ${r.encode} decode: ${r.decode} ${dt}`),r)),tn)})}var mp=(r,i,e)=>{location.protocol==="http:"&&!zt&&(r[i]=()=>{throw new b({code:A.INVALID_OPERATION,message:Ae.NOT_SUPPORTED_HTTP})})},Ci=function(r){return r.type==="candidate-pair"&&r.nominated&&(r.state==="in-progress"||r.state==="succeeded")?!(de(r.selected)&&!r.selected):!1};function ku(){let r="";if(screen.width){let i=screen.width?screen.width*window.devicePixelRatio:"",e=screen.height?screen.height*window.devicePixelRatio:"";r+=`${i} * ${e}`}return r}function Lu(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function xu(){let r={isSupported:!1},i=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let e=0;e<i.length;e++)if(i[e]in window){r.isSupported=!0;break}return r.isSupported}function Pu(){return"captureStream"in HTMLCanvasElement.prototype}function xs(){return _r||We||ht&&ht<63?!1:!!(ec()&&Pu())}var pp=function(){if(T(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let r=null,i=!1;try{r=new RTCPeerConnection({sdpSemantics:pi}),r.addTransceiver(h.AUDIO),i=!0}catch(e){}return r==null||r.close(),i};function $i(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function Ri(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function Lt(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function tt(){return Ss===11?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var Dr=(()=>!(!tt()||Pe&&ht<86))();function _p(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}function tc(){return"RTCRtpSender"in window&&"replaceTrack"in window.RTCRtpSender.prototype}function Ps(){return"RTCRtpSender"in window&&"setParameters"in window.RTCRtpSender.prototype&&Ri()}var xt=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,ic=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,Or="createEncodedStreams"in window.RTCRtpSender.prototype&&Qt()>=86,yi="RTCRtpScriptTransform"in window,Fi="RTCRtpSender"in window&&(Or||yi),rc=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(i=>i in window).length>0};function nn(){let r={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return T(window.AudioDecoder)||(r.AudioDecoder=!0),T(window.AudioEncoder)||(r.AudioEncoder=!0),T(window.VideoDecoder)||(r.VideoDecoder=!0),T(window.VideoEncoder)||(r.VideoEncoder=!0),T(window.ImageDecoder)||(r.ImageDecoder=!0),r}function wu(){return"mediaSession"in navigator&&!T(navigator.mediaSession.setActionHandler)}function Vu(){return!T(window.WebTransport)}function fp(){return typeof WebAssembly!="undefined"?!1:WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]))}function Ep(){let r={browser:`${yt.name}/${yt.version}`,os:Qo(),displayResolution:ku(),isScreenShareSupported:Ls(),isWebRTCSupported:rc(),isGetUserMediaSupported:Lu(),isWebAudioSupported:xu(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:nn(),isMediaSessionSupported:wu(),isWebTransportSupported:Vu()};return navigator.userAgent.includes("miniProgram")&&(r.browser=`mini/${r.browser}`),r}var Uu="checkResult";function gp(){en.setItem(Uu,{ua:navigator.userAgent,checkResult:K})}(function(){ii();let i=en.getItem(Uu);i&&i.ua===navigator.userAgent&&(K=i.checkResult),on()})();var $u=Se(Ne(),1);var Bu=Symbol("instance"),BE=Symbol("abortCtrl"),an=Symbol("cacheResult"),ws=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,Bs.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},Vs=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function Tp(r){return typeof r=="object"&&r&&"then"in r}var Us=new Map;function ue(r,i,e={}){return(t,s,o)=>{let n=e.action||s;if(!e.context){let c=Us.get(t)||[];Us.has(t)||Us.set(t,c),c.push({from:r,to:i,action:n})}let a=o.value;o.value=function(...c){let d=this;if(e.context&&(d=F.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===i)return e.sync?d[an]:Promise.resolve(d[an]);d.state instanceof ws&&d.state.action==e.abortAction&&d.state.abort(d);let l=null;Array.isArray(r)?r.length==0?d.state instanceof ws&&d.state.abort(d):(typeof d.state!="string"||!r.includes(d.state))&&(l=new Vs(d._state,`${d.name} ${n} to ${i} failed: current state ${d._state} not from ${r.join("|")}`)):r!==d.state&&(l=new Vs(d._state,`${d.name} ${n} to ${i} failed: current state ${d._state} not from ${r}`));let p=v=>{if(e.fail&&e.fail.call(this,v),e.sync){if(e.ignoreError)return v;throw v}else return e.ignoreError?Promise.resolve(v):Promise.reject(v)};if(l)return p(l);let m=d.state,f=new ws(m,i,n);Bs.call(d,f);let R=v=>{var U;return d[an]=v,f.aborted||(Bs.call(d,i),(U=e.success)===null||U===void 0||U.call(this,d[an])),v},C=v=>{let U=v instanceof Error?v.message:String(v);return Bs.call(d,m,v),p(new Vs(d._state,`action '${n}' failed :${U}`,v instanceof Error?v:new Error(U)))};try{let v=a.apply(this,c);return Tp(v)?v.then(R).catch(C):e.sync?R(v):Promise.resolve(R(v))}catch(v){return C(v)}}}}var Sp=(()=>typeof window!="undefined"&&window.__AFSM__?(e,t)=>{window.dispatchEvent(new CustomEvent(e,{detail:t}))}:typeof importScripts!="undefined"?(e,t)=>{postMessage({type:e,payload:t})}:()=>{})();function Bs(r,i){let e=this._state;this._state=r;let t=r.toString();r&&this.emit(t,e),this.emit(F.STATECHANGED,r,e,i),this.updateDevTools({value:r,old:e,err:i instanceof Error?i.message:String(i)})}var F=class extends $u.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=F.INIT,i||(i=Date.now().toString(36)),t?Object.setPrototypeOf(this,t):t=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let s=t[Bu];s?this.name=s.name+"-"+s.count++:t[Bu]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=Us.get(i)||[],t=new Set,s=[],o=[],n=new Set,a=Object.getPrototypeOf(i);Us.has(a)&&(a.stateDiagram.forEach(d=>t.add(d)),a.allStates.forEach(d=>n.add(d))),e.forEach(({from:d,to:l,action:p})=>{typeof d=="string"?s.push({from:d,to:l,action:p}):d.length?d.forEach(m=>{s.push({from:m,to:l,action:p})}):o.push({to:l,action:p})}),s.forEach(({from:d,to:l,action:p})=>{n.add(d),n.add(l),n.add(p+"ing"),t.add(`${d} --> ${p}ing : ${p}`),t.add(`${p}ing --> ${l} : ${p} \u{1F7E2}`),t.add(`${p}ing --> ${d} : ${p} \u{1F534}`)}),o.forEach(({to:d,action:l})=>{t.add(`${l}ing --> ${d} : ${l} \u{1F7E2}`),n.forEach(p=>{p!==d&&t.add(`${p} --> ${l}ing : ${l}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:n}}),c}static get(i){let e;return typeof i=="string"?(e=F.instances.get(i),e||F.instances.set(i,e=new F(i,void 0,Object.create(F.prototype)))):(e=F.instances2.get(i),e||F.instances2.set(i,e=new F(i.constructor.name,void 0,Object.create(F.prototype)))),e}static getState(i){var e;return(e=F.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){Sp(F.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){Bs.call(this,i)}};F.STATECHANGED="stateChanged";F.UPDATEAFSM="updateAFSM";F.INIT="[*]";F.ON="on";F.OFF="off";F.instances=new Map;F.instances2=new WeakMap;var Fu=(window==null?void 0:window.requestIdleCallback)||function(r){let i=Date.now();return setTimeout(()=>{r({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-i))}})},1e3)},Ip=(window==null?void 0:window.cancelIdleCallback)||function(r){clearTimeout(r)},Ap=(window==null?void 0:window.cancelAnimationFrame)||(window==null?void 0:window.mozCancelAnimationFrame),$s=class{static generateTaskID(){return this.currentTaskID++}static run(i=fi,e,t){i===Vi?t=N({delay:2e3,count:0,backgroundTask:!0},t):i===_i?t=N({delay:1e4,count:0},t):i===ds?t=N({fps:60,delay:16.6,count:0,backgroundTask:!0},t):t=N({delay:2e3,count:0,backgroundTask:!0},t),mt(e)&&(t=N(N({},t),e)),W(i)&&(e=i,i=fi);let s=N({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:i,callback:e},t);return this.taskMap.set(s.taskID,s),this[i](s),s.taskID}static interval(i){let e=()=>{i.callback(),i.loopCount+=1,this.isBreakLoop(i)};return i.intervalID=setInterval(e,i.delay)}static intervalInWorker(i){i.delay=(1e3/i.fps).toFixed(2);let e=new Worker(URL.createObjectURL(new Blob([`
|
|
10
|
+
`,u+=o)),s&&(u+=`
|
|
11
|
+
Refer to: ${cl("en",a)}
|
|
12
|
+
`),u}var vm=Object.prototype.hasOwnProperty;var vt=r=>typeof r=="function",Zt=r=>typeof r=="undefined";var dl=r=>typeof r=="boolean";var Dm=function(r){if(!r||typeof r!="object"||Object.prototype.toString.call(r)!="[object Object]")return!1;let i=Object.getPrototypeOf(r);if(i===null)return!0;let e=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function ll(r){if(r==null)return!0;if(typeof r=="boolean")return!1;if(typeof r=="number")return r===0;if(typeof r=="string"||typeof r=="function"||Array.isArray(r))return r.length===0;if(r instanceof Error)return r.message==="";if(Dm(r))switch(Object.prototype.toString.call(r)){case"[object File]":case"[object Map]":case"[object Set]":return r.size===0;case"[object Object]":{for(let i in r)if(vm.call(r,i))return!1;return!0}}return!1}var Om=0,Mm=1,ul=2;function km({retryFunction:r,settings:i,onError:e,onRetrying:t,onRetryFailed:s,onRetrySuccess:o,context:n}){return function(...a){let{retries:c=5,timeout:d=1e3}=i,u=0,p=-1,m=Om,f=(R,C)=>_(this,null,function*(){let v=n||this;try{let U=yield r.apply(v,a);u>0&&o&&o.call(this,u),u=0,R(U)}catch(U){let Ge=()=>{clearTimeout(p),u=0,m=ul,C(U)},To=()=>{m!==ul&&u<(vt(c)?c():c)?(u++,m=Mm,vt(t)&&t.call(this,u,Ge),p=window.setTimeout(()=>{p=-1,f(R,C)},vt(d)?d(u):d)):(Ge(),vt(s)&&s.call(this,U))};vt(e)?e.call(this,{error:U,retry:To,reject:C,retryFuncArgs:a,retriedCount:u}):To()}});return new Promise(f)}}var Dt=km;var hl=Se(Ne(),1),Lm=new hl.default,g=Lm;var Ot=(B=>(B.ROOM_DESTROY="1",B.JOIN_START="21",B.JOIN_SCHEDULE_SUCCESS="22",B.JOIN_SIGNAL_CONNECTION_START="23",B.JOIN_SIGNAL_CONNECTION_END="24",B.JOIN_SEND_CMD="25",B.JOIN_RECEIVED_CMD_RES="26",B.JOIN_SUCCESS="27",B.JOIN_FAILED="28",B.LEAVE_START="51",B.LEAVE_SEND_CMD="52",B.LEAVE_SUCCESS="53",B.PUBLISH_START="61",B.SEND_FIRST_VIDEO_FRAME="62",B.PUBLISH_FAILED="63",B.SUBSCRIBE_START="81",B.SUBSCRIBE_SUCCESS="82",B.SUBSCRIBE_FAILED="84",B.UNSUBSCRIBE_SUCCESS="83",B.LOCAL_TRACK_CAPTURE_START="101",B.LOCAL_TRACK_CAPTURE_SUCCESS="102",B.LOCAL_TRACK_CAPTURE_FAILED="103",B.LOCAL_TRACK_PUBLISHED="104",B.LOCAL_TRACK_UNPUBLISHED="105",B.LOCAL_TRACK_REPLACED="106",B.SWITCH_DEVICE_SUCCESS="107",B.TRACK_MUTED="108",B.TRACK_UNMUTED="109",B.REMOTE_TRACK_SUBSCRIBED="110",B.REMOTE_TRACK_UNSUBSCRIBED="111",B.LOCAL_TRACK_RECAPTURE="112",B.PLAY_TRACK_START="151",B.PLAYER_STATE_CHANGED="152",B.VIDEO_LOADED_DATA="153",B.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",B.SIGNAL_CONNECTION_STATE_CHANGED="201",B.PEER_CONNECTION_STATE_CHANGED="202",B.SINGLE_CONNECTION_STAT="203",B.SPC_RECONNECTED="204",B.HEARTBEAT_REPORT="251",B.RECEIVED_PUBLISHED_USER_LIST="252",B.REMOTE_PUBLISH_STATE_CHANGED="253",B.AUDIO_LEVEL_INTERVAL="260",B.NETWORK_QUALITY="261",B.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",B.QUALITY_LIMITATION_CHANGED="263",B.LOG="264",B.SEND_SEI_MESSAGE="265",B))(Ot||{});var Ba=class{constructor(){this._roomIdMap=new Map;typeof registerProcessor=="undefined"&&(this._configs={sdkAppId:"",userId:"",version:Re,env:qt.QCLOUD,browserVersion:yt.name+yt.version,ua:navigator.userAgent})}setConfig({sdkAppId:i,env:e,userId:t,roomId:s}){i!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(i)),this._configs.env=e,this._configs.userId=t,this._roomIdMap.set(t,String(s))}logSuccessEvent(i){Yt||!I.isAbleToUpload||this._configs.env===qt.QCLOUD&&this.uploadEventToKibana(P(N({},i),{result:"success"}))}logFailedEvent(i){if(Yt||!I.isAbleToUpload)return;let{eventType:e,code:t,error:s,userId:o}=i,n={roomId:this._roomIdMap.get(o||this._configs.userId),userId:o,eventType:e,result:"failed",code:t||(s==null?void 0:s.extraCode)||(s==null?void 0:s.code)||A.UNKNOWN};this._configs.env===qt.QCLOUD&&this.uploadEventToKibana(P(N({},n),{error:s}))}uploadEventToKibana(i){let e=`stat-${i.eventType}-${i.result}`;(i.eventType==="delta-join"||i.eventType==="delta-leave"||i.eventType==="delta-publish")&&(e=`${i.eventType}:${i.delta}`),this.uploadEvent({log:e,userId:i.userId}),i.result==="failed"&&(e=`stat-${i.eventType}-${i.result}-${i.code}`,this.uploadEvent({log:e,userId:i.userId,error:i.error}))}uploadEvent({log:i,userId:e,error:t}){let s={timestamp:Ao(),sdkAppId:this._configs.sdkAppId,userId:e||this._configs.userId,version:Re,log:i};t&&(s.errorInfo=t.message,t.stack&&(s.errorInfo+=`
|
|
13
|
+
${t.stack}`)),this.sendRequest(Ai(this._configs.sdkAppId,mi.LOG),s)}sendRequest(i,e){if(!I.isAbleToUpload){setTimeout(()=>{this.sendRequest(i,e)},1e3);return}Qt({url:i,body:JSON.stringify(e)}).catch(()=>{})}},Z=new Ba;var $a=null,Fa=!0;document&&document.head.insertAdjacentHTML("beforeend",Object.values(ct).map(r=>`<link rel="dns-prefetch" href="https://${r}">`).join(`\r
|
|
14
|
+
`));function kt(r){de(r)&&r!==Fa&&(Fa=r,I.info(`setIsNeedToSchedule ${r}`))}g.on("28",()=>kt(!0));g.on("63",()=>kt(!0));g.on("84",()=>kt(!0));g.on("201",r=>{r.state==="RECONNECTING"&&kt(!0)});g.on("202",r=>{r.state==="RECONNECTING"&&kt(!0)});function xm(r,i,e){let t={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let s=performance.getEntriesByType("resource"),o=yr(r,h.MAIN),n=yr(r,h.BACKUP);for(let a of s)if(a.startTime>=e&&(a.name===o||a.name===n)&&a.transferSize>0){let c=a.name===o?h.MAIN:h.BACKUP,d=Math.round(a.duration),u=Math.round(a.domainLookupStart-a.startTime),p=a.redirectStart>0?Math.round(a.redirectEnd-a.redirectStart):0,m=a.fetchStart>0?Math.round(a.domainLookupStart-a.fetchStart):0,f=Math.round(a.domainLookupEnd-a.domainLookupStart),R=Math.round(a.requestStart-a.secureConnectionStart),C=Math.round(a.secureConnectionStart-a.connectStart),v=Math.round(a.responseStart-a.requestStart),U=Math.round(a.responseEnd-a.responseStart),Ge=[f,R,C,v,U];Z.uploadEvent({log:`stat-schedule-net:${d}(${u}(${p}->${m})->${Ge.join("->")}) ${c}`,userId:i}),t=P(N({},t),{totalCost:d,local:u,dns:f,tcp:C,tls:R,request:v,response:U});break}}catch(s){I.error("getScheduleDetailCost error",s)}return t}function pl(d){return _(this,arguments,function*({userId:r,sdkAppId:i,useStringRoomId:e,roomId:t,userSig:s,version:o,frameWorkType:n,role:a,latencyLevel:c}){if(!Fa&&$a)return{isCached:!0,result:$a};let u={delta:0,count:[1,1],msg:[],detail:[]};try{let p=new FormData;p.append("userId",String(r)),p.append("sdkAppId",String(i)),p.append("isStrGroupId",String(e)),p.append("groupId",String(t)),p.append("sdkVersion",o),p.append("userSig",String(s)),a&&p.append("role",String(a)),c&&p.append("latencyLevel",String(c)),n&&p.append("frameWorkType",String(n));let m=x(),f=yield wm(p,u,i);f.config&&(f.config.loggerDomain&&Pi(f.config.loggerDomain),de(f.config.scheduleCache)&&kt(!f.config.scheduleCache)),u.delta=x()-m;let R=xm(Number(i),r,m);return $a=f,{isCached:!1,result:f,detailCost:R}}catch(p){let m=he(p)?p[0]:p,f=ee(m.code)?m.code:0,R=`schedule failed${m.message?`: ${m.message}`:""}`,C=new b({code:A.SCHEDULE_FAILED,extraCode:f,message:L({key:M.JOIN_ROOM_FAILED,data:{error:R,code:f}})});throw I.error(R,f),C}})}var Ci={main:"",backup:""};function Ha(r){he(r)?(Ci.main=r[0],Ci.backup=r[1]):Ci.main=r}function yr(r,i=h.MAIN,e=!1){return`https://${Ci[i]||fl(r,i,e)}/api/v1/config`}function _l(r,i=h.MAIN){return`https://${Ci[i]||fl(r,i)}/api/v1/trtcAutoConf`}function fl(r,i=h.MAIN,e=!1){if(Rs(r))return i===h.MAIN?ct.MAIN_OVERSEA:ct.BACKUP_OVERSEA;let t;return Rs(r)?e?t=i===h.MAIN?ct.MAIN_OVERSEA_OLD:ct.BACKUP_OVERSEA_OLD:t=i===h.MAIN?ct.MAIN_OVERSEA:ct.BACKUP_OVERSEA:t=i===h.MAIN?ct.MAIN:ct.BACKUP,t}function Pm(r,i,e){return new Promise((t,s)=>{Qt({url:r,body:i,timeout:e.timeout}).then(o=>{o.data.code===0?t(o.data.data):s({code:o.data.code,message:o.data.msg})}).catch(s)})}var ml=(r,i)=>Dt({retryFunction:Pm,settings:{retries:3,timeout:0},onError:i,onRetrying:r});function wm(r,i,e){return new Promise((t,s)=>{let o=null;ys([ml(n=>i.count[0]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:d})=>{i.msg[0]=n.message,o||(c>=2&&(d[0]=yr(e,h.MAIN,!0)),a())})(yr(e,h.MAIN),r,{get timeout(){return br(2+i.count[0])*1e3}}),ml(n=>i.count[1]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:d})=>{i.msg[1]=n.message,o||(c>=2&&(d[0]=yr(e,h.BACKUP,!0)),a())})(yr(e,h.BACKUP),r,{get timeout(){return br(2+i.count[1])*1e3}})]).then(n=>{o=n,t(o)}).catch(s)})}var Vm=function(){return new URLSearchParams(location.search).get("trtc_env")||""},Rs=r=>Number(r)<14e8,Ai=function(r,i){let e;os?e=os:e=Rs(r)?_a:pa;let t=Math.floor(Math.random()*Zr(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${t}&sdkappid=${r}&cmdtype=${i}`},bs="unknown";function gl(){if(bs!=="unknown")return bs;let{userAgent:r,connection:i}=navigator,e=(r.match(/NetType\/\S+/)||[])[0]||"";e=e.toLowerCase().replace("nettype/",""),e==="3gnet"&&(e="3g");let t=i&&i.type&&i.type.toLowerCase(),s=i&&i.effectiveType&&i.effectiveType.toLowerCase();return s==="slow-2"&&(s="2g"),t&&(bs=Tl(t,s)),bs}function Tl(r,i){if(Co[r])return r;switch(r){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function Ga(r){bs=Tl(r)}function vr(){return Co[gl()]}function Um(r,i){for(let e of Reflect.ownKeys(i))if(e!=="constructor"&&e!=="prototype"&&e!=="name"){let t=Object.getOwnPropertyDescriptor(i,e)||"";Object.defineProperty(r,e,t)}return r}function Bm(r,i=48e3){return Sl(r/4,i)}function Sl(r,i=48e3){return r*1e3/i}function $m(r,i=48e3){return Il(r,i)*4}function Il(r,i=48e3){return r*i/1e3}var Al=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},Nt=()=>{let r=navigator.language;return r=r.substring(0,2),r==="zh"},Je=function(r){if(!r||typeof r!="object"||Object.prototype.toString.call(r)!="[object Object]")return!1;let i=Object.getPrototypeOf(r);if(i===null)return!0;let e=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function br(r,i=1,e=1){return r<=1?e:br(r-1,e,i+e)}function Lt(r){return r>8?30*1e3:br(r)*1e3}function fe(r){return Reflect.apply(Object.prototype.toString,r,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var K=r=>typeof r=="function",T=r=>typeof r=="undefined",z=r=>typeof r=="string",ee=r=>typeof r=="number",de=r=>typeof r=="boolean",pt=r=>fe(r)==="object",he=r=>fe(r)==="array",Fm=r=>fe(r)==="MediaStreamTrack".toLowerCase(),ft=r=>r.isRemote,Ns=r=>fe(r)==="promise",vs=r=>K(r)&&r.prototype.constructor===r,Yo=r=>vs(r)?r.prototype.constructor.name:"",Hm=typeof AudioWorkletNode!="undefined";function ys(r){return new Promise((i,e)=>{let t=[];r.forEach(s=>{s.then(i).catch(o=>{t.push(o),t.length===r.length&&e(t)})})})}function x(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var El=r=>+r<10?`0${r}`:r,Gm=r=>{let i=r.match(/^\d+\.\d+\.\d+/)[0];if(!i)return r;let e=i.split("."),t=El(e[1])+El(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${t}`},Wm=Object.prototype.hasOwnProperty,{toString:iE}=Object.prototype;function Wa(r){if(r==null)return!0;if(typeof r=="boolean")return!1;if(typeof r=="number")return r===0;if(typeof r=="string"||typeof r=="function"||Array.isArray(r))return r.length===0;if(r instanceof Error)return r.message==="";if(Je(r))switch(Object.prototype.toString.call(r)){case"[object File]":case"[object Map]":case"[object Set]":return r.size===0;case"[object Object]":{for(let i in r)if(Wm.call(r,i))return!1;return!0}}return!1}function Ri(r,i){return{userId:i,hasAudio:!!(r&_i),hasVideo:!!(r&pi),hasAuxiliary:!!(r&wi),hasSmall:!!(r&ns),audioMuted:!!(r&vo),videoMuted:!!(r&Do),audioAvailable:!!(r&_i)&&!(r&vo),videoAvailable:!!(r&pi)&&!(r&Do)}}function Jm(r){let i={urls:`turn:${r.url}`};return!T(r.username)&&!T(r.credential)&&(i.username=r.username,i.credential=r.credential,i.credentialType="password",T(r.credentialType)||(i.credentialType=r.credentialType)),i}function Ds(r,i=!0){if(!z(r))return 0;let e=r.split(".");return i?(Number(e[0])<<24|Number(e[1])<<16|Number(e[2])<<8|Number(e[3]))>>>0:(Number(e[3])<<24|Number(e[2])<<16|Number(e[1])<<8|Number(e[0]))>>>0}var ei=function(r,i,e,t){if(!(pt(r)&&pt(i)))return 0;let s=0,o=Object.keys(i),n;for(let a=0,c=o.length;a<c;a++)if(n=o[a],!(T(i[n])||e&&e.includes(n)))if(pt(r[n])&&pt(i[n]))s+=ei(r[n],i[n],e,t);else{if(t&&t.includes(i[n]))continue;r[n]!==i[n]&&(r[n]=Nr(i[n]),s+=1)}return s};function Nr(r){if(he(r)){let i=[];return r.forEach((e,t)=>{i[t]=Nr(e)}),i}if(pt(r)){let i={};return Object.keys(r).forEach(e=>{i[e]=Nr(r[e])}),i}return r}var Os=r=>{let i=[];if(he(r))i=[...r];else if(z(r)){let e=document.getElementById(r);e&&i.push(e)}else r&&i.push(r);return i},jm=r=>z(r)?document.getElementById(r):r,qm=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"}),Xm=()=>qm.format(new Date);function _t(r,{keysToInclude:i,keysToExclude:e}){try{if(he(r))return`[${r.map(n=>_t(n,{keysToInclude:i,keysToExclude:e})).join(",")}]`;if(!Je(r)||!he(i)&&!he(e))return JSON.stringify(r);let t={},s=new Set(i),o=new Set(e);return Object.keys(r).forEach(n=>{(o.size===0&&s.has(n)||s.size===0&&!o.has(n))&&(t[n]=Je(r[n])||he(r[n])?JSON.parse(_t(r[n],{keysToExclude:e,keysToInclude:i})):r[n])}),JSON.stringify(t)}catch(t){return"{}"}}function Ja(r,i=!1){let e=[];return Object.keys(r).forEach(t=>{i===r[t]&&e.push(t)}),_t(r,{keysToInclude:e})}function Ko(r){return r.replace(/[\u4e00-\u9fa5]/g,"aa").length}var ja=()=>{var r,i,e,t;return(r=window.screen)!=null&&r.orientation?!!((t=(e=(i=window.screen)==null?void 0:i.orientation)==null?void 0:e.type)!=null&&t.includes("portrait")):window.orientation===0||window.orientation===180},Ms=r=>_(void 0,null,function*(){return new Promise((i,e)=>{let t;if(z(r))t=new Image,t.crossOrigin="anonymous",t.src=r;else if(t=r,t.complete){i(t);return}t.onload=()=>i(t),t.onerror=e})}),qa=r=>{let i=r.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]<<0},Zo=r=>(Object.keys(r).forEach(i=>{ee(r[i])&&(i.startsWith("uint")||i.startsWith("int"))?r[i]=Math.floor(r[i]):(Je(r[i])||he(r[i]))&&Zo(r[i])}),r);function en(r){return new Promise(i=>setTimeout(i,r))}var Xa=(r,i)=>{let e=null;return function(...t){return e||(e=r.apply(i||this,t),e.finally(()=>e=null),e)}};var Dr=class{constructor(i){l(this,"userId");l(this,"remoteUserId");l(this,"id");l(this,"sdkAppId");l(this,"type");l(this,"isLocal");this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=dl(i.isLocal)?i.isLocal:!0,this.type=this.isLocal?"":i.type}createChild(i){return Object.setPrototypeOf(i,this)}setUserId(i){this.userId=i}setSdkAppId(i){this.sdkAppId=i}log(i,e){let t=this.isLocal?this.userId:this.remoteUserId;e.unshift(`[${this.isLocal?"\u2191":"\u2193"}${this.type&&this.type!=="main"?"*":""}${this.id}${t?`|${t}`:""}]`),I.log(i,e,Zt(this.userId)||ll(this.userId),this.userId,this.sdkAppId)}info(...i){this.log(2,i)}debug(...i){this.log(1,i)}warn(...i){this.log(3,i)}error(...i){this.log(4,i)}};var E=Ot;var Qm="%cTRTC%c%s",zm="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",Ym="display: inline",Km=!(We||pe||La),Qa=class{constructor(){l(this,"_isEnableUploadLog",!0);l(this,"_localJoinedUser",new Map);l(this,"_queue",[]);l(this,"_timeoutId",-1);l(this,"_logLevel",1);l(this,"_logLevelToUpload",2);!lr&&!ss&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){g.on(E.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var e;((e=i==null?void 0:i.config)==null?void 0:e.logLevelToUpload)&&nt[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),g.on(E.JOIN_SUCCESS,({room:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),g.once(E.JOIN_FAILED,()=>{this.startUpload()}),g.on(E.LEAVE_SUCCESS,({room:i})=>{this.deleteJoinedUser(i.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(i){this._localJoinedUser.set(i.userId,i),this.startUpload()}deleteJoinedUser(i){this._localJoinedUser.delete(i)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),2e3)}getLogsToUpload(){let i={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return i;let e=0;for(;e<this._queue.length&&e!==50;e++){let t=this._queue[e];if(t.forAllJoinedClients)this._localJoinedUser.forEach(({userId:s,sdkAppId:o})=>{i.map.has(s)?i.map.get(s).logs.push(t):i.map.set(s,{userId:s,sdkAppId:o,logs:[t]})});else if(z(t.userId)&&ee(t.sdkAppId)){let{userId:s,sdkAppId:o}=t;i.map.has(s)?i.map.get(s).logs.push(t):i.map.set(s,{userId:s,sdkAppId:o,logs:[t]})}}return i.map.size>0&&(i.splicedQueue=this._queue.splice(0,e)),i}upload(){return _(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:i,splicedQueue:e}=this.getLogsToUpload();if(i.size===0)return;try{let s=[...i.values()];for(let o=0;o<s.length;o++){let{userId:n,sdkAppId:a,logs:c}=s[o];yield this.uploadLogWithRetry(JSON.stringify({timestamp:Ao(),sdkAppId:String(a),userId:n,version:Re,log:c.map(d=>d.log).join(`
|
|
15
|
+
`)}),a),c.forEach(d=>d.uploaded=!0)}}catch(s){}let t=e.filter(s=>!s.uploaded);t.length>0&&(this._queue=t.concat(this._queue))})}uploadLogWithRetry(i,e){return Dt({retryFunction:()=>Qt({url:Ai(e,mi.LOG),body:i,timeout:5e3}),settings:{retries:3,timeout:1e3},onError:({retry:t})=>{t()}})()}getPrefix(i){let e=new Date;e.setTime(is());let t=String(e.getMilliseconds());return"padStart"in String.prototype&&(t=t.toString().padStart(3,"0")),`[${e.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${t}] <${nt[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){T(nt[i])||(this._logLevel!==i&&this.info("setLogLevel",i),this._logLevel=i)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(i){if(z(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch(e){return""}}log(i,e,t=!0,s,o){var c;e.unshift(this.getPrefix(i));let n={log:e.reduce((d,u)=>`${d} ${this.logChunkToString(u)}`.trim(),""),level:i,userId:s,sdkAppId:o,forAllJoinedClients:t};if(g.emit(E.LOG,{log:n}),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push(n),i<this._logLevel)return;let a=((c=nt[i])==null?void 0:c.toLowerCase())||"info";Km?console[a](Qm,zm,Ym,...e):console[a](...e)}debug(...i){this.log(1,i)}info(...i){this.log(2,i)}warn(...i){this.log(3,i)}error(...i){this.log(4,i)}createLogger(i){return new Dr(i)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;nt[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}},I=new Qa;var Zm=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let i=Math.random()*16|0;return(r=="x"?i:i&3|8).toString(16)})},ks=Zm;var za=class{constructor(){l(this,"_prefix","TRTC");l(this,"_queue",new Map);this.checkStorage()}getRealKey(i){return`${this._prefix}_${i}`}checkStorage(){if(!Kt())return;setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(t=>{if(t.startsWith(this._prefix)){let s=localStorage.getItem(t);if(!s)return!1;let o=JSON.parse(s);if(o&&o.expiresIn<Date.now())return!0}return!1}).forEach(t=>localStorage.removeItem(t))}doFlush(){if(!!Kt())try{for(let[i,e]of this._queue)localStorage.setItem(i,JSON.stringify(e))}catch(i){I.warn(i)}}getItem(i){if(!Kt())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){I.warn(e)}}setItem(i,e){if(!!Kt())try{let t={expiresIn:Date.now()+Ro,value:e};this._queue.set(this.getRealKey(i),t)}catch(t){I.warn(t)}}deleteItem(i){if(!Kt())return!1;try{return i=this.getRealKey(i),this._queue.delete(i),localStorage.removeItem(i),!0}catch(e){return I.warn(e),!1}}clear(){if(!!Kt())try{localStorage.clear()}catch(i){I.warn(i)}}},tn=new za;var Et={};es(Et,{HTTPS_API:()=>mp,IS_GET_CAPABILITIES_SUPPORTED:()=>rc,IS_GET_SETTINGS_SUPPORTED:()=>Pt,IS_INSERTABLE_STREAM_SUPPORTED:()=>kr,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>Ni,IS_SEI_SUPPORTED:()=>Gi,IS_SPC_SUPPORTED:()=>Mr,basis:()=>Ep,checkSystemRequirementsInternal:()=>nn,decodeSupportStatus:()=>on,encodeSupportStatus:()=>ec,getBrowserInfo:()=>dp,getDisplayResolution:()=>Ll,isAddTransceiverSupported:()=>tt,isBrowserSupported:()=>tc,isGetReceiversSupported:()=>Hi,isGetSendersSupported:()=>bi,isGetTransceiversSupported:()=>xt,isGetUserMediaSupported:()=>xl,isMediaDevicesSupported:()=>sn,isMediaSessionSupported:()=>Vl,isMediaStreamTrackProcessorSupported:()=>lp,isReplaceTrackSupported:()=>ic,isSIMDSupported:()=>fp,isScreenCaptureApiAvailable:()=>xs,isSelectedCandidatePair:()=>yi,isSetParametersSupported:()=>ws,isSmallStreamAPISupported:()=>wl,isSmallStreamSupported:()=>Ps,isStopTransceiverSupported:()=>_p,isTRTCSupported:()=>up,isUnifiedPlanDefault:()=>pp,isUsedInHttpProtocol:()=>ri,isWebAudioSupported:()=>Pl,isWebCodecSupported:()=>an,isWebCodecsSupported:()=>kl,isWebRTCSupported:()=>sc,isWebTransportSupported:()=>Ul});var Za=Se(Ol(),1);var Y={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},cp=new Map([[ie,["Firefox",ko]],[fr,["Edg",xo]],[Ar,["Chrome",Qo]],[Ue,["Safari",Si]],[ht,["TBS",Vo]],[ps,["XWEB",Uo]],[Er&&$i,["WeChat",Bo]],[_s,["QQ(Win)",$o]],[Tr,["QQ(Mobile)",pr]],[gr,["QQ(Mobile X5)",pr]],[fs,["QQ(Mac)",Fo]],[Es,["QQ(iPad)",Ho]],[gs,["MI",Wo]],[Ts,["HW",Jo]],[Ss,["Samsung",jo]],[Sr,["OPPO",qo]],[Ir,["VIVO",Xo]],[_r,["EDGE",Lo]],[hs,["SogouMobile",Po]],[ms,["Sogou",wo]]]);function dp(){let r=cp.get(!0),i=r?r[0]:"unknown",e=r?r[1]:"unknown";return{browserName:i,browserVersion:e}}var tc=function(){return!(ka||_r||fr&&Ma<80||ie&&Oa<56)},kl=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every(i=>i in window)},sn=function(){if(!navigator.mediaDevices)return ri()||I.error(Ae.NOT_SUPPORTED_MEDIA),!1;let r=["getUserMedia","enumerateDevices"];return r.filter(i=>i in navigator.mediaDevices).length===r.length},Ml=!1;function ri(){return location.protocol==="http:"&&!Yt?(Ml||I.error(L({key:M.NOT_SUPPORTED_HTTP})),Ml=!0,!0):!1}var lp=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},ec=function(){return _(this,null,function*(){if(Y.detail.isH264EncodeSupported&&Y.detail.isVp8EncodeSupported)return{isH264EncodeSupported:Y.detail.isH264EncodeSupported,isVp8EncodeSupported:Y.detail.isVp8EncodeSupported};let r,i=!1,e=!1;try{let t=new RTCPeerConnection,s=document.createElement(h.CANVAS);s.getContext("2d");let o=s.captureStream(0);return t.addTrack(o.getVideoTracks()[0],o),r=yield t.createOffer(),r.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),r.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),t.close(),Y.detail.isH264EncodeSupported=i,Y.detail.isVp8EncodeSupported=e,{isH264EncodeSupported:Y.detail.isH264EncodeSupported,isVp8EncodeSupported:Y.detail.isVp8EncodeSupported}}catch(t){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}})},on=function(){return _(this,null,function*(){if(Y.detail.isH264DecodeSupported&&Y.detail.isVp8DecodeSupported)return{isH264DecodeSupported:Y.detail.isH264DecodeSupported,isVp8DecodeSupported:Y.detail.isVp8DecodeSupported};let r,i=!1,e=!1;try{let t=new RTCPeerConnection;return r=yield t.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),r.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),r.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),t.close(),{isH264DecodeSupported:i,isVp8DecodeSupported:e}}catch(t){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}})},nn=Xa(()=>_(void 0,null,function*(){if(Y.result&&Y.detail.isH264EncodeSupported&&Y.detail.isVp8EncodeSupported&&Y.detail.isH264DecodeSupported&&Y.detail.isVp8DecodeSupported)return Y;let r=tc(),i=sc(),e=kl(),t=sn(),{isH264EncodeSupported:s,isVp8EncodeSupported:o}=yield ec(),{isH264DecodeSupported:n,isVp8DecodeSupported:a}=yield on();if(!s||!o){let c=yield ec();I.warn(`detect encode again h264:${s} vp8:${o} result: ${JSON.stringify(c)}`),s=c.isH264EncodeSupported,o=c.isVp8EncodeSupported}if(s&&n&&(Sr||Ir||xa)&&!ht&&zt()<79){let{encode:c,decode:d}=yield hp();s=c,n=d}return Y.result=r&&i&&t&&(s||o)&&(n||a),Y.detail.isBrowserSupported=r,Y.detail.isWebRTCSupported=i,Y.detail.isWebCodecsSupported=e,Y.detail.isMediaDevicesSupported=t,Y.detail.isScreenShareSupported=xs(),Y.detail.isSmallStreamSupported=Ps(),Y.detail.isH264EncodeSupported=s,Y.detail.isVp8EncodeSupported=o,Y.detail.isH264DecodeSupported=n,Y.detail.isVp8DecodeSupported=a,Y.result||I.error(`${navigator.userAgent} ${Ja(Y.detail,!1)}`),gp(),Y})),up=function(){return Y.result},xs=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},rn=null;function hp(){return _(this,null,function*(){return rn||(rn=new Promise(r=>_(this,null,function*(){let i={encode:!1,decode:!1},e=()=>{};try{I.warn("detectH264Supported start");let t=document.createElement("canvas"),s=t.getContext("2d");t.width=320,t.height=240;let o=setInterval(()=>{s.fillText("test",Math.floor(Math.random()*320),Math.floor(Math.random()*240))},66),n=-1,a=-1;e=()=>{clearInterval(n),clearInterval(o),clearTimeout(a),d.close(),u.close(),c.getTracks().forEach(C=>C.stop())},a=setTimeout(()=>{e(),r(i)},2*1e3);let c=t.captureStream(),d=new RTCPeerConnection({}),u=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});d.addEventListener("icecandidate",C=>u.addIceCandidate(C.candidate)),u.addEventListener("icecandidate",C=>d.addIceCandidate(C.candidate)),d.addTrack(c.getVideoTracks()[0],c);let p=yield d.createOffer();yield d.setLocalDescription(p),yield u.setRemoteDescription(p);let m=yield u.createAnswer(),f=Za.default.parse(m.sdp),R=f.media[0].rtp.findIndex(C=>C.codec==="H264");f.media[0].rtp=[f.media[0].rtp[R]],f.media[0].fmtp=f.media[0].fmtp.filter(C=>C.payload===f.media[0].rtp[0].payload),f.media[0].rtcpFb&&(f.media[0].rtcpFb=f.media[0].rtcpFb.filter(C=>C.payload===f.media[0].rtp[0].payload)),m.sdp=Za.default.write(f),yield u.setLocalDescription(m),yield d.setRemoteDescription(m),n=setInterval(()=>_(this,null,function*(){i.encode&&i.decode&&(e(),r(i));let C=yield d.getSenders()[0].getStats(),v=yield u.getReceivers()[0].getStats();i.encode||C.forEach(U=>{U.type==="outbound-rtp"&&U.mediaType===h.VIDEO&&U.bytesSent>0&&(i.encode=!0)}),i.decode||v.forEach(U=>{U.type==="inbound-rtp"&&U.mediaType===h.VIDEO&&U.bytesReceived>0&&(i.decode=!0)})}),100)}catch(t){e(),I.warn(t),r(i)}})).then(r=>((!r.encode||!r.decode)&&I.warn(`detectH264Supported encode: ${r.encode} decode: ${r.decode} ${lt}`),r)),rn)})}var mp=(r,i,e)=>{location.protocol==="http:"&&!Yt&&(r[i]=()=>{throw new b({code:A.INVALID_OPERATION,message:Ae.NOT_SUPPORTED_HTTP})})},yi=function(r){return r.type==="candidate-pair"&&r.nominated&&(r.state==="in-progress"||r.state==="succeeded")?!(de(r.selected)&&!r.selected):!1};function Ll(){let r="";if(screen.width){let i=screen.width?screen.width*window.devicePixelRatio:"",e=screen.height?screen.height*window.devicePixelRatio:"";r+=`${i} * ${e}`}return r}function xl(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function Pl(){let r={isSupported:!1},i=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let e=0;e<i.length;e++)if(i[e]in window){r.isSupported=!0;break}return r.isSupported}function wl(){return"captureStream"in HTMLCanvasElement.prototype}function Ps(){return Er||We||mt&&mt<63?!1:!!(tc()&&wl())}var pp=function(){if(T(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let r=null,i=!1;try{r=new RTCPeerConnection({sdpSemantics:fi}),r.addTransceiver(h.AUDIO),i=!0}catch(e){}return r==null||r.close(),i};function Hi(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function bi(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function xt(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function tt(){return Is===11?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var Mr=(()=>!(!tt()||Pe&&mt<86))();function _p(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}function ic(){return"RTCRtpSender"in window&&"replaceTrack"in window.RTCRtpSender.prototype}function ws(){return"RTCRtpSender"in window&&"setParameters"in window.RTCRtpSender.prototype&&bi()}var Pt=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,rc=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,kr="createEncodedStreams"in window.RTCRtpSender.prototype&&zt()>=86,Ni="RTCRtpScriptTransform"in window,Gi="RTCRtpSender"in window&&(kr||Ni),sc=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(i=>i in window).length>0};function an(){let r={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return T(window.AudioDecoder)||(r.AudioDecoder=!0),T(window.AudioEncoder)||(r.AudioEncoder=!0),T(window.VideoDecoder)||(r.VideoDecoder=!0),T(window.VideoEncoder)||(r.VideoEncoder=!0),T(window.ImageDecoder)||(r.ImageDecoder=!0),r}function Vl(){return"mediaSession"in navigator&&!T(navigator.mediaSession.setActionHandler)}function Ul(){return!T(window.WebTransport)}function fp(){return typeof WebAssembly!="undefined"?!1:WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]))}function Ep(){let r={browser:`${yt.name}/${yt.version}`,os:zo(),displayResolution:Ll(),isScreenShareSupported:xs(),isWebRTCSupported:sc(),isGetUserMediaSupported:xl(),isWebAudioSupported:Pl(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:an(),isMediaSessionSupported:Vl(),isWebTransportSupported:Ul()};return navigator.userAgent.includes("miniProgram")&&(r.browser=`mini/${r.browser}`),r}var Bl="checkResult";function gp(){tn.setItem(Bl,{ua:navigator.userAgent,checkResult:Y})}(function(){ri();let i=tn.getItem(Bl);i&&i.ua===navigator.userAgent&&(Y=i.checkResult),nn()})();var Fl=Se(Ne(),1);var $l=Symbol("instance"),UE=Symbol("abortCtrl"),cn=Symbol("cacheResult"),Vs=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,$s.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},Us=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function Tp(r){return typeof r=="object"&&r&&"then"in r}var Bs=new Map;function le(r,i,e={}){return(t,s,o)=>{let n=e.action||s;if(!e.context){let c=Bs.get(t)||[];Bs.has(t)||Bs.set(t,c),c.push({from:r,to:i,action:n})}let a=o.value;o.value=function(...c){let d=this;if(e.context&&(d=F.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===i)return e.sync?d[cn]:Promise.resolve(d[cn]);d.state instanceof Vs&&d.state.action==e.abortAction&&d.state.abort(d);let u=null;Array.isArray(r)?r.length==0?d.state instanceof Vs&&d.state.abort(d):(typeof d.state!="string"||!r.includes(d.state))&&(u=new Us(d._state,`${d.name} ${n} to ${i} failed: current state ${d._state} not from ${r.join("|")}`)):r!==d.state&&(u=new Us(d._state,`${d.name} ${n} to ${i} failed: current state ${d._state} not from ${r}`));let p=v=>{if(e.fail&&e.fail.call(this,v),e.sync){if(e.ignoreError)return v;throw v}else return e.ignoreError?Promise.resolve(v):Promise.reject(v)};if(u)return p(u);let m=d.state,f=new Vs(m,i,n);$s.call(d,f);let R=v=>{var U;return d[cn]=v,f.aborted||($s.call(d,i),(U=e.success)===null||U===void 0||U.call(this,d[cn])),v},C=v=>{let U=v instanceof Error?v.message:String(v);return $s.call(d,m,v),p(new Us(d._state,`action '${n}' failed :${U}`,v instanceof Error?v:new Error(U)))};try{let v=a.apply(this,c);return Tp(v)?v.then(R).catch(C):e.sync?R(v):Promise.resolve(R(v))}catch(v){return C(v)}}}}var Sp=(()=>typeof window!="undefined"&&window.__AFSM__?(e,t)=>{window.dispatchEvent(new CustomEvent(e,{detail:t}))}:typeof importScripts!="undefined"?(e,t)=>{postMessage({type:e,payload:t})}:()=>{})();function $s(r,i){let e=this._state;this._state=r;let t=r.toString();r&&this.emit(t,e),this.emit(F.STATECHANGED,r,e,i),this.updateDevTools({value:r,old:e,err:i instanceof Error?i.message:String(i)})}var F=class extends Fl.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=F.INIT,i||(i=Date.now().toString(36)),t?Object.setPrototypeOf(this,t):t=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let s=t[$l];s?this.name=s.name+"-"+s.count++:t[$l]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=Bs.get(i)||[],t=new Set,s=[],o=[],n=new Set,a=Object.getPrototypeOf(i);Bs.has(a)&&(a.stateDiagram.forEach(d=>t.add(d)),a.allStates.forEach(d=>n.add(d))),e.forEach(({from:d,to:u,action:p})=>{typeof d=="string"?s.push({from:d,to:u,action:p}):d.length?d.forEach(m=>{s.push({from:m,to:u,action:p})}):o.push({to:u,action:p})}),s.forEach(({from:d,to:u,action:p})=>{n.add(d),n.add(u),n.add(p+"ing"),t.add(`${d} --> ${p}ing : ${p}`),t.add(`${p}ing --> ${u} : ${p} \u{1F7E2}`),t.add(`${p}ing --> ${d} : ${p} \u{1F534}`)}),o.forEach(({to:d,action:u})=>{t.add(`${u}ing --> ${d} : ${u} \u{1F7E2}`),n.forEach(p=>{p!==d&&t.add(`${p} --> ${u}ing : ${u}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:n}}),c}static get(i){let e;return typeof i=="string"?(e=F.instances.get(i),e||F.instances.set(i,e=new F(i,void 0,Object.create(F.prototype)))):(e=F.instances2.get(i),e||F.instances2.set(i,e=new F(i.constructor.name,void 0,Object.create(F.prototype)))),e}static getState(i){var e;return(e=F.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){Sp(F.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){$s.call(this,i)}};F.STATECHANGED="stateChanged";F.UPDATEAFSM="updateAFSM";F.INIT="[*]";F.ON="on";F.OFF="off";F.instances=new Map;F.instances2=new WeakMap;var Hl=(window==null?void 0:window.requestIdleCallback)||function(r){let i=Date.now();return setTimeout(()=>{r({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-i))}})},1e3)},Ip=(window==null?void 0:window.cancelIdleCallback)||function(r){clearTimeout(r)},Ap=(window==null?void 0:window.cancelAnimationFrame)||(window==null?void 0:window.mozCancelAnimationFrame),Fs=class{static generateTaskID(){return this.currentTaskID++}static run(i=gi,e,t){i===Bi?t=N({delay:2e3,count:0,backgroundTask:!0},t):i===Ei?t=N({delay:1e4,count:0},t):i===ls?t=N({fps:60,delay:16.6,count:0,backgroundTask:!0},t):t=N({delay:2e3,count:0,backgroundTask:!0},t),pt(e)&&(t=N(N({},t),e)),K(i)&&(e=i,i=gi);let s=N({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:i,callback:e},t);return this.taskMap.set(s.taskID,s),this[i](s),s.taskID}static interval(i){let e=()=>{i.callback(),i.loopCount+=1,this.isBreakLoop(i)};return i.intervalID=setInterval(e,i.delay)}static intervalInWorker(i){i.delay=(1e3/i.fps).toFixed(2);let e=new Worker(URL.createObjectURL(new Blob([`
|
|
16
16
|
let timerID = null;
|
|
17
17
|
self.onmessage = function (e) {
|
|
18
18
|
if (e.data === 'start') {
|
|
@@ -23,13 +23,13 @@ ${t.stack}`)),this.sendRequest(Si(this._configs.sdkAppId,li.LOG),s)}sendRequest(
|
|
|
23
23
|
clearInterval(timerID);
|
|
24
24
|
}
|
|
25
25
|
};
|
|
26
|
-
`],{type:"application/javascript"})));e.onmessage=t=>{t.data==="tick"&&(i.callback(),i.loopCount+=1,this.isBreakLoop(i)&&e.postMessage("stop"))},i.worker=e,e.postMessage("start")}static timeout(i){let e=()=>{if(i.callback(),i.loopCount+=1,!this.isBreakLoop(i))return i.timeoutID=setTimeout(e,i.delay)};return i.timeoutID=setTimeout(e,i.delay)}static ric(i){let e=x(),t,s=()=>{if(t=x()-e,t>=i.delay&&(e=x()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!this.isBreakLoop(i))return i.ricID=Fu(s,{timeout:i.delay})};return i.ricID=Fu(s,{timeout:i.delay})}static raf(i){i.delay=(1e3/i.fps).toFixed(2);let e=x(),t,s=()=>{if(document.hidden&&i.backgroundTask)return t=x()-e,e=x(),i.callback(),i.loopCount+=1,this.isBreakLoop(i)?void 0:i.timeoutID=setTimeout(s,i.delay-Math.floor(t%i.delay));if(t=x()-e,t>=i.delay&&(e=x()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!this.isBreakLoop(i))return i.rafID=requestAnimationFrame(s)};if(i.rafID=requestAnimationFrame(s),i.backgroundTask){let o=()=>{if(document.hidden){let n=x()-e;n>=i.delay?s():i.timeoutID=setTimeout(s,i.delay-n)}};document.addEventListener("visibilitychange",o),i.onVisibilitychange=o,document.hidden&&o()}return i.taskID}static hasTask(i){return this.taskMap.has(i)}static clearTask(i){if(!this.taskMap.has(i))return!0;let{intervalID:e,timeoutID:t,rafID:s,ricID:o,onVisibilitychange:n,worker:a}=this.taskMap.get(i);return a&&a.terminate(),e&&clearInterval(e),t&&clearTimeout(t),s&&Ap(s),o&&Ip(o),n&&document.removeEventListener("visibilitychange",n),this.taskMap.delete(i),!0}static isBreakLoop(i){return this.taskMap.has(i.taskID)?i.count!==0&&i.loopCount>=i.count?(this.clearTask(i.taskID),!0):!1:!0}};$s.taskMap=new Map,$s.currentTaskID=1;var re=$s;var JE={STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",STREAM_UPDATED:"stream-updated",STREAM_SUBSCRIBED:"stream-subscribed",CONNECTION_STATE_CHANGED:"connection-state-changed",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",MUTE_AUDIO:"mute-audio",MUTE_VIDEO:"mute-video",UNMUTE_AUDIO:"unmute-audio",UNMUTE_VIDEO:"unmute-video",CLIENT_BANNED:"client-banned",NETWORK_QUALITY:"network-quality",AUDIO_VOLUME:"audio-volume",SEI_MESSAGE:h.SEI_MESSAGE,ERROR:"error"};var ve={LOADED_DATA:h.LOADEDDATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error"};var Pt={};Zr(Pt,{create:()=>De,remove:()=>me});var Fs=new WeakMap;function De(r,i){Fs.has(r)||Fs.set(r,[]);let e=Fs.get(r),s={add:(o,n)=>("addEventListener"in i?(e.push(i.removeEventListener.bind(i,o,n)),i.addEventListener(o,n)):(e.push(i.off.bind(i,o,n)),i.on(o,n)),s)};return s}function me(r){let i=Fs.get(r);i&&(i.forEach(e=>e()),Fs.delete(r))}var wt=new WeakMap;function it({settings:r={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(s,o,n){let a=vt({retryFunction:n.value,settings:r,onError({error:c,retry:d,reject:l,retryFuncArgs:p}){var m;i?i.call(this,c,()=>{var f;(f=wt.get(s))!=null&&f.has(o)?d():l(c)},l,p):(m=wt.get(s))!=null&&m.has(o)?d():l(c)},onRetrying(c,d){var l;W(e)&&e.call(this,c,d),(l=wt.get(s))!=null&&l.has(o)&&(wt.get(s).get(o).stopRetry=d)},onRetryFailed:t});return n.value=function(...c){let d=wt.get(s);return d?d.set(o,{args:c}):wt.set(s,new Map([[o,{args:c}]])),a.apply(this,c).finally(()=>{var l;return(l=wt.get(s))==null?void 0:l.delete(o)})},n}}function Hs({fnName:r,callback:i,validateArgs:e=!0}){return function(t,s,o){let n=o.value;return o.value=function(...a){var c,d;if((c=wt.get(t))!=null&&c.has(r)){let{stopRetry:l,args:p}=wt.get(t).get(r),m=!0;if(e){for(let f of p)if(!a.find(R=>R===f)){m=!1;break}}m&&(i&&i.apply(this,a),l&&l(),(d=wt.get(t))==null||d.delete(r))}return n.apply(this,a)},o}}var Cp=1,Rp=0,cn=class{constructor(i=!0){this.countMap=new Map;this.distributionMap=new Map;this.log=I.createLogger({id:"kv"});i&&(g.on("102",({track:e,cost:t})=>{this.addSuccessEvent({key:e.kind===h.AUDIO?dn.START_MICROPHONE:sc.START_CAMERA,cost:t})}),g.on("103",({track:e,error:t})=>{this.addFailedEvent({key:e.kind===h.AUDIO?dn.START_MICROPHONE:sc.START_CAMERA,error:t})}))}getReportData(){let i={msg_sdk_basic_info:{uint32_sdk_version:ja(this.version||Re),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(([e,t])=>({uint32_key:e,uint32_count:t})),stats_distribution:[...this.distributionMap.entries()].map(([e,t])=>({uint32_key:e,distribution_items:[...t.entries()].map(([s,o])=>({uint32_item_key:s,uint32_item_value:o}))}))};return this.countMap.clear(),this.distributionMap.clear(),i}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(i){let e=+String(i).slice(-3);return e>=700&&e<799}isErrorCodeKey(i){let e=+String(i).slice(-3);return e>=600&&e<699}isCountKey(i){let e=+String(i).slice(-3);return e>=0&&e<599}isNumberKey(i){let e=+String(i).slice(-3);return e>=800&&e<899}addCount({key:i,useUV:e=!1}){if(!this.isCountKey(i)){this.log.debug(`${i} is not count key, last 3 number should be 0~599`);return}e&&this.countMap.has(i)||this.countMap.set(i,(this.countMap.get(i)||0)+1)}addEnum({key:i,value:e,useUV:t=!0}){var o;if(!this.isEnumKey(i))return this.log.debug(`${i} is not enum key, last 3 number should be 700~799`);if(t&&this.countMap.has(i))return;this.countMap.set(i,(this.countMap.get(i)||0)+1);let s=((o=this.distributionMap)==null?void 0:o.get(i))||new Map;s.set(e,(s.get(e)||0)+1),this.distributionMap.set(i,s)}addNumber({key:i,value:e,split:t=100,useUV:s=!1}){var a;if(!this.isNumberKey(i))return this.log.debug(`${i} is not number key, last 3 number should be 800~899`);if(s&&this.countMap.has(i))return;this.countMap.set(i,(this.countMap.get(i)||0)+1);let o=((a=this.distributionMap)==null?void 0:a.get(i))||new Map,n=0;if(ee(t))n=Math.floor(e/t);else for(let c=t.length-1;c>0;c--)if(e>t[c]){n=c;break}o.set(n,(o.get(n)||0)+1),this.distributionMap.set(i,o)}addSuccessEvent({key:i,cost:e,timeKey:t,split:s}){if(!!i&&(this.addEnum({key:i,value:Cp,useUV:!1}),e)){let o=+String(i).slice(-3);o<800&&o>=700?this.addNumber({key:t||i+100,value:e,split:s}):t||this.log.debug(`time stat ignored, ${i}`)}}addFailedEvent({key:i,error:e}){if(!i)return;let t=A.UNKNOWN;e&&(ee(e)?t=e:(!T(e.extraCode)||!T(e.code))&&(t=e.extraCode||e.code)),this.addEnum({key:i,value:Rp,useUV:!1}),this.addEnum({key:i,value:t,useUV:!1})}},un=(G=>(G[G.enterRoom=500700]="enterRoom",G[G.exitRoom=500701]="exitRoom",G[G.switchRole=500702]="switchRole",G[G.destroy=500703]="destroy",G[G.startLocalAudio=500704]="startLocalAudio",G[G.updateLocalAudio=500705]="updateLocalAudio",G[G.stopLocalAudio=500706]="stopLocalAudio",G[G.startLocalVideo=500707]="startLocalVideo",G[G.updateLocalVideo=500708]="updateLocalVideo",G[G.stopLocalVideo=500709]="stopLocalVideo",G[G.startScreenShare=500710]="startScreenShare",G[G.updateScreenShare=500711]="updateScreenShare",G[G.stopScreenShare=500712]="stopScreenShare",G[G.startRemoteVideo=500713]="startRemoteVideo",G[G.updateRemoteVideo=500714]="updateRemoteVideo",G[G.stopRemoteVideo=500715]="stopRemoteVideo",G[G.muteRemoteAudio=500716]="muteRemoteAudio",G[G.setRemoteAudioVolume=500717]="setRemoteAudioVolume",G[G.use=500718]="use",G[G.sendSEIMessage=5e5]="sendSEIMessage",G[G.sendCustomMessage=500001]="sendCustomMessage",G))(un||{}),oc=(d=>(d[d.AudioMixer=550700]="AudioMixer",d[d.AIDenoiser=551700]="AIDenoiser",d[d.VirtualBackground=570700]="VirtualBackground",d[d.Beauty=571700]="Beauty",d[d.Watermark=572700]="Watermark",d[d.BasicBeauty=574700]="BasicBeauty",d[d.CDNStreaming=590700]="CDNStreaming",d[d.DeviceDetector=591700]="DeviceDetector",d[d.Debug=592700]="Debug",d))(oc||{}),nc=(d=>(d[d.AudioMixer=550701]="AudioMixer",d[d.AIDenoiser=551701]="AIDenoiser",d[d.VirtualBackground=570701]="VirtualBackground",d[d.Beauty=571701]="Beauty",d[d.Watermark=572701]="Watermark",d[d.BasicBeauty=574701]="BasicBeauty",d[d.CDNStreaming=590701]="CDNStreaming",d[d.DeviceDetector=591701]="DeviceDetector",d[d.Debug=592701]="Debug",d))(nc||{}),ac=(d=>(d[d.AudioMixer=550702]="AudioMixer",d[d.AIDenoiser=551702]="AIDenoiser",d[d.VirtualBackground=570702]="VirtualBackground",d[d.Beauty=571702]="Beauty",d[d.Watermark=572702]="Watermark",d[d.BasicBeauty=574702]="BasicBeauty",d[d.CDNStreaming=590702]="CDNStreaming",d[d.DeviceDetector=591702]="DeviceDetector",d[d.Debug=592702]="Debug",d))(ac||{});var dn=(t=>(t[t.START_MICROPHONE=501700]="START_MICROPHONE",t[t.MICROPHONE_CAHNNELS=501701]="MICROPHONE_CAHNNELS",t[t.MICROPHONE_SAMPLERATE=501702]="MICROPHONE_SAMPLERATE",t))(dn||{});var sc=(i=>(i[i.START_CAMERA=511700]="START_CAMERA",i))(sc||{});var yp=new cn(!0),Hi=new cn(!1);var D=yp;var Vt=class extends F{constructor(e,t){super(e.id,`${t}-player`);this.kind=t;u(this,"id");u(this,"element",null);u(this,"track");u(this,"url");u(this,"attr");u(this,"muted");u(this,"_log");u(this,"_pausedRetryCount");u(this,"_isElementPlayingFired",!1);u(this,"_interval");u(this,"_delayDestroyTimeoutId",0);u(this,"_isReplayByRecreateMediaStreamIng",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=Aa,this._state="STOPPED",this.bindTrackEvents(),this._log.info(`create ${t}-player ${this.id}`)}get isPlaying(){var e;return this._state==="PLAYING"&&((e=this.element)==null?void 0:e.paused)===!1}get isStopped(){return this._state==="STOPPED"}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,e!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return _(this,null,function*(){if(!this.isPlaying)try{this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield this.element.play()}catch(e){let t=L({key:M.PLAY_FAILED,data:{media:this.kind,error:e}});if(this.track&&!this.track.muted&&this._log.warn(e),t.includes("NotAllowedError"))throw new b({code:A.PLAY_NOT_ALLOWED,message:t})}})}stop(e=0){this._isElementPlayingFired=!1,this.unbindEvents(),e>0?this._delayDestroyTimeoutId||(this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(h.ENDED),this._interval>0&&re.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this.isPlaying&&((e=this.element)==null||e.pause())}resume(){return this._log.info("resume"),this.isPlaying?Promise.resolve():xa?this.replay():this.play().catch(()=>{})}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);return De(this.element,this.element).add(h.PLAYING,e).add(h.ENDED,e).add(h.PAUSE,e).add(h.ERROR,e).add(h.LOADEDDATA,e)}}bindTrackEvents(){if(this.track){let e=this.handleTrackEvent.bind(this);Pt==null||Pt.create(this.track,this.track).add(h.ENDED,e).add(h.MUTE,e).add(h.UNMUTE,e),this.track.readyState===h.ENDED&&this.handleTrackEvent({type:h.ENDED}),this.track.muted&&this.handleTrackEvent({type:h.MUTE})}}bindAutoPlayEvent(){g.on(E.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&me(this.track)}unbindEvents(){this.element&&me(this.element),this.unbindTrackEvents(),g.off(E.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case h.PLAYING:this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(h.PLAYING),this._interval&&(re.clearTask(this._interval),this._interval=-1);break;case h.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(h.ENDED);break;case h.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(h.PAUSE),We&&(this._interval=re.run(fi,()=>{this.element&&this._state==="PAUSED"&&this.resume()},{delay:3e3}));break;case h.ERROR:if(this.element&&this.element.error){this.handlePaused(h.ERROR);let{code:s,message:o}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${s} message: ${o} userAgent: ${navigator.userAgent}`),Z.uploadEvent({log:`stat-${this.kind}-${Ve.PLAYER_ERROR}-${s}-${navigator.userAgent}`,error:this.element.error}),this.replayByRecreateMediaStream()}break;case h.LOADEDDATA:this.kind===h.VIDEO&&this.emit(ve.LOADED_DATA);break}}replayByRecreateMediaStream(){if(!this._isReplayByRecreateMediaStreamIng)return this._isReplayByRecreateMediaStreamIng=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),Z.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),D.addSuccessEvent({key:this.kind===h.AUDIO?506700:516700})}).catch(()=>{var e,t;this._log.error("replayByRecreateMediaStream failed"),Z.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),D.addFailedEvent({key:this.kind===h.AUDIO?506700:516700,error:(e=this.element)==null?void 0:e.error}),(t=this.element)!=null&&t.error&&this.emit(ve.ERROR,this.element.error)}).finally(()=>{this._isReplayByRecreateMediaStreamIng=!1})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((t,s)=>{Zo(e).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var o,n,a;this._log.warn(`element onerror ${(n=(o=this.element)==null?void 0:o.error)==null?void 0:n.code} fired after recreated mediaStream`),s((a=this.element)==null?void 0:a.error)}),Zo(5e3).then(()=>{var o,n;(!this.isPlaying||((o=this.element)==null?void 0:o.error))&&s((n=this.element)==null?void 0:n.error),t()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(e){switch(e.type){case h.ENDED:this.handleStopped(h.ENDED);break;case h.MUTE:this.handlePaused(h.MUTE);break;case h.UNMUTE:this._isElementPlayingFired&&this.handlePlaying(h.UNMUTE);break}}handlePlaying(e){this.emit(ve.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(ve.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(ve.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};y([it({settings:{retries:2,timeout:0},onError(r,i,e,t){t[0]=(t[0]||1e3)+1e3,i()}})],Vt.prototype,"doReplayByRecreateMediaStream",1),y([ue([],"PLAYING",{sync:!0})],Vt.prototype,"handlePlaying",1),y([ue("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],Vt.prototype,"handlePaused",1),y([ue([],"STOPPED",{sync:!0})],Vt.prototype,"handleStopped",1);var ri="trtc_autoplay",cc=`${ri}_mask`,Mr=`${ri}_wrapper`,Gu=`${ri}_header`,dc=`${ri}_content`,ln=`${ri}_action_wrapper`,uc=`${ri}_question`,lc=`${ri}_collapse`,hn=`${ri}_action_confirm`,Wu=`${ri}_detail`,Ju="#2473E8",mc="dialog",bp=`${mc}-show`,Np=`${mc}-1`,vp=`${mc}-2`,ju=!1,pc=()=>!!document.querySelector(`.${Mr}`),Xu=`${Ct}/${Nt()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,qu=`<br><a href='${Xu}' target='_blank'>${Nt()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,Dp=`${Nt()?`\u6D4F\u89C8\u5668\u81EA\u52A8\u64AD\u653E\u7B56\u7565\uFF1A\u5728\u7528\u6237\u4E0E\u9875\u9762\u4EA7\u751F\u4EA4\u4E92\uFF08\u70B9\u51FB\u3001\u89E6\u6478\uFF09\u4E4B\u524D\uFF0C\u6D4F\u89C8\u5668\u7981\u6B62\u64AD\u653E\u6709\u58F0\u5A92\u4F53\u3002\u8BE5\u5F39\u7A97\u7528\u4E8E\u5E2E\u52A9\u7528\u6237\u6062\u590D\u97F3\u89C6\u9891\u64AD\u653E\u3002${qu}`:`Autoplay Policy: Before user interacts with the web page (clicking, touching), page will not be allowed to play media with sound. This Dialog is used to help users resume playback. ${qu}`}`,hc=class{constructor(){u(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");u(this,"_dialogNode",null);u(this,"_bodyPosition","");u(this,"_showDetail",!1);u(this,"_isCollapseClicked",!1);u(this,"_isQuestionClicked",!1);if(Nt()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!ju){let i=document.createElement("style");i.innerHTML=`.${cc}{position:fixed;top:0;left:0;right:0;bottom:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center;background:rgba(0,0,0,0.5);z-index:1500;}.${cc} div:not(.${ln}){display:block !important;}.${Mr}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${Mr} a{color:${Ju};}.${Gu}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${dc}{margin:8px 0;}.${ln}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${lc}{margin-right:auto;cursor:pointer}.${uc}{height:100%;line-height:16px;cursor:pointer;}.${hn}{margin-left:8px;color:#fff;background:${Ju};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${hn}:hover{opacity:0.9;}.${lc},.${hn},.${dc},.${uc}{font-size:14px;}@media screen and (max-width:750px){.${Mr}{width:80vw;}}`,document.head.appendChild(i),ju=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${cc}"><div class='${Mr}'><div class='${Gu}'>${location.host}</div><div class='${dc}'>${this.content}</div><div class='${Wu}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${Dp}</div><div class='${ln}'></div></div></div>`.trim();let e=document.createElement("button");e.className=hn,e.innerText=Nt()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let t=document.createElement("div");t.className=uc,t.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
|
|
26
|
+
`],{type:"application/javascript"})));e.onmessage=t=>{t.data==="tick"&&(i.callback(),i.loopCount+=1,this.isBreakLoop(i)&&e.postMessage("stop"))},i.worker=e,e.postMessage("start")}static timeout(i){let e=()=>{if(i.callback(),i.loopCount+=1,!this.isBreakLoop(i))return i.timeoutID=setTimeout(e,i.delay)};return i.timeoutID=setTimeout(e,i.delay)}static ric(i){let e=x(),t,s=()=>{if(t=x()-e,t>=i.delay&&(e=x()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!this.isBreakLoop(i))return i.ricID=Hl(s,{timeout:i.delay})};return i.ricID=Hl(s,{timeout:i.delay})}static raf(i){i.delay=(1e3/i.fps).toFixed(2);let e=x(),t,s=()=>{if(document.hidden&&i.backgroundTask)return t=x()-e,e=x(),i.callback(),i.loopCount+=1,this.isBreakLoop(i)?void 0:i.timeoutID=setTimeout(s,i.delay-Math.floor(t%i.delay));if(t=x()-e,t>=i.delay&&(e=x()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!this.isBreakLoop(i))return i.rafID=requestAnimationFrame(s)};if(i.rafID=requestAnimationFrame(s),i.backgroundTask){let o=()=>{if(document.hidden){let n=x()-e;n>=i.delay?s():i.timeoutID=setTimeout(s,i.delay-n)}};document.addEventListener("visibilitychange",o),i.onVisibilitychange=o,document.hidden&&o()}return i.taskID}static hasTask(i){return this.taskMap.has(i)}static clearTask(i){if(!this.taskMap.has(i))return!0;let{intervalID:e,timeoutID:t,rafID:s,ricID:o,onVisibilitychange:n,worker:a}=this.taskMap.get(i);return a&&a.terminate(),e&&clearInterval(e),t&&clearTimeout(t),s&&Ap(s),o&&Ip(o),n&&document.removeEventListener("visibilitychange",n),this.taskMap.delete(i),!0}static isBreakLoop(i){return this.taskMap.has(i.taskID)?i.count!==0&&i.loopCount>=i.count?(this.clearTask(i.taskID),!0):!1:!0}};Fs.taskMap=new Map,Fs.currentTaskID=1;var re=Fs;var WE={STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",STREAM_UPDATED:"stream-updated",STREAM_SUBSCRIBED:"stream-subscribed",CONNECTION_STATE_CHANGED:"connection-state-changed",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",MUTE_AUDIO:"mute-audio",MUTE_VIDEO:"mute-video",UNMUTE_AUDIO:"unmute-audio",UNMUTE_VIDEO:"unmute-video",CLIENT_BANNED:"client-banned",NETWORK_QUALITY:"network-quality",AUDIO_VOLUME:"audio-volume",SEI_MESSAGE:h.SEI_MESSAGE,ERROR:"error"};var ve={LOADED_DATA:h.LOADEDDATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error"};var wt={};es(wt,{create:()=>De,remove:()=>me});var Hs=new WeakMap;function De(r,i){Hs.has(r)||Hs.set(r,[]);let e=Hs.get(r),s={add:(o,n)=>("addEventListener"in i?(e.push(i.removeEventListener.bind(i,o,n)),i.addEventListener(o,n)):(e.push(i.off.bind(i,o,n)),i.on(o,n)),s)};return s}function me(r){let i=Hs.get(r);i&&(i.forEach(e=>e()),Hs.delete(r))}var Vt=new WeakMap;function it({settings:r={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(s,o,n){let a=Dt({retryFunction:n.value,settings:r,onError({error:c,retry:d,reject:u,retryFuncArgs:p}){var m;i?i.call(this,c,()=>{var f;(f=Vt.get(s))!=null&&f.has(o)?d():u(c)},u,p):(m=Vt.get(s))!=null&&m.has(o)?d():u(c)},onRetrying(c,d){var u;vt(e)&&e.call(this,c,d),(u=Vt.get(s))!=null&&u.has(o)&&(Vt.get(s).get(o).stopRetry=d)},onRetryFailed:t});return n.value=function(...c){let d=Vt.get(s);return d?d.set(o,{args:c}):Vt.set(s,new Map([[o,{args:c}]])),a.apply(this,c).finally(()=>{var u;return(u=Vt.get(s))==null?void 0:u.delete(o)})},n}}function Gs({fnName:r,callback:i,validateArgs:e=!0}){return function(t,s,o){let n=o.value;return o.value=function(...a){var c,d;if((c=Vt.get(t))!=null&&c.has(r)){let{stopRetry:u,args:p}=Vt.get(t).get(r),m=!0;if(e){for(let f of p)if(!a.find(R=>R===f)){m=!1;break}}m&&(i&&i.apply(this,a),u&&u(),(d=Vt.get(t))==null||d.delete(r))}return n.apply(this,a)},o}}var Cp=1,Rp=0,dn=class{constructor(i=!0){this.countMap=new Map;this.distributionMap=new Map;this.log=I.createLogger({id:"kv"});i&&(g.on("102",({track:e,cost:t})=>{this.addSuccessEvent({key:e.kind===h.AUDIO?ln.START_MICROPHONE:oc.START_CAMERA,cost:t})}),g.on("103",({track:e,error:t})=>{this.addFailedEvent({key:e.kind===h.AUDIO?ln.START_MICROPHONE:oc.START_CAMERA,error:t})}))}getReportData(){let i={msg_sdk_basic_info:{uint32_sdk_version:qa(this.version||Re),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(([e,t])=>({uint32_key:e,uint32_count:t})),stats_distribution:[...this.distributionMap.entries()].map(([e,t])=>({uint32_key:e,distribution_items:[...t.entries()].map(([s,o])=>({uint32_item_key:s,uint32_item_value:o}))}))};return this.countMap.clear(),this.distributionMap.clear(),i}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(i){let e=+String(i).slice(-3);return e>=700&&e<799}isErrorCodeKey(i){let e=+String(i).slice(-3);return e>=600&&e<699}isCountKey(i){let e=+String(i).slice(-3);return e>=0&&e<599}isNumberKey(i){let e=+String(i).slice(-3);return e>=800&&e<899}addCount({key:i,useUV:e=!1}){if(!this.isCountKey(i)){this.log.debug(`${i} is not count key, last 3 number should be 0~599`);return}e&&this.countMap.has(i)||this.countMap.set(i,(this.countMap.get(i)||0)+1)}addEnum({key:i,value:e,useUV:t=!0}){var o;if(!this.isEnumKey(i))return this.log.debug(`${i} is not enum key, last 3 number should be 700~799`);if(t&&this.countMap.has(i))return;this.countMap.set(i,(this.countMap.get(i)||0)+1);let s=((o=this.distributionMap)==null?void 0:o.get(i))||new Map;s.set(e,(s.get(e)||0)+1),this.distributionMap.set(i,s)}addNumber({key:i,value:e,split:t=100,useUV:s=!1}){var a;if(!this.isNumberKey(i))return this.log.debug(`${i} is not number key, last 3 number should be 800~899`);if(s&&this.countMap.has(i))return;this.countMap.set(i,(this.countMap.get(i)||0)+1);let o=((a=this.distributionMap)==null?void 0:a.get(i))||new Map,n=0;if(ee(t))n=Math.floor(e/t);else for(let c=t.length-1;c>0;c--)if(e>t[c]){n=c;break}o.set(n,(o.get(n)||0)+1),this.distributionMap.set(i,o)}addSuccessEvent({key:i,cost:e,timeKey:t,split:s}){if(!!i&&(this.addEnum({key:i,value:Cp,useUV:!1}),e)){let o=+String(i).slice(-3);o<800&&o>=700?this.addNumber({key:t||i+100,value:e,split:s}):t||this.log.debug(`time stat ignored, ${i}`)}}addFailedEvent({key:i,error:e}){if(!i)return;let t=A.UNKNOWN;e&&(ee(e)?t=e:(!T(e.extraCode)||!T(e.code))&&(t=e.extraCode||e.code)),this.addEnum({key:i,value:Rp,useUV:!1}),this.addEnum({key:i,value:t,useUV:!1})}},un=(G=>(G[G.enterRoom=500700]="enterRoom",G[G.exitRoom=500701]="exitRoom",G[G.switchRole=500702]="switchRole",G[G.destroy=500703]="destroy",G[G.startLocalAudio=500704]="startLocalAudio",G[G.updateLocalAudio=500705]="updateLocalAudio",G[G.stopLocalAudio=500706]="stopLocalAudio",G[G.startLocalVideo=500707]="startLocalVideo",G[G.updateLocalVideo=500708]="updateLocalVideo",G[G.stopLocalVideo=500709]="stopLocalVideo",G[G.startScreenShare=500710]="startScreenShare",G[G.updateScreenShare=500711]="updateScreenShare",G[G.stopScreenShare=500712]="stopScreenShare",G[G.startRemoteVideo=500713]="startRemoteVideo",G[G.updateRemoteVideo=500714]="updateRemoteVideo",G[G.stopRemoteVideo=500715]="stopRemoteVideo",G[G.muteRemoteAudio=500716]="muteRemoteAudio",G[G.setRemoteAudioVolume=500717]="setRemoteAudioVolume",G[G.use=500718]="use",G[G.sendSEIMessage=5e5]="sendSEIMessage",G[G.sendCustomMessage=500001]="sendCustomMessage",G))(un||{}),nc=(d=>(d[d.AudioMixer=550700]="AudioMixer",d[d.AIDenoiser=551700]="AIDenoiser",d[d.VirtualBackground=570700]="VirtualBackground",d[d.Beauty=571700]="Beauty",d[d.Watermark=572700]="Watermark",d[d.BasicBeauty=574700]="BasicBeauty",d[d.CDNStreaming=590700]="CDNStreaming",d[d.DeviceDetector=591700]="DeviceDetector",d[d.Debug=592700]="Debug",d))(nc||{}),ac=(d=>(d[d.AudioMixer=550701]="AudioMixer",d[d.AIDenoiser=551701]="AIDenoiser",d[d.VirtualBackground=570701]="VirtualBackground",d[d.Beauty=571701]="Beauty",d[d.Watermark=572701]="Watermark",d[d.BasicBeauty=574701]="BasicBeauty",d[d.CDNStreaming=590701]="CDNStreaming",d[d.DeviceDetector=591701]="DeviceDetector",d[d.Debug=592701]="Debug",d))(ac||{}),cc=(d=>(d[d.AudioMixer=550702]="AudioMixer",d[d.AIDenoiser=551702]="AIDenoiser",d[d.VirtualBackground=570702]="VirtualBackground",d[d.Beauty=571702]="Beauty",d[d.Watermark=572702]="Watermark",d[d.BasicBeauty=574702]="BasicBeauty",d[d.CDNStreaming=590702]="CDNStreaming",d[d.DeviceDetector=591702]="DeviceDetector",d[d.Debug=592702]="Debug",d))(cc||{});var ln=(t=>(t[t.START_MICROPHONE=501700]="START_MICROPHONE",t[t.MICROPHONE_CAHNNELS=501701]="MICROPHONE_CAHNNELS",t[t.MICROPHONE_SAMPLERATE=501702]="MICROPHONE_SAMPLERATE",t))(ln||{});var oc=(i=>(i[i.START_CAMERA=511700]="START_CAMERA",i))(oc||{});var yp=new dn(!0),Wi=new dn(!1);var D=yp;var Ut=class extends F{constructor(e,t){super(e.id,`${t}-player`);this.kind=t;l(this,"id");l(this,"element",null);l(this,"track");l(this,"url");l(this,"attr");l(this,"muted");l(this,"_log");l(this,"_pausedRetryCount");l(this,"_isElementPlayingFired",!1);l(this,"_interval");l(this,"_delayDestroyTimeoutId",0);l(this,"_isReplayByRecreateMediaStreamIng",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=Ca,this._state="STOPPED",this.bindTrackEvents(),this._log.info(`create ${t}-player ${this.id}`)}get isPlaying(){var e;return this._state==="PLAYING"&&((e=this.element)==null?void 0:e.paused)===!1}get isStopped(){return this._state==="STOPPED"}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,e!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return _(this,null,function*(){if(!this.isPlaying)try{this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield this.element.play()}catch(e){let t=L({key:M.PLAY_FAILED,data:{media:this.kind,error:e}});if(this.track&&!this.track.muted&&this._log.warn(e),t.includes("NotAllowedError"))throw new b({code:A.PLAY_NOT_ALLOWED,message:t})}})}stop(e=0){this._isElementPlayingFired=!1,this.unbindEvents(),e>0?this._delayDestroyTimeoutId||(this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(h.ENDED),this._interval>0&&re.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){var e;this.isPlaying&&((e=this.element)==null||e.pause())}resume(){return this._log.info("resume"),this.isPlaying?Promise.resolve():Pa?this.replay():this.play().catch(()=>{})}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){let e=this.handleElementEvent.bind(this);return De(this.element,this.element).add(h.PLAYING,e).add(h.ENDED,e).add(h.PAUSE,e).add(h.ERROR,e).add(h.LOADEDDATA,e)}}bindTrackEvents(){if(this.track){let e=this.handleTrackEvent.bind(this);wt==null||wt.create(this.track,this.track).add(h.ENDED,e).add(h.MUTE,e).add(h.UNMUTE,e),this.track.readyState===h.ENDED&&this.handleTrackEvent({type:h.ENDED}),this.track.muted&&this.handleTrackEvent({type:h.MUTE})}}bindAutoPlayEvent(){g.on(E.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&me(this.track)}unbindEvents(){this.element&&me(this.element),this.unbindTrackEvents(),g.off(E.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case h.PLAYING:this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(h.PLAYING),this._interval&&(re.clearTask(this._interval),this._interval=-1);break;case h.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(h.ENDED);break;case h.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(h.PAUSE),We&&(this._interval=re.run(gi,()=>{this.element&&this._state==="PAUSED"&&this.resume()},{delay:3e3}));break;case h.ERROR:if(this.element&&this.element.error){this.handlePaused(h.ERROR);let{code:s,message:o}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${s} message: ${o} userAgent: ${navigator.userAgent}`),Z.uploadEvent({log:`stat-${this.kind}-${Ve.PLAYER_ERROR}-${s}-${navigator.userAgent}`,error:this.element.error}),this.replayByRecreateMediaStream()}break;case h.LOADEDDATA:this.kind===h.VIDEO&&this.emit(ve.LOADED_DATA);break}}replayByRecreateMediaStream(){if(!this._isReplayByRecreateMediaStreamIng)return this._isReplayByRecreateMediaStreamIng=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),Z.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),D.addSuccessEvent({key:this.kind===h.AUDIO?506700:516700})}).catch(()=>{var e,t;this._log.error("replayByRecreateMediaStream failed"),Z.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),D.addFailedEvent({key:this.kind===h.AUDIO?506700:516700,error:(e=this.element)==null?void 0:e.error}),(t=this.element)!=null&&t.error&&this.emit(ve.ERROR,this.element.error)}).finally(()=>{this._isReplayByRecreateMediaStreamIng=!1})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((t,s)=>{en(e).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var o,n,a;this._log.warn(`element onerror ${(n=(o=this.element)==null?void 0:o.error)==null?void 0:n.code} fired after recreated mediaStream`),s((a=this.element)==null?void 0:a.error)}),en(5e3).then(()=>{var o,n;(!this.isPlaying||((o=this.element)==null?void 0:o.error))&&s((n=this.element)==null?void 0:n.error),t()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(e){switch(e.type){case h.ENDED:this.handleStopped(h.ENDED);break;case h.MUTE:this.handlePaused(h.MUTE);break;case h.UNMUTE:this._isElementPlayingFired&&this.handlePlaying(h.UNMUTE);break}}handlePlaying(e){this.emit(ve.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(ve.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(ve.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};y([it({settings:{retries:2,timeout:0},onError(r,i,e,t){t[0]=(t[0]||1e3)+1e3,i()}})],Ut.prototype,"doReplayByRecreateMediaStream",1),y([le([],"PLAYING",{sync:!0})],Ut.prototype,"handlePlaying",1),y([le("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],Ut.prototype,"handlePaused",1),y([le([],"STOPPED",{sync:!0})],Ut.prototype,"handleStopped",1);var si="trtc_autoplay",dc=`${si}_mask`,Lr=`${si}_wrapper`,Wl=`${si}_header`,lc=`${si}_content`,hn=`${si}_action_wrapper`,uc=`${si}_question`,hc=`${si}_collapse`,mn=`${si}_action_confirm`,Jl=`${si}_detail`,jl="#2473E8",pc="dialog",bp=`${pc}-show`,Np=`${pc}-1`,vp=`${pc}-2`,ql=!1,_c=()=>!!document.querySelector(`.${Lr}`),Ql=`${Ct}/${Nt()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,Xl=`<br><a href='${Ql}' target='_blank'>${Nt()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,Dp=`${Nt()?`\u6D4F\u89C8\u5668\u81EA\u52A8\u64AD\u653E\u7B56\u7565\uFF1A\u5728\u7528\u6237\u4E0E\u9875\u9762\u4EA7\u751F\u4EA4\u4E92\uFF08\u70B9\u51FB\u3001\u89E6\u6478\uFF09\u4E4B\u524D\uFF0C\u6D4F\u89C8\u5668\u7981\u6B62\u64AD\u653E\u6709\u58F0\u5A92\u4F53\u3002\u8BE5\u5F39\u7A97\u7528\u4E8E\u5E2E\u52A9\u7528\u6237\u6062\u590D\u97F3\u89C6\u9891\u64AD\u653E\u3002${Xl}`:`Autoplay Policy: Before user interacts with the web page (clicking, touching), page will not be allowed to play media with sound. This Dialog is used to help users resume playback. ${Xl}`}`,mc=class{constructor(){l(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");l(this,"_dialogNode",null);l(this,"_bodyPosition","");l(this,"_showDetail",!1);l(this,"_isCollapseClicked",!1);l(this,"_isQuestionClicked",!1);if(Nt()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!ql){let i=document.createElement("style");i.innerHTML=`.${dc}{position:fixed;top:0;left:0;right:0;bottom:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center;background:rgba(0,0,0,0.5);z-index:1500;}.${dc} div:not(.${hn}){display:block !important;}.${Lr}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${Lr} a{color:${jl};}.${Wl}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${lc}{margin:8px 0;}.${hn}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${hc}{margin-right:auto;cursor:pointer}.${uc}{height:100%;line-height:16px;cursor:pointer;}.${mn}{margin-left:8px;color:#fff;background:${jl};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${mn}:hover{opacity:0.9;}.${hc},.${mn},.${lc},.${uc}{font-size:14px;}@media screen and (max-width:750px){.${Lr}{width:80vw;}}`,document.head.appendChild(i),ql=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${dc}"><div class='${Lr}'><div class='${Wl}'>${location.host}</div><div class='${lc}'>${this.content}</div><div class='${Jl}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${Dp}</div><div class='${hn}'></div></div></div>`.trim();let e=document.createElement("button");e.className=mn,e.innerText=Nt()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let t=document.createElement("div");t.className=uc,t.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
|
|
27
27
|
<svg class="icon" width="18" height="18" p-id="2030" t="1639646523624" version="1.1" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
|
|
28
28
|
<path d="m464 784.35c0 26.51 21.49 48 48 48s48-21.49 48-48-21.49-48-48-48-48 21.49-48 48z" p-id="2031"/>
|
|
29
29
|
<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"/>
|
|
30
30
|
<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"/>
|
|
31
31
|
</svg>
|
|
32
|
-
`,t.onclick=this.onQuestionClick.bind(this);let s=document.createElement("div");s.className=
|
|
32
|
+
`,t.onclick=this.onQuestionClick.bind(this);let s=document.createElement("div");s.className=hc,s.innerText=`${Nt()?"\u8BE6\u60C5 >":"Detail >"}`,s.onclick=this.onCollapseClick.bind(this);let o=i.content.firstChild,n=o.querySelector(`.${hn}`);return n.appendChild(s),n.appendChild(t),n.appendChild(e),o}addDiaLog(){_c()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${Lr}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",I.info("show autoplay dialog"),Z.uploadEvent({log:bp}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){I.warn("confirm clicked, try resume stream"),g.emit(E.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${Jl}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||Z.uploadEvent({log:Np}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Ql,"_blank"),this._isQuestionClicked||Z.uploadEvent({log:vp}),this._isQuestionClicked=!0}},zl=mc;var je=class extends Ut{constructor(e){super(e,h.VIDEO);l(this,"viewMirror",!1);l(this,"objectFit");l(this,"container");l(this,"canvas");this.container=e.container,this.canvas=e.canvas,T(e.viewMirror)||(this.viewMirror=e.viewMirror),T(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}initializeElement(){var t;let e=document.createElement(h.VIDEO);this.track&&(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,(t=this.container)==null||t.appendChild(this.elementToRender),this.bindElementEvents()}get styleAttribute(){let e=`width: 100%; height: 100%; object-fit: ${this.objectFit};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(h.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(h.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleElementEvent(e){var s;super.handleElementEvent(e);let t=e.type;if(t===h.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn(`${this.kind} player has been remove, element ID: ${(s=this.container)==null?void 0:s.id}`),this._pausedRetryCount>0&&!_c()&&(this._log.info(`${this.kind} player auto resume when paused`),this.resume(),this._pausedRetryCount--)),this.viewMirror&&this.element){let o=this.element.style.transform;t===h.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=o.replace("scaleX(-1)",""):t===h.LEAVE_PICTURE_IN_PICTURE&&!o.includes("scaleX")&&(this.element.style.transform=`${o} scaleX(-1)`)}}setCanvas(e){var t,s;this.canvas!==e&&((t=this.canvas)==null||t.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,e&&((s=this.container)==null||s.appendChild(e)))}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}stop(e=0){var t;super.stop(e),(t=this.canvas)==null||t.remove()}play(){return this.element?this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender):this.initializeElement(),super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(ve.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&(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}};function Ji(r,i){return _(this,null,function*(){if(!r.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield r.audioWorklet.addModule(i),I.info("worklet addModule success")}catch(e){throw I.info(`worklet addModule catch error. ${e.message}`),e}})}typeof window!="undefined"&&(window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext);var ji=new window.AudioContext({sampleRate:48e3}),pn=()=>{ji.state==="suspended"?(ji.resume(),document.addEventListener("click",pn)):ji.state==="interrupted"?ji.resume():document.removeEventListener("click",pn)};document.addEventListener("click",pn);ji.onstatechange=()=>{I.info(`context state: ${ji.state}`),pn()};var qe=r=>ji;var gt=class{constructor(){this.pre=new Set;this.next=new Set;this.connectedNodes=new Set;this._channelCount=1}get channelCount(){return this._channelCount}set channelCount(i){this._channelCount=i,this.node&&(this.node.channelCount=i),this.next.forEach(e=>e.channelCount=i)}setContext(i){this.context=i,this.node&&i.addMixWeight()}removeContext(){var i;this.node&&((i=this.context)==null||i.reduceMixWeight()),delete this.context}setNode(i){var e;if(!this.node)try{(e=this.context)==null||e.addMixWeight(),this.node=i,this.node.channelCountMode="explicit",this.node.channelCount=this._channelCount,this.preNodeReconnect(),this.reconnect(),D.addSuccessEvent({key:502701})}catch(t){I.error(t),D.addFailedEvent({key:502701,error:t})}}deleteNode(){var i;if(!!this.node)try{this._disconnect(),delete this.node,(i=this.context)==null||i.reduceMixWeight(),this.preNodeReconnect(),D.addSuccessEvent({key:502702})}catch(e){I.error(e),D.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(i=>{i.node?i.reconnect():i.preNodeReconnect()})}connectNext(i){this.next.forEach(e=>i._connect(e.node)||e.connectNext(i))}_connect(i){return!this.node||!i?!1:(this.node.connect(i),this.connectedNodes.add(i),!0)}_disconnect(){this.connectedNodes.forEach(i=>{var e;return(e=this.node)==null?void 0:e.disconnect(i)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(...i){return i.forEach(e=>{this.next.add(e),e.pre.add(this)}),this}},_n=class extends gt{constructor(e=256){super();this.fftSize=e;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,s=0,o=0,n=`M${s},${o}`;for(let a=0;a<e.length;a++)o=e[a]/128*100/2,n+=`L${s},${o}`,s+=t;return n}},Ws=class{constructor(){this.source=new gt;this.gain=new gt;this.destination=new gt}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(this.source.node.context.createGain()),this.gain.node.gain.value=i}replaceSource(i){this.source.deleteNode(),this.source.setNode(Op(i))}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}},xr=class extends Ws{constructor(e){super();this.context=e;this.denoiser=new gt;this.source.pipeTo(this.denoiser.pipeTo(this.gain.pipeTo(this.destination)))}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.denoiser.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.denoiser.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.denoiser.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}},fn=class{constructor(){this.audioContext=qe("audio-mixer");this.destination=this.audioContext.createMediaStreamDestination();this.inputs=new Set;this.mixWeight=0}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]}},Yl=new WeakMap;function Op(r){let i=Yl.get(r);if(i)return i;let e=qe();if(r instanceof HTMLAudioElement)i=e.createMediaElementSource(r);else if(r instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([r]));else return r;return Yl.set(r,i),i}var Mp=`
|
|
33
33
|
class VolumeMeter extends AudioWorkletProcessor{constructor(){super();this.volume=0;this.intervalTime=200;this.tick=this.intervalTime;this.isStop=false;this.cache=[];this.sentFirstInfo1=false;this.unmute=false;this.port.onmessage=(event)=>{const{data}=event;switch(data.name){case"chunk":this.cache.push.apply(this.cache,data.data);if(!this.sentFirstInfo1){this.port.postMessage({cl:data.data.length});this.sentFirstInfo1=true;}
|
|
34
34
|
break;case"setIntervalTime":this.intervalTime=data.intervalTime;break;case"unmute":this.unmute=true;break;case"stop":this.isStop=true;break;}};}
|
|
35
35
|
process(inputs,outputs){const input=inputs[0];const output=outputs[0];if(!input&&!output){return true;}
|
|
@@ -40,7 +40,7 @@ let sum=0;let rms;for(let i=0;i<firstChannel.length;++i){sum+=firstChannel[i]*fi
|
|
|
40
40
|
rms=Math.sqrt(sum/firstChannel.length);this.volume=Math.max(rms,this.volume*0.95);this.tick-=firstChannel.length;if(this.tick<0){this.tick+=(this.intervalTime/1000)*sampleRate;this.port.postMessage({volume:this.volume,cacheLen:cl,outputLen:l});}
|
|
41
41
|
return true;}}
|
|
42
42
|
registerProcessor("volume-meter",VolumeMeter);
|
|
43
|
-
`,Ji=class{constructor(i){u(this,"_volume",0);u(this,"_log");u(this,"_scriptProcessorNode",null);u(this,"_audioWorkletNode",null);u(this,"_interval",200);u(this,"ready",this.preload());let{log:e}=i;this._log=e,g.on(E.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){return Ji.workletReady||(Ji.workletReady=Gi(Ji.audioContext,URL.createObjectURL(new Blob([Mp],{type:"application/javascript"})))),Ji.workletReady.then(()=>this.initAudioWorklet()).catch(()=>this.initScriptProcessor())}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Ji.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{this._volume=e.data.volume||0,!i&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),i=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(i){Z.logFailedEvent({userId:this._log.userId,eventType:Ve.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=qe("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{let e=i.inputBuffer.getChannelData(0),t=0;for(let s=0;s<e.length;++s)t+=e[s]*e[s];this._volume=Math.sqrt(t/e.length)||0}}catch(i){this._log.error(`volumeMeter init script processor error: ${i}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,g.off(E.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}},Ws=Ji;u(Ws,"audioContext",qe("volume-meter")),u(Ws,"workletReady");var fn=class extends Et{constructor(e){super();u(this,"_volumeMeter");this._volumeMeter=new Ws(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return _(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),s=new Float32Array(t>>2);e.copyTo(s,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:s},[s.buffer]),e.close()}}};var el=Se(Ne(),1);var Ku=r=>i=>i.deviceId===r;var Js=class{constructor(i,e="Input"){u(this,"kind");u(this,"type");u(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(s=>s.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&Lr(this.devices[0])){this.devices=t;return}e&&(t.forEach(s=>{if(s.deviceId&&!this.devices.find(Ku(s.deviceId))){let o=`${this.kind}${this.type}Added`;I.warn(`${o}: ${JSON.stringify(s)}`),e.emit(o,s)}}),this.devices.forEach(s=>{if(s.deviceId&&!t.find(Ku(s.deviceId))){let o=`${this.kind}${this.type}Removed`;I.warn(`${o}: ${JSON.stringify(s)}`),e.emit(o,s)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},_c=class extends el.EventEmitter{constructor(){super();u(this,"audioInputs",new Js(h.AUDIO));u(this,"videoInputs",new Js(h.VIDEO));u(this,"audioOutputs",new Js(h.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||re.run(Vi,()=>{this.update()},{delay:1e4}))}init(){En().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return _(this,arguments,function*(e=0){let t=yield En(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}},ge=rs||cr?null:new _c;function Lr(r){return r.deviceId===r.groupId&&r.groupId===""}function En(){return _(this,arguments,function*(r=0){if(ii()||!rn())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(r!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{Lr(t)&&(t.kind===h.AUDIO_INPUT?e.audio=!0:t.kind===h.VIDEO_INPUT&&(e.video=!0))}),r===2&&(e.audio=!1),r===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e)}catch(s){I.debug("capture before getDevices failed: ",s)}i=yield navigator.mediaDevices.enumerateDevices(),t==null||t.getTracks().forEach(s=>s.stop())}}return i.map((e,t)=>{let s={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${t}`};return e.deviceId.length>0&&fc.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(s.getCapabilities=()=>e.getCapabilities()),s})})}function Be(r=!1){return ge.update(r?1:0).then(i=>i.audioInputs.devices)}function Xe(r=!1){return ge.update(r?2:0).then(i=>i.videoInputs.devices)}var Zu=!1;function tl(){return _(this,null,function*(){try{Zu||(Zu=!0,I.info(`speakers:${(yield ji()).map(r=>` ${r.deviceId.slice(0,8)}: ${r.label}`)}`))}catch(r){}})}function ji(r=!1){return _(this,null,function*(){return ge.update(r?1:0).then(i=>i.audioOutputs.devices)})}var fc=new Set;function il(r){if(r instanceof CanvasCaptureMediaStreamTrack||!(r instanceof MediaStreamTrack))return!1;let i=r.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let t=`${((r==null?void 0:r.getSettings())||{}).deviceId}_${h.VIDEO_INPUT}`;return!!fc.has(t)}function rl(r){if(r instanceof CanvasCaptureMediaStreamTrack||!(r instanceof MediaStreamTrack))return!1;let i=r.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("\u9EA6\u514B\u98CE"))return!0;let t=`${((r==null?void 0:r.getSettings())||{}).deviceId}_${h.AUDIO_INPUT}`;return!!fc.has(t)}function Ec(r,i){return _(this,null,function*(){let t=(yield Be()).find(s=>s.deviceId===wi);return(t==null?void 0:t.groupId)===r&&t.label===i})}function sl(o){return _(this,arguments,function*({newDeviceId:r,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:s}){return r!==i?!1:s===h.AUDIO&&r===wi?yield Ec(e,t):!0})}var gn,gc=class extends Gs{constructor(e){super();this.log=e;u(this,"volumeMeter");u(this,"volumeDestination");u(this,"analyser",new pn);this.volumeMeter=new fn({log:this.log}),this.volumeDestination=new Et,this.volumeMeter.pipeTo(this.volumeDestination)}destory(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},xr=class extends Vt{constructor(e){super(e,h.AUDIO);u(this,"_outputDeviceId");u(this,"_volume",1);u(this,"_destination",qe("player").createMediaStreamDestination());u(this,"pipeline");u(this,"volumeMeterMode","worklet");this.pipeline=new gc(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(){if((Ti==="15.2"||Ti==="15.3"||Ti==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let t=gn||new Audio;t.setAttribute("autoplay","autoplay"),t.srcObject=this.getMediaStream(),t.muted=this.muted,this.element=t,t===gn&&(gn=void 0),this.bindElementEvents()}play(){return _(this,null,function*(){if(!!this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?this.pipeline.volumeMeter.init():this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(qe("player").createAnalyser()),this.setVolume(this._volume),tl(),Ie(xr.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destory(),super.stop(e)}setSinkId(e){return _(this,null,function*(){var t,s;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(s=(t=this.element).setSinkId)==null?void 0:s.call(t,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){!this.element||(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}},Tn=class extends xr{constructor(i){super(i),this.pipeline.source.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination)}setTrack(i){var e;this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(ve.MEDIA_TRACK_CHANGED,i),i?(this.bindTrackEvents(),this.pipeline.source.channelCount=((e=i.getSettings())==null?void 0:e.channelCount)||1,this.pipeline.replaceSource(i),!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([i]))):this.pipeline.source.deleteNode())}setSourceNode(i){!i||this.pipeline.source.node===i||(this.pipeline.replaceSource(i),i instanceof MediaStreamAudioSourceNode?this.pipeline.destination.setNode(this._destination):this.pipeline.destination.deleteNode(),this.element&&(this.element.srcObject=this.getMediaStream(),this.element.play().catch(()=>{}),this.setVolume(this._volume)))}setVolume(i){this._volume=i,this.element&&(this.element.volume=i)}},Sn=class extends xr{constructor(e){super(e);u(this,"_sourceElement");this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination))}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,s,o;((s=(t=this.element)==null?void 0:t.error)==null?void 0:s.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(ve.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=((o=e.getSettings())==null?void 0:o.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`)):e<=1?(this.element?this._log.info(`set element volume: ${e}`):this._log.info("set element volume: no element"),this.element&&(this.element.volume=e)):(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),me(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(e=0){this.pipeline.destory();let t=this._sourceElement||this.element;t&&Ir&&(gn=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var qi=class extends F{constructor({userId:e,sdkAppId:t,mediaType:s,room:o,PlayerClass:n=s===1?Sn:je}){var a;super();u(this,"id",Ms());u(this,"userId","");u(this,"isRemote");u(this,"mediaType");u(this,"room");u(this,"user");u(this,"_log");u(this,"_inputTrack");u(this,"_outputTrack");u(this,"isPlayCalled");u(this,"container",null);u(this,"player");u(this,"subVideoPlayerMap");u(this,"muted",!1);u(this,"abortCtrl");u(this,"objectFit","cover");u(this,"mirror");u(this,"isScreen",!1);u(this,"manager");u(this,"trackSettings");u(this,"onPlayerError");this.userId=e||"",this.mediaType=s,this._log=I.createLogger({id:`${this.kind[0]}t`,userId:(a=o||this.room)==null?void 0:a.userId,remoteUserId:this instanceof Qe?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof Qe}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(ve.PLAYER_STATE_CHANGED,c=>{g.emit(E.PLAYER_STATE_CHANGED,N({track:this},c)),this.emit("player-state-changed",c)}),this.kind===h.VIDEO&&(this.player.on(ve.LOADED_DATA,()=>{g.emit(E.VIDEO_LOADED_DATA,{track:this})}),this.player.on(ve.MEDIA_TRACK_CHANGED,c=>{var d;(d=this.subVideoPlayerMap)==null||d.forEach(l=>l.setTrack(c))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(ve.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||I}get kind(){return this.mediaType===1?h.AUDIO:h.VIDEO}get strMediaType(){return this.mediaType===4?h.VIDEO:this.mediaType===2?h.SCREEN:h.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}get isMediaTrackActive(){return this.mediaTrack?!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled:!1}play(e,t){return _(this,null,function*(){let s=he(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 je&&(this.player.setObjectFit(this.objectFit),this.container!==s&&s&&(this.container=s,this.player.setContainer(s)),he(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===h.VIDEO)&&this.setPlayerMute(!0),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof je&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,s&&(this.container=s,this.player instanceof je&&this.player.setContainer(s)),g.emit(E.PLAY_TRACK_START,{track:this}),!this._outputTrack){this.log.info("play has not mediaTrack, abort");return}this._log.info(`play with options: ${JSON.stringify(t)}`);try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(),he(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(o){throw this.handleAutoPlayFailed(),this.emit("error",o),o}})}setMirror(e,t){if(this.isScreen||this.kind!==h.VIDEO||T(e)||e===this.mirror)return;this.mirror=e;let s=this.player;t&&(s=t);let o=this.manager;if(de(this.mirror)){s.setViewMirror(this.mirror),o&&(o.mirror=!1);return}switch(this.mirror){case"view":{o&&(o.mirror=!1),s.setViewMirror(!0);break}case"publish":{o&&(o.mirror=!0),s.setViewMirror(!0);break}case"both":o&&(o.mirror=!0),s.setViewMirror(!1)}}playSubContainer(e,t){return _(this,null,function*(){if(!this._outputTrack||this.kind===h.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((o,n)=>{var a;e.find(c=>n===c)||(o.stop(),(a=this.subVideoPlayerMap)==null||a.delete(n))});for(let[o,n]of e.entries()){let a=this.subVideoPlayerMap.get(n);a?t&&(T(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new je({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${o+1}`})}))}let s=[...this.subVideoPlayerMap.values()];for(let o of s)o.setViewMirror(this.player.mirror),yield o.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(){!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(_t(this)?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(e=>{e.stop()}),this.container=null)}resume(){return _(this,null,function*(){var e;!this.isPlayCalled||(yield(e=this.player)==null?void 0:e.resume())})}close(){this.log.info("close"),this.isPlayCalled&&this.stop()}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),g.emit(e?E.TRACK_MUTED:E.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(e){De(e,e).add(h.MUTE,this.onTrackMuted).add(h.UNMUTE,this.onTrackUnmuted).add(h.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===h.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){me(e)}setInputMediaStreamTrack(e){var s;let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.trackSettings=(s=e.getSettings)==null?void 0:s.call(e),e.enabled=!this.muted,t&&this.uninstallTrackEvent(t),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,t||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var s;let t=this._outputTrack;e!==t&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(s=e.getSettings)==null?void 0:s.call(e).deviceId,e.label),this._outputTrack=e,this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(()=>this.handleAutoPlayFailed()),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(_t(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(){if(this.room&&this.room.enableAutoPlayDialog)new Qu;else{let e=()=>{this.resume().then(()=>{document.removeEventListener("click",e,!0)})};document.addEventListener("click",e,!0)}}getVideoFrame(){return this.player instanceof je?this.player.getVideoFrame():""}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};y([ue([],F.INIT,{sync:!0})],qi.prototype,"close",1);var kp=Object.prototype.hasOwnProperty,{toString:BT}=Object.prototype;function Lp(r){if(r==null)return!0;if(typeof r=="boolean")return!1;if(typeof r=="number")return r===0;if(typeof r=="string"||typeof r=="function"||Array.isArray(r))return r.length===0;if(r instanceof Error)return r.message==="";if(Je(r))switch(Object.prototype.toString.call(r)){case"[object File]":case"[object Map]":case"[object Set]":return r.size===0;case"[object Object]":{for(let i in r)if(kp.call(r,i))return!1;return!0}}return!1}var Bt=Lp;var xp=function(r){return _(this,null,function*(){let i=wp(r);I.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],s=["label","deviceId"];i.audio&&(e=yield Be(),I.info(`microphones: ${pt(e,{keysToInclude:s})}`)),i.video&&(t=yield Xe(),I.info(`cameras: ${pt(t,{keysToInclude:s})}`));try{let o=yield navigator.mediaDevices.getUserMedia(i);return ic&&o.getTracks().forEach(n=>{I.info(`${n.kind} capabilities: ${pt(n.getCapabilities(),{keysToInclude:Oo})}`)}),o}catch(o){let{message:n}=o;throw o.name==="NotFoundError"&&(r.video&&t&&t.length===0&&(n=L({key:M.CAMERA_NOT_FOUND})),r.audio&&e&&e.length===0&&(n=L({key:M.MICROPHONE_NOT_FOUND}))),new b({code:A.INITIALIZE_FAILED,name:o.name,message:n,constraint:o.constraint})}})},Pp=vt({retryFunction:xp,settings:{retries:3,timeout:500},onError:({error:r,retry:i,reject:e,retryFuncArgs:t,retriedCount:s})=>{let o=s+1;r.name==="NotReadableError"||r.name==="OverconstrainedError"?(o===1?t[0].video&&(t[0].maxResolution=!1,(!Ue||t[0].width*t[0].height<=1920*1080)&&t[0].frameRate&&(t[0].frameRate=t[0].frameRate>10?10:5)):o===2?t[0].useDeviceIdOnly=!0:o===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(r),t[0].microphoneId&&ol(t[0].microphoneId,!1),t[0].cameraId&&ol(t[0].cameraId,!0)},onRetrying:r=>{I.warn(`getUserMedia NotReadableError observed, retrying [${r}/3]`)},onRetryFailed:r=>{Z.logFailedEvent({eventType:Ve.GET_USER_MEDIA_RETRY,error:r})},onRetrySuccess:r=>{Z.logSuccessEvent({eventType:Ve.GET_USER_MEDIA_RETRY}),Z.uploadEvent({log:`stat-${Ve.GET_USER_MEDIA_RETRY}-success-${r}`})}});function ol(r,i){return _(this,null,function*(){let t=(i?yield Xe():yield Be()).find(s=>s.deviceId===r);t&&W(t.getCapabilities)&&I.warn(pt(t.getCapabilities(),{keysToInclude:Oo}))})}function wp(r){return{audio:Vp(r),video:Up(r)}}function Vp(r){if(!r.audio)return!1;if(r.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:r.sampleRate};return!Bt(r.microphoneId)&&(i.deviceId=r.useExactDeviceId?{exact:r.microphoneId}:r.microphoneId,r.useDeviceIdOnly)?i:(ee(r.channelCount)&&(i.channelCount=r.channelCount),de(r.echoCancellation)&&!r.echoCancellation&&(i.echoCancellation=!1),de(r.noiseSuppression)&&!r.noiseSuppression&&(i.noiseSuppression=!1),de(r.autoGainControl)&&!r.autoGainControl&&(i.autoGainControl=!1),Bt(i)?!0:i)}function Up(r){if(!r.video)return!1;if(r.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=r,e={};return r.cameraId?e.deviceId=r.useExactDeviceId?{exact:r.cameraId}:r.cameraId:r.facingMode&&(e.facingMode=r.facingMode),r.useDeviceIdOnly&&!Bt(e)?e:(r.width&&(e.width={ideal:r.width},i&&!ie&&(e.width.max=r.width)),r.height&&(e.height={ideal:r.height},i&&!ie&&(e.height.max=r.height)),ie&&bt&&r.width&&r.height&&r.width*r.height<352*288&&(e.width=r.width,e.height=r.height),r.frameRate&&(e.frameRate=r.frameRate),Bt(e)?!0:e)}var nl=Pp;function In(r){return J((i,e)=>function(...t){return _(this,null,function*(){return yield r.apply(this,t),i.apply(this,t)})})}function gt(r){return J((i,e)=>function(...t){return _(this,null,function*(){let s=yield i.apply(this,t);return yield r.call(this,...t),s})})}function J(r){return function(i,e,t){return t.value=r(t.value,e),t}}var al=(()=>{let r=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&I.info(`visibility change: ${document.visibilityState}`),!r&&(document.addEventListener("visibilitychange",()=>{I.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),r=!0)}})();var Bp=0,An=class{constructor(){this.log=I.createLogger({id:`fq${++Bp}`});this.isRunning=!1;this.queue=[]}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(i,e=!1){var o,n;let t=N({},i),s=new Promise((a,c)=>{t.resolve=a,t.reject=c});return t.promise=s,e?this.length<=1?this.queue.push(t):(n=(o=this.lastQueueItem)==null?void 0:o.promise)==null||n.then(t.resolve,t.reject):this.queue.push(t),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),s}shift(){let i=this.queue.shift();return this.log.debug(`shift ${this.length}`),i}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:i,args:e,context:t,resolve:s,reject:o}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(s,o).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},qs=new WeakMap,Cn=new WeakMap;function $t(r=!1){return function(i,e,t){let s=t.value;return t.value=function(...o){let n=qs.get(this)||new An;return qs.set(this,n),n.push({fn:s,args:o,context:this},r)},t}}function cl(r){return function(i,e,t){let s=t.value;return t.value=function(...o){let n=qs.get(this);if(n){let a=n.queue.filter((c,d)=>{if(d===0)return!0;let l=!0;return c.args.forEach(p=>{o.find(m=>m===p)||(l=!1)}),l?(c.reject(new b({code:A.API_CALL_ABORTED,message:r})),!1):!0});n.queue=a}return s.apply(this,o)},t}}function Rn(r){return function(i,e,t){let s=t.value;return t.value=function(...o){var a,c,d;let n=[];return(c=(a=qs.get(this))==null?void 0:a.queue)==null||c.forEach(l=>n.push(l)),(d=Cn.get(this))==null||d.forEach(l=>l==null?void 0:l.queue.forEach(p=>n.push(p))),n.forEach(l=>{l.reject(new b({code:A.API_CALL_ABORTED,message:r}))}),qs.delete(this),Cn.delete(this),s.apply(this,o)},t}}function si(r){return function(i,e,t){let s=t.value,o=n=>r(...n);return t.value=function(...n){let a=Cn.get(this)||new Map,c=a.get(o(n))||new An;return a.set(o(n),c),Cn.set(this,a),c.push({fn:s,args:n,context:this})},t}}var Tc=class extends qi{constructor(e,t){super({mediaType:e,PlayerClass:t});u(this,"isRemote",!1);u(this,"deviceId");u(this,"groupId","");u(this,"label","");u(this,"_isRecapturing",!1);u(this,"_lastRecaptureTime",0);u(this,"_onMuteTimeoutId",-1);u(this,"_encodeCheckTimeoutId",-1);u(this,"profile")}get enableEncodeFrame(){return!1}get isPublished(){return this.state==="publish"}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){De(e,e).add(h.MUTE,this.onTrackMuted).add(h.UNMUTE,this.onTrackUnmuted).add(h.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===h.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){me(e)}setStateToCapture(){}capture(e){return _(this,null,function*(){var t;try{let s=x();g.emit(E.LOCAL_TRACK_CAPTURE_START,{track:this});let o;e.customSource?(o=new MediaStream,o.addTrack(e.customSource)):((t=this.mediaTrack)==null||t.stop(),o=yield nl(e));let n=o.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),g.emit(E.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:x()-s}),o}catch(s){throw g.emit(E.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:s}),this.log.error(`getUserMedia error observed ${s}`),s}})}setInputMediaStreamTrack(e){return this.state===F.INIT&&this.setStateToCapture(),super.setInputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.isPublished)return(t=this.room)==null?void 0:t.replaceTrack(this)}publish(e,t){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),t}unpublish(){this.room&&this.room.localTracks.delete(this),g.emit(E.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return _(this,null,function*(){if(this.mediaTrack&&xt){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:s}=this.mediaTrack;(yield sl({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=s,t&&(this.groupId=t),En().then(n=>{let a=n.find(c=>c.deviceId===e);a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.mediaTrack||this.kind===h.AUDIO&&!rl(this.mediaTrack)||this.kind===h.VIDEO&&!il(this.mediaTrack)||this._isRecapturing||e&&bt&&Ue)}onTrackMuted(){if(super.onTrackMuted(),al(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<lr){setTimeout(()=>this.onTrackMuted(),lr);return}this._onMuteTimeoutId=setTimeout(()=>_(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((We||pe)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return _(this,null,function*(){if(Ie(Tc.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<lr){setTimeout(()=>this.onTrackEnded(),lr);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return _(this,null,function*(){var s;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),(s=this._inputTrack)==null||s.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let t={useExactDeviceId:!0};if(e==="user"||e==="environment")t.facingMode=e;else{let o;(this.kind==="audio"?yield Be():yield Xe()).find(a=>a.deviceId===e)&&(o=e),t.deviceId=o}return this.capture(t).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),g.emit(E.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(o=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${o.message}`),this.emit("5",o),g.emit(E.LOCAL_TRACK_RECAPTURE,{track:this,error:o})})})}getRecoverCaptureDeviceId(){return _(this,null,function*(){let e=this instanceof le;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let s=(Xs.get(t)||0)+1;if(Xs.set(t,s),s>=3){let o=e?(yield Xe()).find(n=>!Xs.has(n.deviceId)):(yield Be()).find(n=>!Xs.has(n.deviceId));o&&(this.log.warn(`${t} capture fail ${s} times, change new ${o.deviceId}`),t=o.deviceId)}}return t})}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),(e=this.manager)==null||e.removeInput(this)}},Qe=Tc;y([ue(F.INIT,"capture",{ignoreError:!0,sync:!0})],Qe.prototype,"setStateToCapture",1),y([$t()],Qe.prototype,"capture",1),y([ue("capture","publish",{ignoreError:!0,success(){this.room.localTracks.add(this),g.emit(E.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this._encodeCheckTimeoutId=setTimeout(()=>{if(this.isPublished&&this.isMediaTrackActive){let r=this.stat.bytesSent>0;D[r?"addSuccessEvent":"addFailedEvent"]({key:this.kind===h.AUDIO?503700:513702}),r||(this.log.warn("encode failed"),this.emit("6",this))}},5e3)},fail(r){let i="error",e=r.cause;e.message.includes("timeout")?i="timeout":e.code===A.API_CALL_ABORTED&&(i="api-call"),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:i,error:e})}})],Qe.prototype,"publish",1),y([J(r=>function(){return _(this,null,function*(){let i=this.state==="publish"?"started":"starting";r.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:i,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),ue([],"capture",{sync:!0})],Qe.prototype,"unpublish",1);var Xs=new Map;g.on(E.SWITCH_DEVICE_SUCCESS,r=>{r.track.deviceId&&Xs.delete(r.track.deviceId)});var Oe=class extends Qe{constructor(e){super(1,Tn);u(this,"mediaType",1);u(this,"volume",0);u(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});u(this,"playerMuted",!0);u(this,"pipeline");u(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});this.manager=e,this.pipeline=new kr(e),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}get playerMediaTrack(){return this.mediaTrack}setInputMediaStreamTrack(e){return _(this,null,function*(){yield Ie(Oe.prototype,this,"setInputMediaStreamTrack").call(this,e);let t=this.trackSettings||{};D.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),D.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),D.addEnum({key:502700,value:0});let{sampleRate:s,channelCount:o}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:s,channelCount:o})}`),this.pipeline.source.channelCount=o||1,this.pipeline.replaceSource(e),this.updatePlayingState(!!e)})}capture({deviceId:e,customSource:t,useExactDeviceId:s=!1}){return super.capture({video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:s,customSource:t})}switchDevice(e){return _(this,null,function*(){if(!!this.mediaTrack){if(this.deviceId===e)if(e===wi){if(yield Ec(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0}),this.room&&(yield this.room.replaceTrack(this)),g.emit(E.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(t){throw this.log.error(`switch microphone failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}}})}listenDeviceChange(){ge&&!ge.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&ge.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return _(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current microphone is lost: ${JSON.stringify(e)}`),ae(this.userId,{eventId:2003,param1:6,streamType:1});let t=yield Be();t[0]?this.recapture(t[0].deviceId):ge.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(o){return _(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:s}){let n=!1;!T(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,n=!0),!T(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,n=!0),!T(s)&&s!==this.profile.autoGainControl&&(this.profile.autoGainControl=s,n=!0),n&&this.deviceId&&(yield this.recapture(this.deviceId))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&D.addEnum({key:502700,value:2}),this.resetPlayerSource()}enableTrackANS(e){if(!this._inputTrack)return;let t=this._inputTrack.getConstraints();return t.noiseSuppression=e,this._inputTrack.applyConstraints(t).catch(s=>this._log.warn(`${e?"enable":"disable"} ANS failed `,s))}addDenoiser(e){var t;if(ht<=92&&((t=this.trackSettings)==null?void 0:t.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}D.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.resetPlayerSource(),this.enableTrackANS(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.resetPlayerSource(),this.enableTrackANS(!0))}resetPlayerSource(){this.player.setSourceNode(this.pipeline.gain.node||this.pipeline.denoiser.node||this.pipeline.source.node)}close(){this.pipeline.remove(),ge.off("audioInputAdded",this.handleMicrophoneAdded,this),ge.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return _(this,null,function*(){try{yield Ie(Oe.prototype,this,"recapture").call(this,e)}catch(t){let s=(yield Be()).find(o=>o.deviceId!==e);if(s)yield Ie(Oe.prototype,this,"recapture").call(this,s.deviceId);else throw t}})}};var Ni=class{constructor(i,e=!1){this.dataView=i;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-2,t=[],s=0;for(let n=i;n<=e;n++){let a=this.dataView.getInt8(n);switch(a){case 0:case 1:case 2:case 3:s===2&&(t.push(3),s=0),a==0?s++:s=0,t.push(a);break;default:s=0,t.push(a);break}}t.push(this.dataView.getInt8(this.dataView.byteLength-1));let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=o}removePreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,t=[],s=0;for(let n=i;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:s++,t.push(this.dataView.getInt8(n));break;case 3:s!==2&&t.push(this.dataView.getInt8(n)),s=0;break;default:t.push(this.dataView.getInt8(n)),s=0;break}let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=o}get isSEI(){return this.dataView.getUint8(4)===6}get seiPayloadStartIndex(){let i=6;for(let e=6;e<this.dataView.buffer.byteLength&&(i++,this.dataView.getUint8(e)===255);e++);return i}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let i=0,e=6;for(let o=6;o<this.dataView.buffer.byteLength;o++){let n=this.dataView.getUint8(o);if(e++,n===255)i+=255;else{i+=n;break}}let t=new ArrayBuffer(i),s=new DataView(t);for(let o=0;o<t.byteLength;o++,e++)s.setInt8(o,this.dataView.getInt8(e));return s}};var yn=class{constructor(){u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(this,"_seiPayloadType",243)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),s=e%255,o=[];o.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)o.push(255);o.push(s);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Ni(new DataView(new Uint8Array(o).buffer),!0)}sendSEI(i,e){e!=null&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(i),e!=null&&e.small&&this._smallSeiMessageList.push(i)}getNaluCount(i){let e=0,t=0,s=new DataView(i);for(let o=0;o<i.byteLength;o++)switch(s.getUint8(o)){case 0:e++;break;case 1:(e===2||e===3)&&t++,e=0;break;default:e=0;break}return t}encode(i,e){let t=e?this._smallSeiMessageList:this._seiMessageList;if(t.length>0&&i.data.byteLength>0){let s=this.getNaluCount(i.data),o=9-s;if(o<=0)return 0;let n=t.splice(0,o).reverse().map(this.encodeSEINalu.bind(this)),a=n.reduce((m,f)=>m+f.dataView.byteLength,0),c=new ArrayBuffer(a+i.data.byteLength),d=new DataView(c),l=new DataView(i.data),p=0;for(let m=0;m<n.length;m++)for(let f=0;f<n[m].dataView.byteLength;f++)d.setInt8(p++,n[m].dataView.getInt8(f));for(let m=0;m<i.data.byteLength;m++)d.setInt8(p++,l.getInt8(m));return i.data=c,n.length}return 0}};var le=class extends Qe{constructor(e,t=4){super(t,je);u(this,"profile",{width:640,height:480,frameRate:15,bitrate:500});u(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0});u(this,"small");u(this,"isNeedToSetBandwidth");u(this,"muteImage");u(this,"manager");u(this,"_seiCodec",new yn);u(this,"pipeline",[]);this.manager=e;let s=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),this.setProfile(P(N({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",s),this.on("publish",s),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!xt||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}setMute(e){return _(this,null,function*(){var t,s,o;if(Y(e)){if(this.muteImage===e)return;yield(t=this.manager)==null?void 0:t.deleteWatermark("mute"),yield(s=this.manager)==null?void 0:s.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e}),this.muteImage=e,Ie(le.prototype,this,"setMute").call(this,!1)}else yield(o=this.manager)==null?void 0:o.deleteWatermark("mute"),this.muteImage=void 0,Ie(le.prototype,this,"setMute").call(this,e)})}capture({deviceId:e,facingMode:t,useExactDeviceId:s=!1,customSource:o}){return super.capture({audio:!1,video:!0,facingMode:t||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:s,customSource:o})}setProfile(e){let t=N({},e),s=t.width>t.height;t.width*t.height<=160*120&&pe&&Pe&&(this.log.warn(`resolution is ${t.width}*${t.height}, fallback to 240*180`),t.width=s?240:180,t.height=s?180:240,t.bitrate=Math.max(t.bitrate,150)),t.width*t.height>1280*720&&Pa&&(t.width=s?1280:720,t.height=s?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(t):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(P(N({},this.profile),{width:1920,height:1080})))}applyProfile(){var s;if(!this.mediaTrack)return;let e=this.settings;if(e.height!==this.profile.height||e.width!==this.profile.width||e.frameRate!==this.profile.frameRate)return(s=this.mediaTrack)==null?void 0:s.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}).then(()=>{if(this.manager&&this.manager.changeInput(this),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth)return this.isNeedToSetBandwidth=!1,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:h.VIDEO,videoType:h.BIG})})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return xt&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e}get scaleResolutionDownBy(){let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:Ja()&&this.profile.width>this.profile.height&&e.height>e.width?Math.max(e.width/this.profile.height,e.height/this.profile.width,1):Math.max(e.width/this.profile.width,e.height/this.profile.height,1)}isAllowed2k4k(e){var t;return!this.room||!this.room.scheduleResult||this.isScreen||e.height*e.width<2560*1440?!0:((t=this.room.scheduleResult.trtcAutoConf)==null?void 0:t["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return _(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e))return;let t={useExactDeviceId:!0};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),g.emit(E.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(t){throw this.log.error(`switch camera failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}})}listenDeviceChange(){ge&&!ge.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&ge.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return _(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current camera is lost: ${JSON.stringify(e)}`),ae(this.userId,{eventId:2003,param1:7,streamType:2});let t=yield Xe();t[0]?this.recapture(t[0].deviceId):ge.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return _(this,null,function*(){this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}encodeFrame(e,t){let s=t?8:this.mediaType;return this.pipeline.reduce((o,n)=>n?n(o,s):o,e)}get enableEncodeFrame(){return this.pipeline.some(e=>e)}play(e,t){return _(this,null,function*(){return T(this.mirror)&&!this.isScreen&&this.setMirror("view"),Ie(le.prototype,this,"play").call(this,e,t)})}close(){ge.off("videoInputAdded",this.handleCameraAdded,this),ge.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return _(this,null,function*(){try{yield Ie(le.prototype,this,"recapture").call(this,e)}catch(t){let s=(yield Xe()).find(o=>o.deviceId!==e);if(s)yield Ie(le.prototype,this,"recapture").call(this,s.deviceId);else throw t}})}};var hl=Ms();if(navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:hl,exposeOrigin:!0,permittedOrigins:["*"]})}catch(r){}var Wp=function(r){return _(this,null,function*(){let i=null,e=qp(r);I.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);r.systemAudio&&t.getAudioTracks().length===0&&(Sr&&ht<74||Ue||ie)&&I.warn("Your browser not support capture system audio");let s=t.getVideoTracks()[0];if(s){if(r.frameRate)try{yield s.applyConstraints({frameRate:{min:r.frameRate,ideal:r.frameRate},width:r.width,height:r.height})}catch(o){I.warn(`screen applyConstraints failed: ${o}`)}r.captureElement&&(yield Jp(s,r.captureElement))}if(r.audio){let o=jp(r);I.info(`getUserMedia with constraints: ${JSON.stringify(o)}`),i=yield navigator.mediaDevices.getUserMedia(o),t.addTrack(i.getAudioTracks()[0])}return t})};function Jp(r,i){return _(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&W(r.cropTo))try{if(!(((e=r.getCaptureHandle())==null?void 0:e.handle)===hl))return;let s=yield CropTarget.fromElement(i);yield r.cropTo(s)}catch(t){I.warn(`cropTo target failed ${t}`)}})}function jp(r){let i={echoCancellation:r.echoCancellation,autoGainControl:r.autoGainControl,noiseSuppression:r.noiseSuppression,sampleRate:r.sampleRate,channelCount:r.channelCount};return T(r.microphoneId)||(i.deviceId=r.microphoneId),{audio:i,video:!1}}function qp(r){let i={preferCurrentTab:r.preferDisplaySurface==="current-tab"||!!r.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Ue?{max:r.width}:{ideal:r.width,max:r.width},height:Ue?{max:r.height}:{ideal:r.height,max:r.height},frameRate:r.frameRate,displaySurface:r.preferDisplaySurface||"monitor"};if(i.video=e,r.systemAudio){let{echoCancellation:t=!0,noiseSuppression:s=!1,autoGainControl:o=!1}=r;i.audio={echoCancellation:t,noiseSuppression:s,autoGainControl:o,sampleRate:48e3}}return i}var ml=Wp;var ze=class extends le{constructor(e){super(e,2);u(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});u(this,"objectFit","contain");u(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(l){return _(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:s,noiseSuppression:o,audioTrack:n,videoTrack:a,captureElement:c,preferDisplaySurface:d}){try{let p;return a||n?(p=new MediaStream,a&&p.addTrack(a),n&&p.addTrack(n)):p=yield ml({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:s,noiseSuppression:o,captureElement:c,preferDisplaySurface:d}),yield this.setInputMediaStreamTrack(p.getVideoTracks()[0]),p}catch(p){throw this.log.error(`getDisplayMedia error observed ${p}`),p instanceof b?p:new b({code:A.INITIALIZE_FAILED,name:p.name,message:p.message})}})}switchDevice(e){return _(this,null,function*(){throw new Error("Method not implemented.")})}};var Ft=class extends Oe{constructor(i){super(i),this._log.id=`s-${this._log.id}`}};var Xp="registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});",Sc;function pl(r){return _(this,null,function*(){let i=qe("dump");Sc||(Sc=Gi(i,URL.createObjectURL(new Blob([Xp],{type:"application/javascript"})))),yield Sc;let e=new AudioWorkletNode(i,"dumper",{numberOfInputs:r.length,numberOfOutputs:0});return r.forEach((t,s)=>t.connect(e,0,s)),new ReadableStream({start(t){e.port.onmessage=s=>{t.enqueue(s.data)}},cancel(){r.forEach(t=>t.disconnect(e)),e.port.close()}})})}var bn=class extends _n{constructor(e){super();this.room=e;u(this,"_localAudioTrack");u(this,"_localScreenAudioTrack");u(this,"log",I.createLogger({id:"am"}));u(this,"denoiser");e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}dump(e){var l,p;if(!this._localAudioTrack)return;let t=[],s=[];(l=this._localAudioPipline)!=null&&l.source.node&&(t.push(this._localAudioPipline.source.node),s.push("mic")),(p=this._localAudioPipline)!=null&&p.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),s.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),s.push("mix")),this.log.info(`dump audio track ${s}, duration: ${e}`);let o=new AbortController,n=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),o.abort("timeout")},e*1e3),c=()=>{for(let m=0;m<s.length;m++){let f=URL.createObjectURL(new Blob(n[m])),R=document.createElement("a");R.href=f,R.download=`${s[m]}.pcm`,R.style.display="none",document.body.appendChild(R),R.click(),URL.revokeObjectURL(f),R.remove()}clearTimeout(a),o.abort("download")},d=pl(t).then(m=>m.pipeTo(new WritableStream({write(f){f.forEach((R,C)=>n[C]=n[C]?n[C].concat(R[0]):[R[0]])}}),o).catch(f=>c));return{then:d.then.bind(d),download:c}}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return this._localAudioTrack!==null}changeInput(e){if(e instanceof Ft)this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();else if(e instanceof Oe)this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();else if(e instanceof oi)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixOnChange(){var e,t;(e=this._localAudioTrack)==null||e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null||t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)}removeInput(e){e instanceof Ft?delete this._localScreenAudioTrack:e instanceof Oe?delete this._localAudioTrack:e instanceof oi}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}removeDenoiser(e){var t;delete this.denoiser,(t=this._localAudioTrack)==null||t.removeDenoiser(e)}destroy(){this.close()}};function Nn(r=30,i=2){return J((e,t)=>function(...s){return new Promise((o,n)=>{let a=setTimeout(()=>{let c=new b({code:A.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${r}s`});I.warn(c),i===2?n(c):i===1&&o()},r*1e3);e.apply(this,s).then(o,n).finally(()=>{clearTimeout(a)})})})}var Ic=class extends qi{constructor(e,t,s){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:s,room:e});this.room=e;this.user=t;u(this,"tinyId");u(this,"isRemote",!0);u(this,"jitterBufferDelay",0);u(this,"_decodeCheckTimeoutId",-1);this.tinyId=t.tinyId}setMute(e){this.hasFlag&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.hasFlag&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===Ic.STATE_SUBSCRIBE}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.hasFlag||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} hasFlag: ${this.hasFlag} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}onFlagChanged(){this.updatePlayingState(this.hasFlag)}onTrackMuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackMuted()}onTrackUnmuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackUnmuted()}onTrackEnded(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackEnded()}},rt=Ic;u(rt,"STATE_SUBSCRIBE","subscribe"),y([Nn(5,1)],rt.prototype,"waitHasMediaTrack",1),y([ue(F.INIT,rt.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),g.emit(E.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0),this._decodeCheckTimeoutId=setTimeout(()=>{if(this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived>0){let r=this.player.isPlaying||(this.kind===h.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0);D[r?"addSuccessEvent":"addFailedEvent"]({key:this.kind===h.AUDIO?504700:514702}),r||this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===h.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`} )`)}},5e3)},ignoreError:!0})],rt.prototype,"subscribe",1),y([ue(rt.STATE_SUBSCRIBE,F.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),g.emit(E.REMOTE_TRACK_UNSUBSCRIBED,{track:this}),clearTimeout(this._decodeCheckTimeoutId)}})],rt.prototype,"unsubscribe",1);var oi=class extends rt{constructor(e,t){super(e,t,1);u(this,"volume",0);u(this,"mediaType",1);u(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});u(this,"audioDecoder");this.manager=e.audioManager}onPlayerError(e){if(this.enableDecodeFrame){this.room.enableInsertableStreams();let t=new AudioDecoder({error:s=>this._log.error(s),output:s=>{this.player.write(s)}});t.configure({codec:"opus",sampleRate:48e3,numberOfChannels:1}),this._log.info(`audioDecoder state:${t.state}`),this.audioDecoder=t}}get enableDecodeFrame(){var e,t;return((t=(e=this.player.element)==null?void 0:e.error)==null?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&Fi&&nn().AudioDecoder}decodeFrame(e){var t;return((t=this.audioDecoder)==null?void 0:t.state)==="configured"&&this.audioDecoder.decode(new EncodedAudioChunk({data:e.data,timestamp:e.timestamp,type:"key"})),e}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get hasFlag(){return this.user.muteState.hasAudio}isFlagChanged(e){let t=e.hasAudio&&!e.audioMuted;return this.hasFlag||(this.volume=0),this.hasFlag!==t}};var zp=[-1,-1,1,-1,-1,1,1,1],Yp=[0,0,1,0,0,1,1,1],Ye=class extends F{constructor(e,t){super();this.context=e;u(this,"name");u(this,"input");u(this,"output");u(this,"texture");u(this,"ctx2d",null);u(this,"fbo");u(this,"width",0);u(this,"height",0);u(this,"x",0);u(this,"y",0);u(this,"program");u(this,"vertexShader");u(this,"fragmentShader");u(this,"totalFrames",0);u(this,"dropFrames",0);u(this,"matchInputSize",!0);u(this,"texCoordBuffer");u(this,"positionBuffer");u(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});u(this,"cost",0);u(this,"_canvas",null);u(this,"_image");if(this.context.on("disconnect",this.close,this),this.name=t.name,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof Fe){if(e.ctx&&t.create2d){let s=document.createElement("canvas"),o=typeof s.transferControlToOffscreen=="function"?s.transferControlToOffscreen():s;o.width=this.width,o.height=this.height,this.ctx2d=o.getContext("2d"),this._image=o,this._canvas=o}return}try{let s=e.ctx;this.texCoordBuffer=this.createBuffer(Yp),this.positionBuffer=this.createBuffer(zp),t.createTexture!==!1&&(this.texture=s.createTexture(),this.useTexture(),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.pixelStorei(s.PACK_ALIGNMENT,1),s.pixelStorei(s.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=s.createFramebuffer(),this.useBufferFrame(),this.useTexture(),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,this.width,this.height,0,s.RGBA,s.UNSIGNED_BYTE,null),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(s.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(s.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(s){this.context.destroy(s)}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,s=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),s}connect(e,...t){return e.addInput(this,...t),this.output=e,e}addInput(e,...t){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();if(this.context instanceof ye&&this.render(e)||this.context instanceof Fe&&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}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 ye){let s=this.context.ctx;s.deleteBuffer(this.texCoordBuffer),s.deleteBuffer(this.positionBuffer),this.fbo&&s.deleteFramebuffer(this.fbo),this.texture&&s.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&s.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&s.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&s.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let t=this.context.ctx;e.forEach((s,o)=>{s&&(t.activeTexture(t.TEXTURE0+o),t.bindTexture(t.TEXTURE_2D,s))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,s=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,s),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),s}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let s=this.context.ctx;s.bindBuffer(s.ARRAY_BUFFER,e),s.bufferData(s.ARRAY_BUFFER,new Float32Array(t),s.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((s,o)=>{t.enableVertexAttribArray(o),t.bindBuffer(t.ARRAY_BUFFER,s),t.vertexAttribPointer(o,2,t.FLOAT,!1,0,0)})}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(!(this.width===e&&this.height===t)){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let s=this.context.ctx;s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,s.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let s=this.context.ctx;s.drawArrays(s.TRIANGLE_STRIP,0,4)}draw2d(e,t,s,o,n){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,t,s):this.ctx2d.drawImage(e,t,s,o,n),!0):!1}getInfo(){var p;let{totalFrames:e,x:t,y:s,width:o,height:n,name:a,cost:c}=this,d=Date.now(),l=(e-this.lastInfo.totalFrames)/((d-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:s,width:o,height:n,timestamp:d,fps:l,name:a,cost:c},N({parent:(p=this.input)==null?void 0:p.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,s=t.createTexture();return this.useTextures(s),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),s}};y([ue(F.INIT,"connected",{sync:!0})],Ye.prototype,"connect",1),y([ue("connected",F.INIT,{ignoreError:!0,sync:!0})],Ye.prototype,"disconnect",1),y([ue([],"closed",{sync:!0})],Ye.prototype,"close",1);var Kp=[0,1,1,1,0,0,1,0],Qs=class extends Ye{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));u(this,"_intervalId",0);u(this,"_sequence",0);u(this,"checkGLError",!1);e instanceof Fe?this.ctx2d=e.ctx:e.available&&(t==null?void 0:t.mirrorUpAndDown)&&this.setTexBuffer(Kp)}start(e){this._intervalId=re.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(re.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof ye){let s=this.context.ctx.getError();s&&this.context.destroy(new Error(`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${s}`))}},{fps:this.context.frameRate})}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}removeInput(e){super.removeInput(e),re.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}},Pr=class extends Qs{constructor(e,t){super(e,t);u(this,"_videoTrack");u(this,"_canvasContainer");Number(gi)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks();let s=o=>{var c;let n=()=>{var d;return(d=this._videoTrack)==null?void 0:d.removeEventListener(o,a)},a=()=>{n(),this.context.destroy(new Error(`video track ${o}`))};this.once("closed",n),(c=this._videoTrack)==null||c.addEventListener(o,a)};e instanceof ye&&s("mute"),s("ended")}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(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()}},vn=class extends Pr{render(i){var e;return!!((e=this.input)!=null&&e.requestFrame(i))}};var Dn=class extends Pr{constructor(e,t){super(e,{name:"smallDestination"});this.resolution=t}resize(e,t){let s,o=e*t,n=this.resolution.width*this.resolution.height;I.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),o>n?s=o/n:(I.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${t} small: ${this.resolution.width} * ${this.resolution.height}`),s=o/(160*120)),super.resize(e/Math.sqrt(s),t/Math.sqrt(s))}};var zs=class extends Ye{constructor(e,t){super(e,N({name:"imageSource"},t));u(this,"_lastImage");u(this,"_totalFrames",0);u(this,"_autoResize",!1);this._autoResize=(t==null?void 0:t.autoResize)!==!1}_render(e,t){var n,a;let{width:s,height:o}=this;if(this.image instanceof HTMLVideoElement){if(W(this.image.getVideoPlaybackQuality)&&Pe){let d=this.image.getVideoPlaybackQuality().totalVideoFrames;if(((a=(n=this.image.srcObject)==null?void 0:n.getVideoTracks()[0])==null?void 0:a.muted)===!0||this._totalFrames===d)return!1;this._totalFrames=d,this.dropFrames=this._totalFrames-this.totalFrames}if({videoWidth:s,videoHeight:o}=this.image,!s||!o)return!1;this.image.width=s,this.image.height=o}else if(this.image instanceof HTMLImageElement||this.image instanceof ImageData||this.image instanceof ImageBitmap){if({width:s,height:o}=this.image,this.image!==this._lastImage)this._lastImage=this.image;else if(s===this.width&&o===this.height)return!1}else(this.image instanceof HTMLCanvasElement||this.image instanceof OffscreenCanvas)&&({width:s,height:o}=this.image,this._lastImage=this.image);if(!this._autoResize)return!0;if(this.width===s&&this.height===o&&this.totalFrames){if(t){this.useTexture();let c=this.context.ctx;c.texSubImage2D(c.TEXTURE_2D,0,0,0,c.RGBA,c.UNSIGNED_BYTE,this.image)}}else{if(t){this.useTexture();let c=this.context.ctx;c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,this.image)}this.resize(s,o)}return!0}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},Ys=class extends zs{constructor(e,t,s){super(e,s);this._player=t;this.name="videoPlayerSource"}get image(){return this._player.element}},wr=class extends Ys{constructor(i,e,t){super(i,new je({id:t.name,track:e,muted:!0,container:null,objectFit:"contain",log:t.logger}),t),this.name="videoTrackSource",this._player.play()}get image(){return this._player.element}replaceTrack(i){this._player.setTrack(i),this._player.play()}close(){super.close(),this._player.stop()}};var Zp=`
|
|
43
|
+
`,qi=class{constructor(i){l(this,"_volume",0);l(this,"_log");l(this,"_scriptProcessorNode",null);l(this,"_audioWorkletNode",null);l(this,"_interval",200);l(this,"ready",this.preload());let{log:e}=i;this._log=e,g.on(E.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){return qi.workletReady||(qi.workletReady=Ji(qi.audioContext,URL.createObjectURL(new Blob([Mp],{type:"application/javascript"})))),qi.workletReady.then(()=>this.initAudioWorklet()).catch(()=>this.initScriptProcessor())}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(qi.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{this._volume=e.data.volume||0,!i&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),i=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(i){Z.logFailedEvent({userId:this._log.userId,eventType:Ve.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=qe("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{let e=i.inputBuffer.getChannelData(0),t=0;for(let s=0;s<e.length;++s)t+=e[s]*e[s];this._volume=Math.sqrt(t/e.length)||0}}catch(i){this._log.error(`volumeMeter init script processor error: ${i}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,g.off(E.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}},Js=qi;l(Js,"audioContext",qe("volume-meter")),l(Js,"workletReady");var En=class extends gt{constructor(e){super();l(this,"_volumeMeter");this._volumeMeter=new Js(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return _(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),s=new Float32Array(t>>2);e.copyTo(s,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:s},[s.buffer]),e.close()}}};var tu=Se(Ne(),1);var Zl=r=>i=>i.deviceId===r;var js=class{constructor(i,e="Input"){l(this,"kind");l(this,"type");l(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(s=>s.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&Pr(this.devices[0])){this.devices=t;return}e&&(t.forEach(s=>{if(s.deviceId&&!this.devices.find(Zl(s.deviceId))){let o=`${this.kind}${this.type}Added`;I.warn(`${o}: ${JSON.stringify(s)}`),e.emit(o,s)}}),this.devices.forEach(s=>{if(s.deviceId&&!t.find(Zl(s.deviceId))){let o=`${this.kind}${this.type}Removed`;I.warn(`${o}: ${JSON.stringify(s)}`),e.emit(o,s)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},fc=class extends tu.EventEmitter{constructor(){super();l(this,"audioInputs",new js(h.AUDIO));l(this,"videoInputs",new js(h.VIDEO));l(this,"audioOutputs",new js(h.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||re.run(Bi,()=>{this.update()},{delay:1e4}))}init(){gn().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return _(this,arguments,function*(e=0){let t=yield gn(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}},ge=ss||lr?null:new fc;function Pr(r){return r.deviceId===r.groupId&&r.groupId===""}function gn(){return _(this,arguments,function*(r=0){if(ri()||!sn())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(r!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{Pr(t)&&(t.kind===h.AUDIO_INPUT?e.audio=!0:t.kind===h.VIDEO_INPUT&&(e.video=!0))}),r===2&&(e.audio=!1),r===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e)}catch(s){I.debug("capture before getDevices failed: ",s)}i=yield navigator.mediaDevices.enumerateDevices(),t==null||t.getTracks().forEach(s=>s.stop())}}return i.map((e,t)=>{let s={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${t}`};return e.deviceId.length>0&&Ec.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(s.getCapabilities=()=>e.getCapabilities()),s})})}function Be(r=!1){return ge.update(r?1:0).then(i=>i.audioInputs.devices)}function Xe(r=!1){return ge.update(r?2:0).then(i=>i.videoInputs.devices)}var eu=!1;function iu(){return _(this,null,function*(){try{eu||(eu=!0,I.info(`speakers:${(yield Xi()).map(r=>` ${r.deviceId.slice(0,8)}: ${r.label}`)}`))}catch(r){}})}function Xi(r=!1){return _(this,null,function*(){return ge.update(r?1:0).then(i=>i.audioOutputs.devices)})}var Ec=new Set;function ru(r){if(r instanceof CanvasCaptureMediaStreamTrack||!(r instanceof MediaStreamTrack))return!1;let i=r.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let t=`${((r==null?void 0:r.getSettings())||{}).deviceId}_${h.VIDEO_INPUT}`;return!!Ec.has(t)}function su(r){if(r instanceof CanvasCaptureMediaStreamTrack||!(r instanceof MediaStreamTrack))return!1;let i=r.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("\u9EA6\u514B\u98CE"))return!0;let t=`${((r==null?void 0:r.getSettings())||{}).deviceId}_${h.AUDIO_INPUT}`;return!!Ec.has(t)}function gc(r,i){return _(this,null,function*(){let t=(yield Be()).find(s=>s.deviceId===Ui);return(t==null?void 0:t.groupId)===r&&t.label===i})}function ou(o){return _(this,arguments,function*({newDeviceId:r,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:s}){return r!==i?!1:s===h.AUDIO&&r===Ui?yield gc(e,t):!0})}var Tn,Tc=class extends Ws{constructor(e){super();this.log=e;l(this,"volumeMeter");l(this,"volumeDestination");l(this,"analyser",new _n);this.volumeMeter=new En({log:this.log}),this.volumeDestination=new gt,this.volumeMeter.pipeTo(this.volumeDestination)}destory(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},wr=class extends Ut{constructor(e){super(e,h.AUDIO);l(this,"_outputDeviceId");l(this,"_volume",1);l(this,"_destination",qe("player").createMediaStreamDestination());l(this,"pipeline");l(this,"volumeMeterMode","worklet");this.pipeline=new Tc(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(){if((Ii==="15.2"||Ii==="15.3"||Ii==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let t=Tn||new Audio;t.setAttribute("autoplay","autoplay"),t.srcObject=this.getMediaStream(),t.muted=this.muted,this.element=t,t===Tn&&(Tn=void 0),this.bindElementEvents()}play(){return _(this,null,function*(){if(!!this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?this.pipeline.volumeMeter.init():this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(qe("player").createAnalyser()),this.setVolume(this._volume),iu(),Ie(wr.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destory(),super.stop(e)}setSinkId(e){return _(this,null,function*(){var t,s;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(s=(t=this.element).setSinkId)==null?void 0:s.call(t,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){!this.element||(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}},Sn=class extends wr{constructor(i){super(i),this.pipeline.source.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination)}setTrack(i){var e;this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(ve.MEDIA_TRACK_CHANGED,i),i?(this.bindTrackEvents(),this.pipeline.source.channelCount=((e=i.getSettings())==null?void 0:e.channelCount)||1,this.pipeline.replaceSource(i),!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([i]))):this.pipeline.source.deleteNode())}setSourceNode(i){!i||this.pipeline.source.node===i||(this.pipeline.replaceSource(i),i instanceof MediaStreamAudioSourceNode?this.pipeline.destination.setNode(this._destination):this.pipeline.destination.deleteNode(),this.element&&(this.element.srcObject=this.getMediaStream(),this.element.play().catch(()=>{}),this.setVolume(this._volume)))}setVolume(i){this._volume=i,this.element&&(this.element.volume=i)}},In=class extends wr{constructor(e){super(e);l(this,"_sourceElement");this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter,this.pipeline.destination))}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,s,o;((s=(t=this.element)==null?void 0:t.error)==null?void 0:s.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(ve.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=((o=e.getSettings())==null?void 0:o.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`)):e<=1?(this.element?this._log.info(`set element volume: ${e}`):this._log.info("set element volume: no element"),this.element&&(this.element.volume=e)):(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),me(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(e=0){this.pipeline.destory();let t=this._sourceElement||this.element;t&&Cr&&(Tn=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var Qi=class extends F{constructor({userId:e,sdkAppId:t,mediaType:s,room:o,PlayerClass:n=s===1?In:je}){var a;super();l(this,"id",ks());l(this,"userId","");l(this,"isRemote");l(this,"mediaType");l(this,"room");l(this,"user");l(this,"_log");l(this,"_inputTrack");l(this,"_outputTrack");l(this,"isPlayCalled");l(this,"container",null);l(this,"player");l(this,"subVideoPlayerMap");l(this,"muted",!1);l(this,"abortCtrl");l(this,"objectFit","cover");l(this,"mirror");l(this,"isScreen",!1);l(this,"manager");l(this,"trackSettings");l(this,"onPlayerError");this.userId=e||"",this.mediaType=s,this._log=I.createLogger({id:`${this.kind[0]}t`,userId:(a=o||this.room)==null?void 0:a.userId,remoteUserId:this instanceof Qe?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof Qe}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(ve.PLAYER_STATE_CHANGED,c=>{g.emit(E.PLAYER_STATE_CHANGED,N({track:this},c)),this.emit("player-state-changed",c)}),this.kind===h.VIDEO&&(this.player.on(ve.LOADED_DATA,()=>{g.emit(E.VIDEO_LOADED_DATA,{track:this})}),this.player.on(ve.MEDIA_TRACK_CHANGED,c=>{var d;(d=this.subVideoPlayerMap)==null||d.forEach(u=>u.setTrack(c))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(ve.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||I}get kind(){return this.mediaType===1?h.AUDIO:h.VIDEO}get strMediaType(){return this.mediaType===4?h.VIDEO:this.mediaType===2?h.SCREEN:h.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}get isMediaTrackActive(){return this.mediaTrack?!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled:!1}play(e,t){return _(this,null,function*(){let s=he(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 je&&(this.player.setObjectFit(this.objectFit),this.container!==s&&s&&(this.container=s,this.player.setContainer(s)),he(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===h.VIDEO)&&this.setPlayerMute(!0),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof je&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,s&&(this.container=s,this.player instanceof je&&this.player.setContainer(s)),g.emit(E.PLAY_TRACK_START,{track:this}),!this._outputTrack){this.log.info("play has not mediaTrack, abort");return}this._log.info(`play with options: ${JSON.stringify(t)}`);try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(),he(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(o){throw this.handleAutoPlayFailed(),this.emit("error",o),o}})}setMirror(e,t){if(this.isScreen||this.kind!==h.VIDEO||T(e)||e===this.mirror)return;this.mirror=e;let s=this.player;t&&(s=t);let o=this.manager;if(de(this.mirror)){s.setViewMirror(this.mirror),o&&(o.mirror=!1);return}switch(this.mirror){case"view":{o&&(o.mirror=!1),s.setViewMirror(!0);break}case"publish":{o&&(o.mirror=!0),s.setViewMirror(!0);break}case"both":o&&(o.mirror=!0),s.setViewMirror(!1)}}playSubContainer(e,t){return _(this,null,function*(){if(!this._outputTrack||this.kind===h.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((o,n)=>{var a;e.find(c=>n===c)||(o.stop(),(a=this.subVideoPlayerMap)==null||a.delete(n))});for(let[o,n]of e.entries()){let a=this.subVideoPlayerMap.get(n);a?t&&(T(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new je({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${o+1}`})}))}let s=[...this.subVideoPlayerMap.values()];for(let o of s)o.setViewMirror(this.player.mirror),yield o.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(){!this.isPlayCalled||(this.isPlayCalled=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(ft(this)?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(e=>{e.stop()}),this.container=null)}resume(){return _(this,null,function*(){var e;!this.isPlayCalled||(yield(e=this.player)==null?void 0:e.resume())})}close(){this.log.info("close"),this.isPlayCalled&&this.stop()}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),g.emit(e?E.TRACK_MUTED:E.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(e){De(e,e).add(h.MUTE,this.onTrackMuted).add(h.UNMUTE,this.onTrackUnmuted).add(h.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===h.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){me(e)}setInputMediaStreamTrack(e){var s;let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.trackSettings=(s=e.getSettings)==null?void 0:s.call(e),e.enabled=!this.muted,t&&this.uninstallTrackEvent(t),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,t||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var s;let t=this._outputTrack;e!==t&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(s=e.getSettings)==null?void 0:s.call(e).deviceId,e.label),this._outputTrack=e,this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(()=>this.handleAutoPlayFailed()),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(ft(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(){if(this.room&&this.room.enableAutoPlayDialog)new zl;else{let e=()=>{this.resume().then(()=>{document.removeEventListener("click",e,!0)})};document.addEventListener("click",e,!0)}}getVideoFrame(){return this.player instanceof je?this.player.getVideoFrame():""}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};y([le([],F.INIT,{sync:!0})],Qi.prototype,"close",1);var kp=Object.prototype.hasOwnProperty,{toString:UT}=Object.prototype;function Lp(r){if(r==null)return!0;if(typeof r=="boolean")return!1;if(typeof r=="number")return r===0;if(typeof r=="string"||typeof r=="function"||Array.isArray(r))return r.length===0;if(r instanceof Error)return r.message==="";if(Je(r))switch(Object.prototype.toString.call(r)){case"[object File]":case"[object Map]":case"[object Set]":return r.size===0;case"[object Object]":{for(let i in r)if(kp.call(r,i))return!1;return!0}}return!1}var $t=Lp;var xp=function(r){return _(this,null,function*(){let i=wp(r);I.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],s=["label","deviceId"];i.audio&&(e=yield Be(),I.info(`microphones: ${_t(e,{keysToInclude:s})}`)),i.video&&(t=yield Xe(),I.info(`cameras: ${_t(t,{keysToInclude:s})}`));try{let o=yield navigator.mediaDevices.getUserMedia(i);return rc&&o.getTracks().forEach(n=>{I.info(`${n.kind} capabilities: ${_t(n.getCapabilities(),{keysToInclude:Mo})}`)}),o}catch(o){let{message:n}=o;throw o.name==="NotFoundError"&&(r.video&&t&&t.length===0&&(n=L({key:M.CAMERA_NOT_FOUND})),r.audio&&e&&e.length===0&&(n=L({key:M.MICROPHONE_NOT_FOUND}))),new b({code:A.INITIALIZE_FAILED,name:o.name,message:n,constraint:o.constraint})}})},Pp=Dt({retryFunction:xp,settings:{retries:3,timeout:500},onError:({error:r,retry:i,reject:e,retryFuncArgs:t,retriedCount:s})=>{let o=s+1;r.name==="NotReadableError"||r.name==="OverconstrainedError"?(o===1?t[0].video&&(t[0].maxResolution=!1,(!Ue||t[0].width*t[0].height<=1920*1080)&&t[0].frameRate&&(t[0].frameRate=t[0].frameRate>10?10:5)):o===2?t[0].useDeviceIdOnly=!0:o===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(r),t[0].microphoneId&&nu(t[0].microphoneId,!1),t[0].cameraId&&nu(t[0].cameraId,!0)},onRetrying:r=>{I.warn(`getUserMedia NotReadableError observed, retrying [${r}/3]`)},onRetryFailed:r=>{Z.logFailedEvent({eventType:Ve.GET_USER_MEDIA_RETRY,error:r})},onRetrySuccess:r=>{Z.logSuccessEvent({eventType:Ve.GET_USER_MEDIA_RETRY}),Z.uploadEvent({log:`stat-${Ve.GET_USER_MEDIA_RETRY}-success-${r}`})}});function nu(r,i){return _(this,null,function*(){let t=(i?yield Xe():yield Be()).find(s=>s.deviceId===r);t&&K(t.getCapabilities)&&I.warn(_t(t.getCapabilities(),{keysToInclude:Mo}))})}function wp(r){return{audio:Vp(r),video:Up(r)}}function Vp(r){if(!r.audio)return!1;if(r.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:r.sampleRate};return!$t(r.microphoneId)&&(i.deviceId=r.useExactDeviceId?{exact:r.microphoneId}:r.microphoneId,r.useDeviceIdOnly)?i:(ee(r.channelCount)&&(i.channelCount=r.channelCount),de(r.echoCancellation)&&!r.echoCancellation&&(i.echoCancellation=!1),de(r.noiseSuppression)&&!r.noiseSuppression&&(i.noiseSuppression=!1),de(r.autoGainControl)&&!r.autoGainControl&&(i.autoGainControl=!1),$t(i)?!0:i)}function Up(r){if(!r.video)return!1;if(r.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=r,e={};return r.cameraId?e.deviceId=r.useExactDeviceId?{exact:r.cameraId}:r.cameraId:r.facingMode&&(e.facingMode=r.facingMode),r.useDeviceIdOnly&&!$t(e)?e:(r.width&&(e.width={ideal:r.width},i&&!ie&&(e.width.max=r.width)),r.height&&(e.height={ideal:r.height},i&&!ie&&(e.height.max=r.height)),ie&&bt&&r.width&&r.height&&r.width*r.height<352*288&&(e.width=r.width,e.height=r.height),r.frameRate&&(e.frameRate=r.frameRate),$t(e)?!0:e)}var au=Pp;function An(r){return W((i,e)=>function(...t){return _(this,null,function*(){return yield r.apply(this,t),i.apply(this,t)})})}function Tt(r){return W((i,e)=>function(...t){return _(this,null,function*(){let s=yield i.apply(this,t);return yield r.call(this,...t),s})})}function W(r){return function(i,e,t){return t.value=r(t.value,e),t}}var cu=(()=>{let r=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&I.info(`visibility change: ${document.visibilityState}`),!r&&(document.addEventListener("visibilitychange",()=>{I.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),r=!0)}})();var Bp=0,Cn=class{constructor(){this.log=I.createLogger({id:`fq${++Bp}`});this.isRunning=!1;this.queue=[]}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(i,e=!1){var o,n;let t=N({},i),s=new Promise((a,c)=>{t.resolve=a,t.reject=c});return t.promise=s,e?this.length<=1?this.queue.push(t):(n=(o=this.lastQueueItem)==null?void 0:o.promise)==null||n.then(t.resolve,t.reject):this.queue.push(t),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),s}shift(){let i=this.queue.shift();return this.log.debug(`shift ${this.length}`),i}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:i,args:e,context:t,resolve:s,reject:o}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(s,o).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},Xs=new WeakMap,Rn=new WeakMap;function Ft(r=!1){return function(i,e,t){let s=t.value;return t.value=function(...o){let n=Xs.get(this)||new Cn;return Xs.set(this,n),n.push({fn:s,args:o,context:this},r)},t}}function du(r){return function(i,e,t){let s=t.value;return t.value=function(...o){let n=Xs.get(this);if(n){let a=n.queue.filter((c,d)=>{if(d===0)return!0;let u=!0;return c.args.forEach(p=>{o.find(m=>m===p)||(u=!1)}),u?(c.reject(new b({code:A.API_CALL_ABORTED,message:r})),!1):!0});n.queue=a}return s.apply(this,o)},t}}function yn(r){return function(i,e,t){let s=t.value;return t.value=function(...o){var a,c,d;let n=[];return(c=(a=Xs.get(this))==null?void 0:a.queue)==null||c.forEach(u=>n.push(u)),(d=Rn.get(this))==null||d.forEach(u=>u==null?void 0:u.queue.forEach(p=>n.push(p))),n.forEach(u=>{u.reject(new b({code:A.API_CALL_ABORTED,message:r}))}),Xs.delete(this),Rn.delete(this),s.apply(this,o)},t}}function oi(r){return function(i,e,t){let s=t.value,o=n=>r(...n);return t.value=function(...n){let a=Rn.get(this)||new Map,c=a.get(o(n))||new Cn;return a.set(o(n),c),Rn.set(this,a),c.push({fn:s,args:n,context:this})},t}}var Sc=class extends Qi{constructor(e,t){super({mediaType:e,PlayerClass:t});l(this,"isRemote",!1);l(this,"deviceId");l(this,"groupId","");l(this,"label","");l(this,"_isRecapturing",!1);l(this,"_lastRecaptureTime",0);l(this,"_onMuteTimeoutId",-1);l(this,"_encodeCheckTimeoutId",-1);l(this,"profile")}get enableEncodeFrame(){return!1}get isPublished(){return this.state==="publish"}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){De(e,e).add(h.MUTE,this.onTrackMuted).add(h.UNMUTE,this.onTrackUnmuted).add(h.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===h.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){me(e)}setStateToCapture(){}capture(e){return _(this,null,function*(){var t;try{let s=x();g.emit(E.LOCAL_TRACK_CAPTURE_START,{track:this});let o;e.customSource?(o=new MediaStream,o.addTrack(e.customSource)):((t=this.mediaTrack)==null||t.stop(),o=yield au(e));let n=o.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),g.emit(E.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:x()-s}),o}catch(s){throw g.emit(E.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:s}),this.log.error(`getUserMedia error observed ${s}`),s}})}setInputMediaStreamTrack(e){return this.state===F.INIT&&this.setStateToCapture(),super.setInputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.isPublished)return(t=this.room)==null?void 0:t.replaceTrack(this)}publish(e,t){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),t}unpublish(){this.room&&this.room.localTracks.delete(this),g.emit(E.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return _(this,null,function*(){if(this.mediaTrack&&Pt){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:s}=this.mediaTrack;(yield ou({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=s,t&&(this.groupId=t),gn().then(n=>{let a=n.find(c=>c.deviceId===e);a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.mediaTrack||this.kind===h.AUDIO&&!su(this.mediaTrack)||this.kind===h.VIDEO&&!ru(this.mediaTrack)||this._isRecapturing||e&&bt&&Ue)}onTrackMuted(){if(super.onTrackMuted(),cu(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<mr){setTimeout(()=>this.onTrackMuted(),mr);return}this._onMuteTimeoutId=setTimeout(()=>_(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((We||pe)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return _(this,null,function*(){if(Ie(Sc.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<mr){setTimeout(()=>this.onTrackEnded(),mr);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return _(this,null,function*(){var s;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),(s=this._inputTrack)==null||s.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let t={useExactDeviceId:!0};if(e==="user"||e==="environment")t.facingMode=e;else{let o;(this.kind==="audio"?yield Be():yield Xe()).find(a=>a.deviceId===e)&&(o=e),t.deviceId=o}return this.capture(t).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),g.emit(E.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(o=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${o.message}`),this.emit("5",o),g.emit(E.LOCAL_TRACK_RECAPTURE,{track:this,error:o})})})}getRecoverCaptureDeviceId(){return _(this,null,function*(){let e=this instanceof ue;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let s=(Qs.get(t)||0)+1;if(Qs.set(t,s),s>=3){let o=e?(yield Xe()).find(n=>!Qs.has(n.deviceId)):(yield Be()).find(n=>!Qs.has(n.deviceId));o&&(this.log.warn(`${t} capture fail ${s} times, change new ${o.deviceId}`),t=o.deviceId)}}return t})}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),(e=this.manager)==null||e.removeInput(this)}},Qe=Sc;y([le(F.INIT,"capture",{ignoreError:!0,sync:!0})],Qe.prototype,"setStateToCapture",1),y([Ft()],Qe.prototype,"capture",1),y([le("capture","publish",{ignoreError:!0,success(){this.room.localTracks.add(this),g.emit(E.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this._encodeCheckTimeoutId=setTimeout(()=>{if(this.isPublished&&this.isMediaTrackActive){let r=this.stat.bytesSent>0;D[r?"addSuccessEvent":"addFailedEvent"]({key:this.kind===h.AUDIO?503700:513702}),r||(this.log.warn("encode failed"),this.emit("6",this))}},5e3)},fail(r){let i="error",e=r.cause;e.message.includes("timeout")?i="timeout":e.code===A.API_CALL_ABORTED&&(i="api-call"),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:i,error:e})}})],Qe.prototype,"publish",1),y([W(r=>function(){return _(this,null,function*(){let i=this.state==="publish"?"started":"starting";r.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:i,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),le([],"capture",{sync:!0})],Qe.prototype,"unpublish",1);var Qs=new Map;g.on(E.SWITCH_DEVICE_SUCCESS,r=>{r.track.deviceId&&Qs.delete(r.track.deviceId)});var Oe=class extends Qe{constructor(e){super(1,Sn);l(this,"mediaType",1);l(this,"volume",0);l(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});l(this,"playerMuted",!0);l(this,"pipeline");l(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});this.manager=e,this.pipeline=new xr(e),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}get playerMediaTrack(){return this.mediaTrack}setInputMediaStreamTrack(e){return _(this,null,function*(){yield Ie(Oe.prototype,this,"setInputMediaStreamTrack").call(this,e);let t=this.trackSettings||{};D.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),D.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),D.addEnum({key:502700,value:0});let{sampleRate:s,channelCount:o}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:s,channelCount:o})}`),this.pipeline.source.channelCount=o||1,this.pipeline.replaceSource(e),this.updatePlayingState(!!e)})}capture({deviceId:e,customSource:t,useExactDeviceId:s=!1}){return super.capture({video:!1,audio:!0,microphoneId:e,echoCancellation:this.profile.echoCancellation,autoGainControl:this.profile.autoGainControl,noiseSuppression:this.profile.noiseSuppression,sampleRate:this.profile.sampleRate,channelCount:this.profile.channelCount,useExactDeviceId:s,customSource:t})}switchDevice(e){return _(this,null,function*(){if(!!this.mediaTrack){if(this.deviceId===e)if(e===Ui){if(yield gc(this.groupId,this.label))return}else return;try{this.log.info(`switchDevice audio to: ${e}`),this.mediaTrack&&this.mediaTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0}),this.room&&(yield this.room.replaceTrack(this)),g.emit(E.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(t){throw this.log.error(`switch microphone failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}}})}listenDeviceChange(){ge&&!ge.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&ge.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return _(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current microphone is lost: ${JSON.stringify(e)}`),ae(this.userId,{eventId:2003,param1:6,streamType:1});let t=yield Be();t[0]?this.recapture(t[0].deviceId):ge.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(o){return _(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:s}){let n=!1;!T(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,n=!0),!T(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,n=!0),!T(s)&&s!==this.profile.autoGainControl&&(this.profile.autoGainControl=s,n=!0),n&&this.deviceId&&(yield this.recapture(this.deviceId))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&D.addEnum({key:502700,value:2}),this.resetPlayerSource()}enableTrackANS(e){if(!this._inputTrack)return;let t=this._inputTrack.getConstraints();return t.noiseSuppression=e,this._inputTrack.applyConstraints(t).catch(s=>this._log.warn(`${e?"enable":"disable"} ANS failed `,s))}addDenoiser(e){var t;if(mt<=92&&((t=this.trackSettings)==null?void 0:t.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}D.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.resetPlayerSource(),this.enableTrackANS(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.resetPlayerSource(),this.enableTrackANS(!0))}resetPlayerSource(){this.player.setSourceNode(this.pipeline.gain.node||this.pipeline.denoiser.node||this.pipeline.source.node)}close(){this.pipeline.remove(),ge.off("audioInputAdded",this.handleMicrophoneAdded,this),ge.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return _(this,null,function*(){try{yield Ie(Oe.prototype,this,"recapture").call(this,e)}catch(t){let s=(yield Be()).find(o=>o.deviceId!==e);if(s)yield Ie(Oe.prototype,this,"recapture").call(this,s.deviceId);else throw t}})}};var Di=class{constructor(i,e=!1){this.dataView=i;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-2,t=[],s=0;for(let n=i;n<=e;n++){let a=this.dataView.getInt8(n);switch(a){case 0:case 1:case 2:case 3:s===2&&(t.push(3),s=0),a==0?s++:s=0,t.push(a);break;default:s=0,t.push(a);break}}t.push(this.dataView.getInt8(this.dataView.byteLength-1));let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=o}removePreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,t=[],s=0;for(let n=i;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:s++,t.push(this.dataView.getInt8(n));break;case 3:s!==2&&t.push(this.dataView.getInt8(n)),s=0;break;default:t.push(this.dataView.getInt8(n)),s=0;break}let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=o}get isSEI(){return this.dataView.getUint8(4)===6}get seiPayloadStartIndex(){let i=6;for(let e=6;e<this.dataView.buffer.byteLength&&(i++,this.dataView.getUint8(e)===255);e++);return i}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let i=0,e=6;for(let o=6;o<this.dataView.buffer.byteLength;o++){let n=this.dataView.getUint8(o);if(e++,n===255)i+=255;else{i+=n;break}}let t=new ArrayBuffer(i),s=new DataView(t);for(let o=0;o<t.byteLength;o++,e++)s.setInt8(o,this.dataView.getInt8(e));return s}};var bn=class{constructor(){l(this,"_seiMessageList",[]);l(this,"_smallSeiMessageList",[]);l(this,"_seiPayloadType",243)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),s=e%255,o=[];o.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)o.push(255);o.push(s);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Di(new DataView(new Uint8Array(o).buffer),!0)}sendSEI(i,e){e!=null&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(i),e!=null&&e.small&&this._smallSeiMessageList.push(i)}getNaluCount(i){let e=0,t=0,s=new DataView(i);for(let o=0;o<i.byteLength;o++)switch(s.getUint8(o)){case 0:e++;break;case 1:(e===2||e===3)&&t++,e=0;break;default:e=0;break}return t}encode(i,e){let t=e?this._smallSeiMessageList:this._seiMessageList;if(t.length>0&&i.data.byteLength>0){let s=this.getNaluCount(i.data),o=9-s;if(o<=0)return 0;let n=t.splice(0,o).reverse().map(this.encodeSEINalu.bind(this)),a=n.reduce((m,f)=>m+f.dataView.byteLength,0),c=new ArrayBuffer(a+i.data.byteLength),d=new DataView(c),u=new DataView(i.data),p=0;for(let m=0;m<n.length;m++)for(let f=0;f<n[m].dataView.byteLength;f++)d.setInt8(p++,n[m].dataView.getInt8(f));for(let m=0;m<i.data.byteLength;m++)d.setInt8(p++,u.getInt8(m));return i.data=c,n.length}return 0}};var ue=class extends Qe{constructor(e,t=4){super(t,je);l(this,"profile",{width:640,height:480,frameRate:15,bitrate:500});l(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0});l(this,"small");l(this,"isNeedToSetBandwidth");l(this,"muteImage");l(this,"manager");l(this,"_seiCodec",new bn);l(this,"pipeline",[]);this.manager=e;let s=()=>{this.isAllowed2k4k(this.profile)?this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),this.setProfile(P(N({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",s),this.on("publish",s),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!Pt||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}setMute(e){return _(this,null,function*(){var t,s,o;if(z(e)){if(this.muteImage===e)return;yield(t=this.manager)==null?void 0:t.deleteWatermark("mute"),yield(s=this.manager)==null?void 0:s.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e}),this.muteImage=e,Ie(ue.prototype,this,"setMute").call(this,!1)}else yield(o=this.manager)==null?void 0:o.deleteWatermark("mute"),this.muteImage=void 0,Ie(ue.prototype,this,"setMute").call(this,e)})}capture({deviceId:e,facingMode:t,useExactDeviceId:s=!1,customSource:o}){return super.capture({audio:!1,video:!0,facingMode:t||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:s,customSource:o})}setProfile(e){let t=N({},e),s=t.width>t.height;t.width*t.height<=160*120&&pe&&Pe&&(this.log.warn(`resolution is ${t.width}*${t.height}, fallback to 240*180`),t.width=s?240:180,t.height=s?180:240,t.bitrate=Math.max(t.bitrate,150)),t.width*t.height>1280*720&&wa&&(t.width=s?1280:720,t.height=s?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),t.bitrate&&(this.isNeedToSetBandwidth=t.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(t):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(P(N({},this.profile),{width:1920,height:1080})))}applyProfile(){var s;if(!this.mediaTrack)return;let e=this.settings;if(e.height!==this.profile.height||e.width!==this.profile.width||e.frameRate!==this.profile.frameRate)return(s=this.mediaTrack)==null?void 0:s.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}).then(()=>{if(this.manager&&this.manager.changeInput(this),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth)return this.isNeedToSetBandwidth=!1,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:h.VIDEO,videoType:h.BIG})})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return Pt&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e}get scaleResolutionDownBy(){let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:ja()&&this.profile.width>this.profile.height&&e.height>e.width?Math.max(e.width/this.profile.height,e.height/this.profile.width,1):Math.max(e.width/this.profile.width,e.height/this.profile.height,1)}isAllowed2k4k(e){var t;return!this.room||!this.room.scheduleResult||this.isScreen||e.height*e.width<2560*1440?!0:((t=this.room.scheduleResult.trtcAutoConf)==null?void 0:t["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return _(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e))return;let t={useExactDeviceId:!0};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),g.emit(E.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(t){throw this.log.error(`switch camera failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}})}listenDeviceChange(){ge&&!ge.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&ge.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return _(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current camera is lost: ${JSON.stringify(e)}`),ae(this.userId,{eventId:2003,param1:7,streamType:2});let t=yield Xe();t[0]?this.recapture(t[0].deviceId):ge.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return _(this,null,function*(){this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}encodeFrame(e,t){let s=t?8:this.mediaType;return this.pipeline.reduce((o,n)=>n?n(o,s):o,e)}get enableEncodeFrame(){return this.pipeline.some(e=>e)}play(e,t){return _(this,null,function*(){return T(this.mirror)&&!this.isScreen&&this.setMirror("view"),Ie(ue.prototype,this,"play").call(this,e,t)})}close(){ge.off("videoInputAdded",this.handleCameraAdded,this),ge.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return _(this,null,function*(){try{yield Ie(ue.prototype,this,"recapture").call(this,e)}catch(t){let s=(yield Xe()).find(o=>o.deviceId!==e);if(s)yield Ie(ue.prototype,this,"recapture").call(this,s.deviceId);else throw t}})}};var mu=ks();if(navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:mu,exposeOrigin:!0,permittedOrigins:["*"]})}catch(r){}var Wp=function(r){return _(this,null,function*(){let i=null,e=qp(r);I.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);r.systemAudio&&t.getAudioTracks().length===0&&(Ar&&mt<74||Ue||ie)&&I.warn("Your browser not support capture system audio");let s=t.getVideoTracks()[0];if(s){if(r.frameRate)try{yield s.applyConstraints({frameRate:{min:r.frameRate,ideal:r.frameRate},width:r.width,height:r.height})}catch(o){I.warn(`screen applyConstraints failed: ${o}`)}r.captureElement&&(yield Jp(s,r.captureElement))}if(r.audio){let o=jp(r);I.info(`getUserMedia with constraints: ${JSON.stringify(o)}`),i=yield navigator.mediaDevices.getUserMedia(o),t.addTrack(i.getAudioTracks()[0])}return t})};function Jp(r,i){return _(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&K(r.cropTo))try{if(!(((e=r.getCaptureHandle())==null?void 0:e.handle)===mu))return;let s=yield CropTarget.fromElement(i);yield r.cropTo(s)}catch(t){I.warn(`cropTo target failed ${t}`)}})}function jp(r){let i={echoCancellation:r.echoCancellation,autoGainControl:r.autoGainControl,noiseSuppression:r.noiseSuppression,sampleRate:r.sampleRate,channelCount:r.channelCount};return T(r.microphoneId)||(i.deviceId=r.microphoneId),{audio:i,video:!1}}function qp(r){let i={preferCurrentTab:r.preferDisplaySurface==="current-tab"||!!r.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Ue?{max:r.width}:{ideal:r.width,max:r.width},height:Ue?{max:r.height}:{ideal:r.height,max:r.height},frameRate:r.frameRate,displaySurface:r.preferDisplaySurface||"monitor"};if(i.video=e,r.systemAudio){let{echoCancellation:t=!0,noiseSuppression:s=!1,autoGainControl:o=!1}=r;i.audio={echoCancellation:t,noiseSuppression:s,autoGainControl:o,sampleRate:48e3}}return i}var pu=Wp;var ze=class extends ue{constructor(e){super(e,2);l(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});l(this,"objectFit","contain");l(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(u){return _(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:s,noiseSuppression:o,audioTrack:n,videoTrack:a,captureElement:c,preferDisplaySurface:d}){try{let p;return a||n?(p=new MediaStream,a&&p.addTrack(a),n&&p.addTrack(n)):p=yield pu({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:s,noiseSuppression:o,captureElement:c,preferDisplaySurface:d}),yield this.setInputMediaStreamTrack(p.getVideoTracks()[0]),p}catch(p){throw this.log.error(`getDisplayMedia error observed ${p}`),p instanceof b?p:new b({code:A.INITIALIZE_FAILED,name:p.name,message:p.message})}})}switchDevice(e){return _(this,null,function*(){throw new Error("Method not implemented.")})}};var Ht=class extends Oe{constructor(i){super(i),this._log.id=`s-${this._log.id}`}};var Xp="registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});",Ic;function Ac(r){return _(this,null,function*(){let i=qe("dump");Ic||(Ic=Ji(i,URL.createObjectURL(new Blob([Xp],{type:"application/javascript"})))),yield Ic;let e=new AudioWorkletNode(i,"dumper",{numberOfInputs:r.length,numberOfOutputs:0});return r.forEach((t,s)=>t.connect(e,0,s)),new ReadableStream({start(t){e.port.onmessage=s=>{t.enqueue(s.data)}},cancel(){r.forEach(t=>t.disconnect(e)),e.port.close()}})})}var w={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},rt=(S=>(S[S.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",S[S.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",S[S.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",S[S.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",S[S.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",S[S.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",S[S.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",S[S.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",S[S.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",S[S.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",S[S.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",S[S.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",S[S.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",S[S.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",S[S.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",S[S.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",S[S.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",S[S.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",S[S.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",S[S.INVALID_OPERATION=5100]="INVALID_OPERATION",S[S.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",S[S.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",S[S.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",S[S.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",S[S.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",S[S.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",S[S.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",S[S.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",S[S.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",S[S.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",S[S.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",S[S.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",S[S.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",S[S.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",S[S.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",S[S.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",S[S.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",S[S.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",S[S.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",S[S.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",S[S.DEVICE_ERROR=5300]="DEVICE_ERROR",S[S.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",S[S.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",S[S.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",S[S.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",S[S.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",S[S.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",S[S.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",S[S.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",S[S.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",S[S.SERVER_ERROR=5400]="SERVER_ERROR",S[S.NEED_TO_BUY=5401]="NEED_TO_BUY",S[S.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",S[S.OPERATION_FAILED=5500]="OPERATION_FAILED",S[S.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",S[S.REJOIN_FAILED=5502]="REJOIN_FAILED",S[S.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",S[S.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",S[S.OPERATION_ABORT=5998]="OPERATION_ABORT",S[S.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",S))(rt||{});var Nn=class extends fn{constructor(e){super();this.room=e;l(this,"_localAudioTrack");l(this,"_localScreenAudioTrack");l(this,"log",I.createLogger({id:"am"}));l(this,"denoiser");e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId))}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}dump(e){var u,p;if(!this._localAudioTrack)return;let t=[],s=[];(u=this._localAudioPipline)!=null&&u.source.node&&(t.push(this._localAudioPipline.source.node),s.push("mic")),(p=this._localAudioPipline)!=null&&p.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),s.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),s.push("mix")),this.log.info(`dump audio track ${s}, duration: ${e}`);let o=new AbortController,n=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),o.abort("timeout")},e*1e3),c=()=>{for(let m=0;m<s.length;m++){let f=URL.createObjectURL(new Blob(n[m])),R=document.createElement("a");R.href=f,R.download=`${s[m]}.pcm`,R.style.display="none",document.body.appendChild(R),R.click(),URL.revokeObjectURL(f),R.remove()}clearTimeout(a),o.abort("download")},d=Ac(t).then(m=>m.pipeTo(new WritableStream({write(f){f.forEach((R,C)=>n[C]=n[C]?n[C].concat(R[0]):[R[0]])}}),o).catch(f=>c));return{then:d.then.bind(d),download:c}}getPCM(e){var o;if(typeof WritableStream=="undefined")throw new b({code:A.INVALID_OPERATION,extraCode:5200,message:"browser not support WritableStream"});let t=new Float32Array(1920),s=0;if((o=this._localAudioPipline)!=null&&o.source.node){let n=new AbortController;return Ac([this._localAudioPipline.source.node]).then(a=>a.pipeTo(new WritableStream({write(c){t.set(c[0][0],s),s+=c[0][0].length,s>=1920&&(s=0,e(t),t=new Float32Array(1920))}}),n)),n}throw new b({code:A.INVALID_OPERATION,extraCode:5106,message:"please startLocalAudio first"})}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return this._localAudioTrack!==null}changeInput(e){if(e instanceof Ht)this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();else if(e instanceof Oe)this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();else if(e instanceof ni)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixOnChange(){var e,t;(e=this._localAudioTrack)==null||e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null||t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)}removeInput(e){e instanceof Ht?delete this._localScreenAudioTrack:e instanceof Oe?delete this._localAudioTrack:e instanceof ni}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}removeDenoiser(e){var t;delete this.denoiser,(t=this._localAudioTrack)==null||t.removeDenoiser(e)}destroy(){this.close()}};function vn(r=30,i=2){return W((e,t)=>function(...s){return new Promise((o,n)=>{let a=setTimeout(()=>{let c=new b({code:A.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${r}s`});I.warn(c),i===2?n(c):i===1&&o()},r*1e3);e.apply(this,s).then(o,n).finally(()=>{clearTimeout(a)})})})}var Cc=class extends Qi{constructor(e,t,s){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:s,room:e});this.room=e;this.user=t;l(this,"tinyId");l(this,"isRemote",!0);l(this,"jitterBufferDelay",0);l(this,"_decodeCheckTimeoutId",-1);this.tinyId=t.tinyId}setMute(e){this.hasFlag&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.hasFlag&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===Cc.STATE_SUBSCRIBE}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.hasFlag||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} hasFlag: ${this.hasFlag} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}onFlagChanged(){this.updatePlayingState(this.hasFlag)}onTrackMuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackMuted()}onTrackUnmuted(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackUnmuted()}onTrackEnded(){this.hasFlag&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackEnded()}},st=Cc;l(st,"STATE_SUBSCRIBE","subscribe"),y([vn(5,1)],st.prototype,"waitHasMediaTrack",1),y([le(F.INIT,st.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),g.emit(E.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0),this._decodeCheckTimeoutId=setTimeout(()=>{if(this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived>0){let r=this.player.isPlaying||(this.kind===h.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0);D[r?"addSuccessEvent":"addFailedEvent"]({key:this.kind===h.AUDIO?504700:514702}),r||this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===h.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`} )`)}},5e3)},ignoreError:!0})],st.prototype,"subscribe",1),y([le(st.STATE_SUBSCRIBE,F.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),g.emit(E.REMOTE_TRACK_UNSUBSCRIBED,{track:this}),clearTimeout(this._decodeCheckTimeoutId)}})],st.prototype,"unsubscribe",1);var ni=class extends st{constructor(e,t){super(e,t,1);l(this,"volume",0);l(this,"mediaType",1);l(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});l(this,"audioDecoder");this.manager=e.audioManager}onPlayerError(e){if(this.enableDecodeFrame){this.room.enableInsertableStreams();let t=new AudioDecoder({error:s=>this._log.error(s),output:s=>{this.player.write(s)}});t.configure({codec:"opus",sampleRate:48e3,numberOfChannels:1}),this._log.info(`audioDecoder state:${t.state}`),this.audioDecoder=t}}get enableDecodeFrame(){var e,t;return((t=(e=this.player.element)==null?void 0:e.error)==null?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&Gi&&an().AudioDecoder}decodeFrame(e){var t;return((t=this.audioDecoder)==null?void 0:t.state)==="configured"&&this.audioDecoder.decode(new EncodedAudioChunk({data:e.data,timestamp:e.timestamp,type:"key"})),e}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get hasFlag(){return this.user.muteState.hasAudio}isFlagChanged(e){let t=e.hasAudio&&!e.audioMuted;return this.hasFlag||(this.volume=0),this.hasFlag!==t}};var zp=[-1,-1,1,-1,-1,1,1,1],Yp=[0,0,1,0,0,1,1,1],Ye=class extends F{constructor(e,t){super();this.context=e;l(this,"name");l(this,"input");l(this,"output");l(this,"texture");l(this,"ctx2d",null);l(this,"fbo");l(this,"width",0);l(this,"height",0);l(this,"x",0);l(this,"y",0);l(this,"program");l(this,"vertexShader");l(this,"fragmentShader");l(this,"totalFrames",0);l(this,"dropFrames",0);l(this,"matchInputSize",!0);l(this,"texCoordBuffer");l(this,"positionBuffer");l(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});l(this,"cost",0);l(this,"_canvas",null);l(this,"_image");if(this.context.on("disconnect",this.close,this),this.name=t.name,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof Fe){if(e.ctx&&t.create2d){let s=document.createElement("canvas"),o=typeof s.transferControlToOffscreen=="function"?s.transferControlToOffscreen():s;o.width=this.width,o.height=this.height,this.ctx2d=o.getContext("2d"),this._image=o,this._canvas=o}return}try{let s=e.ctx;this.texCoordBuffer=this.createBuffer(Yp),this.positionBuffer=this.createBuffer(zp),t.createTexture!==!1&&(this.texture=s.createTexture(),this.useTexture(),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.pixelStorei(s.PACK_ALIGNMENT,1),s.pixelStorei(s.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=s.createFramebuffer(),this.useBufferFrame(),this.useTexture(),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,this.width,this.height,0,s.RGBA,s.UNSIGNED_BYTE,null),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(s.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(s.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(s){this.context.destroy(s)}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,s=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),s}connect(e,...t){return e.addInput(this,...t),this.output=e,e}addInput(e,...t){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();if(this.context instanceof ye&&this.render(e)||this.context instanceof Fe&&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}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 ye){let s=this.context.ctx;s.deleteBuffer(this.texCoordBuffer),s.deleteBuffer(this.positionBuffer),this.fbo&&s.deleteFramebuffer(this.fbo),this.texture&&s.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&s.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&s.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&s.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let t=this.context.ctx;e.forEach((s,o)=>{s&&(t.activeTexture(t.TEXTURE0+o),t.bindTexture(t.TEXTURE_2D,s))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,s=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,s),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),s}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let s=this.context.ctx;s.bindBuffer(s.ARRAY_BUFFER,e),s.bufferData(s.ARRAY_BUFFER,new Float32Array(t),s.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((s,o)=>{t.enableVertexAttribArray(o),t.bindBuffer(t.ARRAY_BUFFER,s),t.vertexAttribPointer(o,2,t.FLOAT,!1,0,0)})}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(!(this.width===e&&this.height===t)){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let s=this.context.ctx;s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,s.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let s=this.context.ctx;s.drawArrays(s.TRIANGLE_STRIP,0,4)}draw2d(e,t,s,o,n){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,t,s):this.ctx2d.drawImage(e,t,s,o,n),!0):!1}getInfo(){var p;let{totalFrames:e,x:t,y:s,width:o,height:n,name:a,cost:c}=this,d=Date.now(),u=(e-this.lastInfo.totalFrames)/((d-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:s,width:o,height:n,timestamp:d,fps:u,name:a,cost:c},N({parent:(p=this.input)==null?void 0:p.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,s=t.createTexture();return this.useTextures(s),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),s}};y([le(F.INIT,"connected",{sync:!0})],Ye.prototype,"connect",1),y([le("connected",F.INIT,{ignoreError:!0,sync:!0})],Ye.prototype,"disconnect",1),y([le([],"closed",{sync:!0})],Ye.prototype,"close",1);var Kp=[0,1,1,1,0,0,1,0],zs=class extends Ye{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));l(this,"_intervalId",0);l(this,"_sequence",0);l(this,"checkGLError",!1);e instanceof Fe?this.ctx2d=e.ctx:e.available&&(t==null?void 0:t.mirrorUpAndDown)&&this.setTexBuffer(Kp)}start(e){this._intervalId=re.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(re.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof ye){let s=this.context.ctx.getError();s&&this.context.destroy(new Error(`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${s}`))}},{fps:this.context.frameRate})}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}removeInput(e){super.removeInput(e),re.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}},Vr=class extends zs{constructor(e,t){super(e,t);l(this,"_videoTrack");l(this,"_canvasContainer");Number(Si)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks();let s=o=>{var c;let n=()=>{var d;return(d=this._videoTrack)==null?void 0:d.removeEventListener(o,a)},a=()=>{n(),this.context.destroy(new Error(`video track ${o}`))};this.once("closed",n),(c=this._videoTrack)==null||c.addEventListener(o,a)};e instanceof ye&&s("mute"),s("ended")}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(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()}},Dn=class extends Vr{render(i){var e;return!!((e=this.input)!=null&&e.requestFrame(i))}};var On=class extends Vr{constructor(e,t){super(e,{name:"smallDestination"});this.resolution=t}resize(e,t){let s,o=e*t,n=this.resolution.width*this.resolution.height;I.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),o>n?s=o/n:(I.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${t} small: ${this.resolution.width} * ${this.resolution.height}`),s=o/(160*120)),super.resize(e/Math.sqrt(s),t/Math.sqrt(s))}};var Ys=class extends Ye{constructor(e,t){super(e,N({name:"imageSource"},t));l(this,"_lastImage");l(this,"_totalFrames",0);l(this,"_autoResize",!1);this._autoResize=(t==null?void 0:t.autoResize)!==!1}_render(e,t){var n,a;let{width:s,height:o}=this;if(this.image instanceof HTMLVideoElement){if(K(this.image.getVideoPlaybackQuality)&&Pe){let d=this.image.getVideoPlaybackQuality().totalVideoFrames;if(((a=(n=this.image.srcObject)==null?void 0:n.getVideoTracks()[0])==null?void 0:a.muted)===!0||this._totalFrames===d)return!1;this._totalFrames=d,this.dropFrames=this._totalFrames-this.totalFrames}if({videoWidth:s,videoHeight:o}=this.image,!s||!o)return!1;this.image.width=s,this.image.height=o}else if(this.image instanceof HTMLImageElement||this.image instanceof ImageData||this.image instanceof ImageBitmap){if({width:s,height:o}=this.image,this.image!==this._lastImage)this._lastImage=this.image;else if(s===this.width&&o===this.height)return!1}else(this.image instanceof HTMLCanvasElement||this.image instanceof OffscreenCanvas)&&({width:s,height:o}=this.image,this._lastImage=this.image);if(!this._autoResize)return!0;if(this.width===s&&this.height===o&&this.totalFrames){if(t){this.useTexture();let c=this.context.ctx;c.texSubImage2D(c.TEXTURE_2D,0,0,0,c.RGBA,c.UNSIGNED_BYTE,this.image)}}else{if(t){this.useTexture();let c=this.context.ctx;c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,this.image)}this.resize(s,o)}return!0}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},Ks=class extends Ys{constructor(e,t,s){super(e,s);this._player=t;this.name="videoPlayerSource"}get image(){return this._player.element}},Ur=class extends Ks{constructor(i,e,t){super(i,new je({id:t.name,track:e,muted:!0,container:null,objectFit:"contain",log:t.logger}),t),this.name="videoTrackSource",this._player.play()}get image(){return this._player.element}replaceTrack(i){this._player.setTrack(i),this._player.play()}close(){super.close(),this._player.stop()}};var Zp=`
|
|
44
44
|
// \u9876\u70B9\u7740\u8272\u5668
|
|
45
45
|
attribute vec4 a_position;
|
|
46
46
|
attribute vec2 a_texCoord;
|
|
@@ -58,22 +58,22 @@ uniform sampler2D u_texture;
|
|
|
58
58
|
|
|
59
59
|
void main() {
|
|
60
60
|
gl_FragColor = texture2D(u_texture, v_texCoord);
|
|
61
|
-
} `,Xi=class extends F{constructor(e){super();u(this,"frameRate");u(this,"_canvas");u(this,"log");u(this,"hasAlpha",!1);u(this,"name");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}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 wr(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new Pr(this,e)}createVideoImageSource(e,t){return new zs(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new Ys(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};u(Xi,"_ids",0);var t_={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},ye=class extends Xi{constructor(){super(...arguments);u(this,"defaultProgam");u(this,"defaultVShader");u(this,"defaultFShader");u(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Xi._ids++}`),this.ctx=this._canvas.getContext("webgl2",t_),!this.ctx)throw new Error("webgl2 not supported");this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,Zp),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,e_),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new Error("webgl context lost"))}),this.log.info("video context created use webgl")}destroy(e){return this.disconnect(),this.log.info(`video context destroy ${e?`: ${e}`:""}`),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}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var s;(s=this.ctx)==null||s.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let s=this.ctx,o=s.createShader(e);return s.shaderSource(o,t),s.compileShader(o),o}createProgram(e,t){let s=this.ctx,o=s.createProgram();return s.attachShader(o,e),s.attachShader(o,t),s.linkProgram(o),s.getProgramParameter(o,s.LINK_STATUS)||this.log.error(s.getProgramInfoLog(o)),o}};y([ue(F.INIT,"created",{sync:!0})],ye.prototype,"create",1),y([ue("created",F.INIT,{ignoreError:!0,sync:!0,success(r){r&&this.emit("unavailable",r),this.removeAllListeners()}})],ye.prototype,"destroy",1);var Fe=class extends Xi{constructor(){super(...arguments);u(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Xi._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new Error("2d context not supported");this.log.info("video context created use 2d")}destroy(e){this.disconnect(),this.log.info(`video context destroy ${e?`: ${e}`:""}`),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners()}};y([ue(F.INIT,"created",{sync:!0})],Fe.prototype,"create",1),y([ue("created",F.INIT,{ignoreError:!0,sync:!0})],Fe.prototype,"destroy",1);function i_(r){return[15,30,45,60].reduce((e,t)=>Math.abs(t-r)<Math.abs(e-r)?t:e)}var Tt=class extends rt{constructor(e,t,s=4){super(e,t,s);u(this,"mediaType",4);u(this,"source");u(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});u(this,"pipeline",[]);this.manager=e.videoManager}play(e,t){return(de(t==null?void 0:t.canvasRender)?t.canvasRender:Ss===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t)}useCanvasPlayer(){if(this.log.info(`useCanvasPlayer(), ${!!this.player.element}`),!this.player.element)return;let e=new Fe({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=e.createVideoPlayerSource(this.player);this.source=t;let s=new Qs(e);t.connect(s),this.player.setCanvas(e._canvas),this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this)}updateCanvasPlayerFPS(e){let t=this.decodeFPS,s=i_(t);if(!ee(t)||t<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${t} `);return}if(s===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${s} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${t}, closest: ${s}, current: ${e.frameRate}`),e.frameRate=s}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 s=e.find(a=>a.uint32_video_stream_type===t);return(s==null?void 0:s.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),super.stop()}get enableDecodeFrame(){return this.manager.configPipeline(this),this.pipeline.some(e=>e)}decodeFrame(e){return this.pipeline.reduce((t,s)=>s?s(t,this):t,e)}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get hasFlag(){return this.user.muteState.hasVideo&&!this.user.muteState.videoMuted}isFlagChanged(e){let t=e.hasVideo&&!e.videoMuted;return this.hasFlag!==t}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}},Vr=class extends Tt{constructor(e,t){super(e,t,2);u(this,"mediaType",2);u(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let t=e.hasAuxiliary;return this.hasFlag!==t}};function Te(...r){}var r_=r=>r();function Cc(){this.dispose()}var s_=()=>typeof __FASTRX_DEVTOOLS__!="undefined",o_=1,ni=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new Ac(i,this,this.streamId++);return St.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},Ks=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=Te,this.error=Te,this.next=Te,this.dispose=Te,this.subscribe=Te,this.doDefer()}subscribe(i){return i instanceof ni?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(r_),this.defers.clear()}defer(i){this.defers.add(i)}removeDefer(i){this.defers.delete(i)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},H=class extends Ks{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)}};function _l(r,...i){return i.reduce((e,t)=>t(e),r)}function ai(r,i,e){if(s_()){let t=Object.defineProperties(Object.setPrototypeOf(r,ni.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}});St.create(t);for(let s=0;s<e.length;s++){let o=e[s];typeof o=="function"&&o instanceof ni&&St.addSource(t,o)}return t}return r}function j(r,i){return function(...e){return t=>{if(t instanceof ni){let s=ai(o=>{let n=new r(o,...e);n.sourceId=s.id,n.subscribe(t)},i,arguments);return s.source=t,St.pipe(s),s}else return s=>t(new r(s,...e))}}}function vi(r,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:r,payload:i}})}var Ac=class extends H{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{St.defer(this.source,this.id)})}next(i){St.next(this.source,this.id,i),this.sink.next(i)}complete(){St.complete(this.source,this.id),this.sink.complete()}error(i){St.complete(this.source,this.id,i),this.sink.error(i)}},St={addSource(r,i){vi("addSource",{id:r.id,name:r.toString(),source:{id:i.id,name:i.toString()}})},next(r,i,e){vi("next",{id:r.id,streamId:i,data:e&&e.toString()})},subscribe({id:r,end:i},e){vi("subscribe",{id:r,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(r,i,e){vi("complete",{id:r.id,streamId:i,err:e?e.toString():null})},defer(r,i){vi("defer",{id:r.id,streamId:i})},pipe(r){vi("pipe",{name:r.toString(),id:r.id,source:{id:r.source.id,name:r.source.toString()}})},update(r){vi("update",{id:r.id,name:r.toString()})},create(r){r.id||(r.id=o_++),vi("create",{name:r.toString(),id:r.id})}},Mn=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var Rc=class extends Ks{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 kn(){return r=>{let i=new Rc(r);if(r instanceof ni){let e=ai(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=r,St.pipe(e),e}return ai(i.add.bind(i),"share",arguments)}}function n_(...r){return ai(i=>{let e=r.length,t=e,s=e,o=new Array(e),n=()=>{--s===0&&i.complete()},a=(c,d)=>{let l=new H(i);l.next=p=>{--t===0?(l.next=m=>{o[d]=m,i.next(o)},l.next(p)):o[d]=p},l.complete=n,l.subscribe(c)};r.forEach(a)},"combineLatest",arguments)}var yc=class extends H{constructor(i,...e){super(i);let t=new H(this.sink);t.next=s=>this.buffer=s,t.complete=Te,t.subscribe(n_(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},XA=j(yc,"withLatestFrom"),bc=class extends H{constructor(i,e,t){super(i),this.bufferSize=e,this.startBufferEvery=t,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(i){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(i)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(i),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(i=>this.sink.next(i)),super.complete()}},QA=j(bc,"bufferCount"),Nc=class extends H{constructor(i,e){super(i),this.buffer=[];let t=new H(i);t.next=s=>{i.next(this.buffer),this.buffer=[]},t.complete=Te,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},zA=j(Nc,"buffer");function vc(r){let i=arguments,e=kn()(ai(t=>{e.next=s=>t.next(s),e.complete=()=>t.complete(),e.error=s=>t.error(s),r&&t.subscribe(r)},"subject",i));return e.next=Te,e.complete=Te,e.error=Te,e}function fl(r){return ai(i=>{let e=0,t=setInterval(()=>i.next(e++),r);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}var Dc=class extends H{constructor(i,e,t){super(i),this.f=e;let s=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=o=>{this.acc=o,this.complete=s,this.resetNext()}:(this.acc=t,this.complete=s)}next(i){this.acc=this.f(this.acc,i)}},a_=j(Dc,"reduce");var Oc=class extends H{constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},c_=j(Oc,"filter"),Mc=class extends H{next(i){}},aC=j(Mc,"ignoreElements"),kc=class extends H{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&this.complete()}},d_=j(kc,"take"),Lc=class extends H{constructor(i,e){super(i);let t=new H(i);t.next=()=>i.complete(),t.complete=Cc,t.subscribe(e)}},cC=j(Lc,"takeUntil"),xc=class extends H{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):this.complete()}},u_=j(xc,"takeWhile");var Pc=class extends H{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},dC=j(Pc,"skip"),wc=class extends H{constructor(i,e){super(i),i.next=Te;let t=new H(i);t.next=()=>{t.dispose(),i.resetNext()},t.complete=Cc,t.subscribe(e)}},uC=j(wc,"skipUntil"),Vc=class extends H{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},l_=j(Vc,"skipWhile"),h_={leading:!0,trailing:!1},Uc=class extends H{constructor(i,e,t){super(i),this.durationSelector=e,this.trailing=t}cacheValue(i){this.last=i,this.disposed&&this.throttle(i)}send(i){this.sink.next(i),this.throttle(i)}throttle(i){this.reset(),this.subscribe(this.durationSelector(i))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},Bc=class extends H{constructor(i,e,t=h_){super(i),this.durationSelector=e,this.config=t,this._throttle=new Uc(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=Te,this._throttle.complete(),super.complete()}},lC=j(Bc,"throttle");var $c=class extends H{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Fc=class extends H{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new $c(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()}},hC=j(Fc,"debounce");var Hc=class extends H{constructor(i,e,t){super(i),this.count=e,this.defaultValue=t}next(i){this.count--===0&&(this.defaultValue=i,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("not enough elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},mC=j(Hc,"elementAt");var Gc=class extends H{constructor(i,e){super(i),this.f=e,this.i=0}next(i){this.f(i)?(this.sink.next(this.i++),this.complete()):++this.i}},pC=j(Gc,"findIndex"),Wc=class extends H{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},_C=j(Wc,"first"),Jc=class extends H{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i)}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},fC=j(Jc,"last"),jc=class extends H{constructor(i,e){super(i),this.predicate=e,this.index=0}next(i){this.predicate(i,this.index++)?this.result=!0:(this.result=!1,this.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},EC=j(jc,"every");var qc=class extends H{constructor(i,e,t){super(i),this.f=e,typeof t=="undefined"?this.next=s=>{this.acc=s,this.resetNext(),this.sink.next(this.acc)}:this.acc=t}next(i){this.sink.next(this.acc=this.f(this.acc,i))}},IC=j(qc,"scan"),Xc=class extends H{constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},AC=j(Xc,"pairwise"),Qc=class extends H{constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},El=j(Qc,"map");var Ur=class extends H{constructor(i,e,t){super(i),this.data=e,this.context=t}next(i){let e=this.context.combineResults;e?this.sink.next(e(this.data,i)):this.sink.next(i)}tryComplete(){this.context.resetComplete(),this.dispose()}},Br=class extends H{constructor(i,e,t){super(i),this.makeSource=e,this.combineResults=t,this.index=0}subInner(i,e){let t=this.currentSink=new e(this.sink,i,this);this.complete=this.tryComplete,t.complete=t.tryComplete,t.subscribe(this.makeSource(i,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},Ln=class extends Ur{},xn=class extends Br{next(i){this.subInner(i,Ln),this.next=e=>{this.currentSink.dispose(),this.subInner(e,Ln)}}},m_=j(xn,"switchMap");function Un(r){return(i,e)=>r(()=>i,e)}var CC=Un(j(xn,"switchMapTo")),zc=class extends Ur{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},Pn=class extends Br{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(),zc),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},RC=j(Pn,"concatMap"),yC=Un(j(Pn,"concatMapTo")),Yc=class extends Ur{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},wn=class extends Br{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,Yc),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},bC=j(wn,"mergeMap"),NC=Un(j(wn,"mergeMapTo")),Kc=class extends Ur{dispose(){this.context.resetNext(),super.dispose()}},Vn=class extends Br{next(i){this.next=Te,this.subInner(i,Kc)}},vC=j(Vn,"exhaustMap"),DC=Un(j(Vn,"exhaustMapTo")),Zc=class extends H{constructor(i,e){super(i),this.f=e,this.groups=new Map}next(i){let e=this.f(i),t=this.groups.get(e);typeof t=="undefined"&&(t=vc(),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)}},OC=j(Zc,"groupBy"),ed=class extends H{constructor(){super(...arguments),this.start=new Date}next(i){this.sink.next({value:i,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},MC=j(ed,"timeInterval"),td=class extends H{constructor(i,e){super(i),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(i){this.buffer.push(i)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},kC=j(td,"bufferTime"),id=class extends H{constructor(i,e){super(i),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(i){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:t,data:s}=e;super.next(s),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(t))}},i)}next(i){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:i})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},LC=j(id,"delay"),rd=class extends H{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},xC=j(rd,"catchError");var sd=class extends H{constructor(i,e){super(i),e instanceof Function?this.next=t=>{e(t),i.next(t)}:(e.next&&(this.next=t=>{e.next(t),i.next(t)}),e.complete&&(this.complete=()=>{e.complete(),i.complete()}),e.error&&(this.error=t=>{e.error(t),i.error(t)}))}},UC=j(sd,"tap"),od=class extends H{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new Mn(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},BC=j(od,"timeout");var iR=_l(fl(250),El(()=>performance.now()),kn());var $r=new Map;g.on(E.JOIN_SUCCESS,({room:r})=>{ae(r.userId,{eventId:32788})});g.on(E.LEAVE_START,({room:r})=>{ae(r.userId,{eventId:32789})});g.on(E.LOCAL_TRACK_PUBLISHED,({track:r})=>{if(r.room){let i=32769;r.mediaType===4?i=32768:r.mediaType===2&&(i=32805),ae(r.room.userId,{eventId:i})}});g.on(E.LOCAL_TRACK_UNPUBLISHED,({track:r})=>{if(r.room){let i=32771;r.mediaType===4?i=32770:r.mediaType===2&&(i=32806),ae(r.room.userId,{eventId:i})}});g.on(E.TRACK_MUTED,({track:r})=>{r.room&&(r.kind===h.AUDIO?ae(r.room.userId,{eventId:r.isRemote?32785:32772,remoteUserId:r.isRemote?r.userId:void 0}):ae(r.room.userId,{eventId:r.isRemote?32784:32773,remoteUserId:r.isRemote?r.userId:void 0}))});g.on(E.TRACK_UNMUTED,({track:r})=>{r.room&&(r.kind===h.AUDIO?ae(r.room.userId,{eventId:r.isRemote?32787:32774,remoteUserId:r.isRemote?r.userId:void 0}):ae(r.room.userId,{eventId:r.isRemote?32786:32775,remoteUserId:r.isRemote?r.userId:void 0}))});g.on(E.REMOTE_TRACK_SUBSCRIBED,({track:r})=>{!r.room||(r.mediaType===1&&ae(r.room.userId,{eventId:32777,remoteUserId:r.userId}),r.mediaType===4&&ae(r.room.userId,{eventId:32776,remoteUserId:r.userId}),r.mediaType===8&&ae(r.room.userId,{eventId:32803,remoteUserId:r.userId}))});g.on(E.REMOTE_TRACK_UNSUBSCRIBED,({track:r})=>{!r.room||(r.mediaType===1&&ae(r.room.userId,{eventId:32779,remoteUserId:r.userId}),r.mediaType===4&&ae(r.room.userId,{eventId:32778,remoteUserId:r.userId}),r.mediaType===8&&ae(r.room.userId,{eventId:32804,remoteUserId:r.userId}))});g.on(E.SWITCH_DEVICE_SUCCESS,({track:r})=>{r.room&&ae(r.room.userId,{eventId:r.kind===h.VIDEO?32780:32781})});g.on(E.LOCAL_TRACK_REPLACED,({track:r})=>{r.room&&ae(r.room.userId,{eventId:r.kind===h.VIDEO?32782:32783})});g.on(E.SIGNAL_CONNECTION_STATE_CHANGED,({room:r,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&&ae(r.userId,{eventId:t})});g.on(E.PEER_CONNECTION_STATE_CHANGED,({room:r,prevState:i,state:e,remoteUserId:t})=>{let s=!!t,o;switch(e){case"CONNECTED":i==="RECONNECTING"?o=s?32801:32798:o=s?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(o=s?32802:32799);break;case"RECONNECTING":o=s?32800:32797;break}o&&ae(r.userId,{eventId:o,remoteUserId:t})});g.on(E.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({userId:r,remoteUserId:i,codec:e,isHWCodec:t,prevImplementation:s,streamType:o})=>{let n=t?1:0;s||(n=t?3:2);let a=e==="h264"?0:2,c={eventId:4004,param1:n,param2:a,streamType:o||2};i&&(c.remoteUserId=i,c.eventId=4005),ae(r,c),D.addEnum({key:i?514701:513701,value:n}),D.addEnum({key:i?514700:513700,value:a})});g.on(E.LOCAL_TRACK_RECAPTURE,({track:r,error:i})=>{if(r.userId){let e={eventId:2003,param1:0};r.kind===h.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=r.streamType==="auxiliary"?7:2,i&&(e.param1=8)),ae(r.userId,e)}});function ae(r,i){let e=P(N({},i),{timestamp:ts()});$r.has(r)?$r.get(r).push(e):$r.set(r,[e])}function gl(r){if($r.has(r)){let i=$r.get(r).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 $r.delete(r),i}return[]}var Tl=Se(Ne(),1);var Bn=class extends Tl.EventEmitter{constructor(e,t,s="userId"){super();this.mySelfId=e;this._log=t;this.key=s;u(this,"userMap",new Map);u(this,"remotePublishedUserMap",new Map)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:s,tinyId:o,role:n}=e;if(this.userMap.has(t))return;let a={userId:s,tinyId:o,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let s=this.userMap.get(e);if(!s)return;let o=`peer leave [${e}]`;T(t)||(o+=`:${Ca[t]}`),this._log.info(o);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",s.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(s=>s[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 s=t[this.key];if(e.findIndex(o=>o[this.key]===t[this.key])<0){this._log.info(`remote [${s}] unpublish`);let o=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(s),this.emit("6",{prevMuteState:o,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var l;let s=t[this.key];if(s===this.mySelfId)return;let{flag:o,userId:n,tinyId:a}=t,c=Ai(o,n),d=(l=this.remotePublishedUserMap.get(s))==null?void 0:l.muteState;if(d){let p=this.remotePublishedUserMap.get(s);p&&p.flag!==o&&(p.flag=o,this._log.info(`remote publish updated: ${JSON.stringify(p.muteState)}`),this.emit("6",{prevMuteState:d,muteState:c,flag:o}))}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:Ai(0,n),muteState:c,flag:o})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function nd({timesInSecond:r,maxSizeInSecond:i,getSize:e}){return J((t,s)=>{let o=new Map;return g.on(E.ROOM_DESTROY,({room:n})=>o.delete(n)),function(...n){let a=o.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.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>=r||a.totalSizeInSecond>i))throw new b({code:A.INVALID_OPERATION,message:L({key:M.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=r,isSize:a.totalSizeInSecond>i,name:s,timesInSecond:r,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var Sl=!0,Il=function(){var r;Sl&&(Sl=!1,I.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Ct}/en/index.html`),console.info(`* Changelog: ${Ct}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),I.info("TRTC Web SDK Version:",Re),I.info("UA:",navigator.userAgent),I.info(`URL: ${location.href}${((r=self.frameElement)==null?void 0:r.tagName)==="IFRAME"?" in iframe":""}`),Is().then(i=>{i&&I.info(dt)}))};var st={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"};var w={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},It=(S=>(S[S.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",S[S.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",S[S.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",S[S.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",S[S.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",S[S.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",S[S.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",S[S.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",S[S.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",S[S.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",S[S.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",S[S.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",S[S.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",S[S.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",S[S.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",S[S.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",S[S.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",S[S.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",S[S.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",S[S.INVALID_OPERATION=5100]="INVALID_OPERATION",S[S.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",S[S.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",S[S.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",S[S.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",S[S.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",S[S.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",S[S.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",S[S.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",S[S.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",S[S.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",S[S.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",S[S.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",S[S.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",S[S.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",S[S.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",S[S.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",S[S.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",S[S.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",S[S.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",S[S.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",S[S.DEVICE_ERROR=5300]="DEVICE_ERROR",S[S.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",S[S.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",S[S.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",S[S.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",S[S.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",S[S.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",S[S.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",S[S.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",S[S.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",S[S.SERVER_ERROR=5400]="SERVER_ERROR",S[S.NEED_TO_BUY=5401]="NEED_TO_BUY",S[S.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",S[S.OPERATION_FAILED=5500]="OPERATION_FAILED",S[S.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",S[S.REJOIN_FAILED=5502]="REJOIN_FAILED",S[S.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",S[S.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",S[S.OPERATION_ABORT=5998]="OPERATION_ABORT",S[S.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",S))(It||{});function Cl({code:r,params:i,enableDocLink:e=!1}){let t="",s,o=It[r];try{s=Al[o]}catch(n){s=Al.UNKNOWN_ERROR}return W(s)?t=s(i):Y(s)&&(t=s),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var Al=P(N({},Ae),{INVALID_PARAMETER({fnName:r}){return`the parameters of the '${r}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:r,rule:i,fnName:e,value:t}){let s=`${r||i.name}`,o="";return Array.isArray(i.type)?o=i.type.join("|"):o=i.type,`'${s}' must be type of ${o} when calling ${e}(), received type: ${fe(t)}.`},INVALID_PARAMETER_EMPTY({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:r,rule:i,fnName:e,value:t}){let s=`${r||i.name}`,o=`${i.instanceOf.name||i.instanceOf}`;return`'${s}' must be instanceof ${o} when calling ${e}(), received type: ${fe(t)}.`},INVALID_PARAMETER_RANGE({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:r,rule:i,fnName:e}){return`'${r||i.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:r,rule:i,value:e}){return`the min value of ${r||i.name} is ${i.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:r,rule:i,value:e}){return`the max value of ${r||i.name} is ${i.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:r,fnName:i}){return`'${r}' is not found in the document object when calling ${i}().`},INVALID_ELEMENT_ID_TYPE({key:r,fnName:i,type:e}){return`the element corresponding to '${r}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`},INVALID_STREAM_ID({key:r}){return`'${r}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:r}){return`'${r}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:r}){return`'${r}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:r}){return`'${r}' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.`},INVALID_ROOM_ID_REQUIED(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},INVALID_STREAM_TYPE:({fnName:r})=>`'streamType' is required when 'userId' is not '*', calling ${r}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:r}){return`the API '${r}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:r}){return`cannot ${r} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:r,value:i}){return`cannot ${r} because remote user(userId: ${i.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:r,value:i}){return`cannot ${r} because remote user(userId: ${i.userId}) does not publishing ${i.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:r}){return`you are already ${r}(), cannot repeated call '${r}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:r}){return`cannot call '${r}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:r}){return`cannot call '${r}' because the microphone is not turned on.`},INVALID_BUFFER_EMPTY:({key:r})=>`the buffer size of paramerter '${r}' 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:r})=>`you need to call ${r}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:r}){return`the current browser does not support the capability of the function '${r}' 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:r}){return`cannot call ${r} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:r,error:i}){return`'${r}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:r,deviceType:i=Qi(r),error:e}){return`NotFoundError, no ${i} detected, please check your device and the configuration on '${r}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:r,deviceType:i=Qi(r),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:r,deviceType:i=Qi(r),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:r,deviceType:i=Qi(r),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:r,deviceType:i=Qi(r),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:r,deviceType:i=Qi(r),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:r,deviceType:i=Qi(r),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:r}){return`camera recover capture failed ${(r==null?void 0:r.name)||""}: ${(r==null?void 0:r.originMessage)||(r==null?void 0:r.message)}`},MICROPHONE_RECOVER_FAILED({error:r}){return`microphone recover capture failed ${(r==null?void 0:r.name)||""}: ${(r==null?void 0:r.originMessage)||(r==null?void 0:r.message)}`},OPERATION_FAILED({fnName:r,error:i}){return`'${r}' 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:r}){return`an error was caught on trtc.on('${r}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:r,error:i}){return`video context error ${r} ${(i==null?void 0:i.name)||""} ${(i==null?void 0:i.message)||""}`},SERVER_ERROR({fnName:r,error:i}){return`'${r}' got server error: ${i==null?void 0:i.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:r,url:i}){return`You need to buy packages for ${r}. Refer to: ${i}`},ACCOUNT_NO_MONEY:({fnParams:r})=>`your TRTC account run out of credit, please recharge.${r.sdkAppId?` SDKAppId: ${r.sdkAppId}`:""}`,OPERATION_ABORT({fnName:r}){return`'${r}' abort`},UNKNOWN_ERROR({fnName:r,error:i}){return`'${r}' throw unknown exception${i?`, error: ${i.toString()}.`:"."}`}});function Qi(r){if(!r)return"camera";let i=r.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var zi=class extends Error{constructor({code:e,extraCode:t,message:s="",messageParams:o,fnName:n="",originError:a}){var d;let c;s?c=s:c=Cl({code:t||e,params:N({fnName:n,error:a},o)});super(c);u(this,"name","RtcError");u(this,"code");u(this,"extraCode");u(this,"functionName");u(this,"message");u(this,"handler");u(this,"originError");this.name=It[e],this.code=e,this.extraCode=t,this.functionName=n,this.originError=a,this.message=c,this.extraCode===5302&&((d=this.originError)==null?void 0:d.message.includes("system"))&&(this.handler=()=>{let l={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},p={startLocalVideo:"webcam",startLocalAudio:"microphone"},m=document.createElement("a");Ei?m.href=`ms-settings:privacy-${p[this.functionName]}`:bt&&(m.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${l[this.functionName]}`),m.href.length>0&&m.click()})}static convertFrom(e,t,s){let o=e;if(e instanceof b){let{stack:n}=e,a={code:w.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case A.INVALID_PARAMETER:a.code=w.INVALID_PARAMETER,a.message=e.message;break;case A.INVALID_OPERATION:a.code=w.INVALID_OPERATION;break;case A.NOT_SUPPORTED:case A.NOT_SUPPORTED_H264:a.code=w.ENV_NOT_SUPPORTED,e.getCode()===A.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(Ae.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case A.JOIN_ROOM_FAILED:a.messageParams={fnParams:s};case A.SERVER_TIMEOUT:case A.SWITCH_ROLE_FAILED:a.code=w.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case A.API_CALL_ABORTED:a.code=w.OPERATION_ABORT;break;case A.DEVICE_NOT_FOUND:case A.DEVICE_AUTO_RECOVER_FAILED:case A.INITIALIZE_FAILED:a.code=5300,e.name&&(a.extraCode=p_(e.name));break;case A.UNKNOWN:break;default:a.code=w.OPERATION_FAILED}o=new zi(a),n&&(o.stack+=n.substr(n.indexOf(`
|
|
62
|
-
`)))}else{if(e instanceof zi)return e;o=new zi({code:w.UNKNOWN_ERROR,fnName:t,originError:e})}return o}};function p_(r){let i;switch(r){case"NotFoundError":i=5301;break;case"NotAllowedError":i=5302;break;case"NotReadableError":i=5303;break;case"OverconstrainedError":i=5304;break;case"InvalidStateError":i=5305;break;case"SecurityError":i=5306;break;case"AbortError":i=5307;break;default:i=5300}return i}var k=zi;var Rl={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},yl={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}}},Fr={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(r,i,e){if(Y(r)&&!document.getElementById(r))throw new k({code:w.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},bl={name:"userId",required:!0,type:"string"},Nl={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[st.AUDIO_PROFILE_STANDARD,st.AUDIO_PROFILE_STANDARD_STEREO,st.AUDIO_PROFILE_HIGH,st.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function eo(r,i){if(!r)throw new k({code:w.INVALID_OPERATION,extraCode:5101,fnName:i})}function vl(r,i,e){if(!r)throw new k({code:w.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}var qy={type:"number",notLessThanZero:!0},__={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(r,i,e){if(this._room.isJoined)throw new k({code:w.INVALID_OPERATION,extraCode:5104,fnName:e});if(r.roomId){if(Y(r.roomId))throw new k({code:w.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});if(!(/^[1-9]\d*$/.test(String(r.roomId))&&r.roomId<4294967295))throw new k({code:w.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:i}})}else if(r.strRoomId){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(r.strRoomId))throw new k({code:w.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:i}})}else throw new k({code:w.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:Fr,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:Rl},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.videoTrack)&&ii())throw new k({code:w.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:P(N({},Fr),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:Rl}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:Nl},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.audioTrack)&&ii())throw new k({code:w.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:Nl}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:Fr,publish:{type:"boolean"},option:yl},validate(r,i,e,t,s){var o;if(!((o=r==null?void 0:r.option)!=null&&o.videoTrack)&&ii())throw new k({code:w.ENV_NOT_SUPPORTED,extraCode:5201});if(!Ls())throw new k({code:w.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:Fr,publish:{type:"boolean"},option:yl}},muteRemoteAudio:[bl,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[bl,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:Fr,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(r,i,e){eo(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(vl(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new k({code:w.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:r}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:P(N({},Fr),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(r,i,e){eo(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(vl(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new k({code:w.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:r}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(r,i,e){if(r.userId!=="*"&&T(r.streamType))throw new k({code:w.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(r,i,e){eo(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(r,i,e,t){if(!Fi)throw new k({code:w.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new k({code:w.INVALID_OPERATION,fnName:e,extraCode:5108});if(r.byteLength>1e3)throw new k({code:w.INVALID_PARAMETER,extraCode:5018,fnName:e});if(r.byteLength===0)throw new k({code:w.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});eo(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(r,i,e){if(!r&&!this._room.isMainStreamPublished||r&&!this._room.isAuxStreamPublished)throw new k({code:w.INVALID_OPERATION,extraCode:5109,messageParams:{key:i},fnName:e})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(r,i,e,t){if(r.byteLength>1e3)throw new k({code:w.INVALID_PARAMETER,extraCode:5018,fnName:e});if(r.byteLength===0)throw new k({code:w.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(r,i,e){if(eo(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new k({code:w.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}}},Ce={TRTC:__};var Me=class extends Error{};function f_(r,i){let e=yr(r);for(let t=0;t<i.length;t++)Kt(e[t],i[t]);return e}function E_(r){this._resolve=Promise.resolve(r)}function g_(r){this._reject=Promise.reject(r)}var Yi=class{constructor(i,e){this.instance=i;this.group=e;this.started=!1;this.ops=[];this.startSame=()=>!0;this.mergeUpdate=f_;let t=Yi.instances.get(i);t?t.set(e,this):Yi.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=Yi.instances.get(i);return t&&t.get(e)||new Yi(i,e)}static gets(i,e){let t=Yi.instances.get(i),s=[];return t&&t.forEach((o,n)=>{e.test(n)&&s.push(o)}),s}action(i,e,t){let s=a=>{var c;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),a},o=a=>{var c,d;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new Me("start failed")),(d=this.currentOp)==null||d.action(),a},n={type:i,action:()=>e(...n.args).then(s,o),args:t,resolve:E_,reject:g_};try{switch(this.state){case 1:if(i===0)throw new Me("already started");break;case 4:if(i===2)throw new Me("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(s,o)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new Me("already start");break;case 3:switch(i.type){case 2:throw new Me("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Me("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new Me("keep stop");if(this.ops.slice(1).forEach(s=>s.reject(t)),this.ops=this.ops.slice(0,1),this.state===3)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,i.args),this.lastOp.promise;case 3:throw new Me("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Me("start not allowed after update");case 0:throw new Me("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new Me("keep start")),new Me("already start")}}i.promise=new Promise((t,s)=>{i._resolve?i._resolve.then(t):i.resolve=t,i._reject?i._reject.catch(s):i.reject=s});let{action:e}=i;return i.action=()=>e().then(i.resolve,i.reject),this.ops.push(i),i.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}},Ht=Yi;Ht.instances=new WeakMap;var Fn=new WeakMap,Hn=(r,i)=>{if(i instanceof Me){let{stack:e}=i;i=new k({code:w.OPERATION_ABORT,message:`${r} abort: ${i.message}`,fnName:r}),e&&(i.stack+=e.substr(e.indexOf(`
|
|
63
|
-
`)))}throw i};function
|
|
61
|
+
} `,zi=class extends F{constructor(e){super();l(this,"frameRate");l(this,"_canvas");l(this,"log");l(this,"hasAlpha",!1);l(this,"name");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}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 Ur(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new Vr(this,e)}createVideoImageSource(e,t){return new Ys(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new Ks(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};l(zi,"_ids",0);var t_={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},ye=class extends zi{constructor(){super(...arguments);l(this,"defaultProgam");l(this,"defaultVShader");l(this,"defaultFShader");l(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${zi._ids++}`),this.ctx=this._canvas.getContext("webgl2",t_),!this.ctx)throw new Error("webgl2 not supported");this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,Zp),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,e_),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new Error("webgl context lost"))}),this.log.info("video context created use webgl")}destroy(e){return this.disconnect(),this.log.info(`video context destroy ${e?`: ${e}`:""}`),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}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var s;(s=this.ctx)==null||s.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let s=this.ctx,o=s.createShader(e);return s.shaderSource(o,t),s.compileShader(o),o}createProgram(e,t){let s=this.ctx,o=s.createProgram();return s.attachShader(o,e),s.attachShader(o,t),s.linkProgram(o),s.getProgramParameter(o,s.LINK_STATUS)||this.log.error(s.getProgramInfoLog(o)),o}};y([le(F.INIT,"created",{sync:!0})],ye.prototype,"create",1),y([le("created",F.INIT,{ignoreError:!0,sync:!0,success(r){r&&this.emit("unavailable",r),this.removeAllListeners()}})],ye.prototype,"destroy",1);var Fe=class extends zi{constructor(){super(...arguments);l(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${zi._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new Error("2d context not supported");this.log.info("video context created use 2d")}destroy(e){this.disconnect(),this.log.info(`video context destroy ${e?`: ${e}`:""}`),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners()}};y([le(F.INIT,"created",{sync:!0})],Fe.prototype,"create",1),y([le("created",F.INIT,{ignoreError:!0,sync:!0})],Fe.prototype,"destroy",1);function i_(r){return[15,30,45,60].reduce((e,t)=>Math.abs(t-r)<Math.abs(e-r)?t:e)}var St=class extends st{constructor(e,t,s=4){super(e,t,s);l(this,"mediaType",4);l(this,"source");l(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});l(this,"pipeline",[]);this.manager=e.videoManager}play(e,t){return(de(t==null?void 0:t.canvasRender)?t.canvasRender:Is===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t)}useCanvasPlayer(){if(this.log.info(`useCanvasPlayer(), ${!!this.player.element}`),!this.player.element)return;let e=new Fe({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=e.createVideoPlayerSource(this.player);this.source=t;let s=new zs(e);t.connect(s),this.player.setCanvas(e._canvas),this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this)}updateCanvasPlayerFPS(e){let t=this.decodeFPS,s=i_(t);if(!ee(t)||t<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${t} `);return}if(s===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${s} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${t}, closest: ${s}, current: ${e.frameRate}`),e.frameRate=s}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 s=e.find(a=>a.uint32_video_stream_type===t);return(s==null?void 0:s.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),super.stop()}get enableDecodeFrame(){return this.manager.configPipeline(this),this.pipeline.some(e=>e)}decodeFrame(e){return this.pipeline.reduce((t,s)=>s?s(t,this):t,e)}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get hasFlag(){return this.user.muteState.hasVideo&&!this.user.muteState.videoMuted}isFlagChanged(e){let t=e.hasVideo&&!e.videoMuted;return this.hasFlag!==t}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}},Br=class extends St{constructor(e,t){super(e,t,2);l(this,"mediaType",2);l(this,"objectFit","contain")}get hasFlag(){return this.user.muteState.hasAuxiliary}isFlagChanged(e){let t=e.hasAuxiliary;return this.hasFlag!==t}};function Te(...r){}var r_=r=>r();function yc(){this.dispose()}var s_=()=>typeof __FASTRX_DEVTOOLS__!="undefined",o_=1,ai=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new Rc(i,this,this.streamId++);return It.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},Zs=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=Te,this.error=Te,this.next=Te,this.dispose=Te,this.subscribe=Te,this.doDefer()}subscribe(i){return i instanceof ai?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(r_),this.defers.clear()}defer(i){this.defers.add(i)}removeDefer(i){this.defers.delete(i)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},H=class extends Zs{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)}};function _u(r,...i){return i.reduce((e,t)=>t(e),r)}function ci(r,i,e){if(s_()){let t=Object.defineProperties(Object.setPrototypeOf(r,ai.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}});It.create(t);for(let s=0;s<e.length;s++){let o=e[s];typeof o=="function"&&o instanceof ai&&It.addSource(t,o)}return t}return r}function J(r,i){return function(...e){return t=>{if(t instanceof ai){let s=ci(o=>{let n=new r(o,...e);n.sourceId=s.id,n.subscribe(t)},i,arguments);return s.source=t,It.pipe(s),s}else return s=>t(new r(s,...e))}}}function Oi(r,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:r,payload:i}})}var Rc=class extends H{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{It.defer(this.source,this.id)})}next(i){It.next(this.source,this.id,i),this.sink.next(i)}complete(){It.complete(this.source,this.id),this.sink.complete()}error(i){It.complete(this.source,this.id,i),this.sink.error(i)}},It={addSource(r,i){Oi("addSource",{id:r.id,name:r.toString(),source:{id:i.id,name:i.toString()}})},next(r,i,e){Oi("next",{id:r.id,streamId:i,data:e&&e.toString()})},subscribe({id:r,end:i},e){Oi("subscribe",{id:r,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(r,i,e){Oi("complete",{id:r.id,streamId:i,err:e?e.toString():null})},defer(r,i){Oi("defer",{id:r.id,streamId:i})},pipe(r){Oi("pipe",{name:r.toString(),id:r.id,source:{id:r.source.id,name:r.source.toString()}})},update(r){Oi("update",{id:r.id,name:r.toString()})},create(r){r.id||(r.id=o_++),Oi("create",{name:r.toString(),id:r.id})}},kn=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var bc=class extends Zs{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 Ln(){return r=>{let i=new bc(r);if(r instanceof ai){let e=ci(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=r,It.pipe(e),e}return ci(i.add.bind(i),"share",arguments)}}function n_(...r){return ci(i=>{let e=r.length,t=e,s=e,o=new Array(e),n=()=>{--s===0&&i.complete()},a=(c,d)=>{let u=new H(i);u.next=p=>{--t===0?(u.next=m=>{o[d]=m,i.next(o)},u.next(p)):o[d]=p},u.complete=n,u.subscribe(c)};r.forEach(a)},"combineLatest",arguments)}var Nc=class extends H{constructor(i,...e){super(i);let t=new H(this.sink);t.next=s=>this.buffer=s,t.complete=Te,t.subscribe(n_(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},QA=J(Nc,"withLatestFrom"),vc=class extends H{constructor(i,e,t){super(i),this.bufferSize=e,this.startBufferEvery=t,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(i){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(i)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(i),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(i=>this.sink.next(i)),super.complete()}},zA=J(vc,"bufferCount"),Dc=class extends H{constructor(i,e){super(i),this.buffer=[];let t=new H(i);t.next=s=>{i.next(this.buffer),this.buffer=[]},t.complete=Te,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},YA=J(Dc,"buffer");function Oc(r){let i=arguments,e=Ln()(ci(t=>{e.next=s=>t.next(s),e.complete=()=>t.complete(),e.error=s=>t.error(s),r&&t.subscribe(r)},"subject",i));return e.next=Te,e.complete=Te,e.error=Te,e}function fu(r){return ci(i=>{let e=0,t=setInterval(()=>i.next(e++),r);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}var Mc=class extends H{constructor(i,e,t){super(i),this.f=e;let s=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=o=>{this.acc=o,this.complete=s,this.resetNext()}:(this.acc=t,this.complete=s)}next(i){this.acc=this.f(this.acc,i)}},a_=J(Mc,"reduce");var kc=class extends H{constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},c_=J(kc,"filter"),Lc=class extends H{next(i){}},cC=J(Lc,"ignoreElements"),xc=class extends H{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&this.complete()}},d_=J(xc,"take"),Pc=class extends H{constructor(i,e){super(i);let t=new H(i);t.next=()=>i.complete(),t.complete=yc,t.subscribe(e)}},dC=J(Pc,"takeUntil"),wc=class extends H{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):this.complete()}},l_=J(wc,"takeWhile");var Vc=class extends H{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},lC=J(Vc,"skip"),Uc=class extends H{constructor(i,e){super(i),i.next=Te;let t=new H(i);t.next=()=>{t.dispose(),i.resetNext()},t.complete=yc,t.subscribe(e)}},uC=J(Uc,"skipUntil"),Bc=class extends H{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},u_=J(Bc,"skipWhile"),h_={leading:!0,trailing:!1},$c=class extends H{constructor(i,e,t){super(i),this.durationSelector=e,this.trailing=t}cacheValue(i){this.last=i,this.disposed&&this.throttle(i)}send(i){this.sink.next(i),this.throttle(i)}throttle(i){this.reset(),this.subscribe(this.durationSelector(i))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},Fc=class extends H{constructor(i,e,t=h_){super(i),this.durationSelector=e,this.config=t,this._throttle=new $c(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=Te,this._throttle.complete(),super.complete()}},hC=J(Fc,"throttle");var Hc=class extends H{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Gc=class extends H{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new Hc(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()}},mC=J(Gc,"debounce");var Wc=class extends H{constructor(i,e,t){super(i),this.count=e,this.defaultValue=t}next(i){this.count--===0&&(this.defaultValue=i,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("not enough elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},pC=J(Wc,"elementAt");var Jc=class extends H{constructor(i,e){super(i),this.f=e,this.i=0}next(i){this.f(i)?(this.sink.next(this.i++),this.complete()):++this.i}},_C=J(Jc,"findIndex"),jc=class extends H{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i,this.complete())}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},fC=J(jc,"first"),qc=class extends H{constructor(i,e,t){super(i),this.f=e,this.defaultValue=t,this.index=0}next(i){(!this.f||this.f(i,this.index++))&&(this.defaultValue=i)}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},EC=J(qc,"last"),Xc=class extends H{constructor(i,e){super(i),this.predicate=e,this.index=0}next(i){this.predicate(i,this.index++)?this.result=!0:(this.result=!1,this.complete())}complete(){if(this.result===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.result);super.complete()}},gC=J(Xc,"every");var Qc=class extends H{constructor(i,e,t){super(i),this.f=e,typeof t=="undefined"?this.next=s=>{this.acc=s,this.resetNext(),this.sink.next(this.acc)}:this.acc=t}next(i){this.sink.next(this.acc=this.f(this.acc,i))}},AC=J(Qc,"scan"),zc=class extends H{constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},CC=J(zc,"pairwise"),Yc=class extends H{constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},Eu=J(Yc,"map");var $r=class extends H{constructor(i,e,t){super(i),this.data=e,this.context=t}next(i){let e=this.context.combineResults;e?this.sink.next(e(this.data,i)):this.sink.next(i)}tryComplete(){this.context.resetComplete(),this.dispose()}},Fr=class extends H{constructor(i,e,t){super(i),this.makeSource=e,this.combineResults=t,this.index=0}subInner(i,e){let t=this.currentSink=new e(this.sink,i,this);this.complete=this.tryComplete,t.complete=t.tryComplete,t.subscribe(this.makeSource(i,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},xn=class extends $r{},Pn=class extends Fr{next(i){this.subInner(i,xn),this.next=e=>{this.currentSink.dispose(),this.subInner(e,xn)}}},m_=J(Pn,"switchMap");function Bn(r){return(i,e)=>r(()=>i,e)}var RC=Bn(J(Pn,"switchMapTo")),Kc=class extends $r{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},wn=class extends Fr{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(),Kc),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},yC=J(wn,"concatMap"),bC=Bn(J(wn,"concatMapTo")),Zc=class extends $r{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Vn=class extends Fr{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,Zc),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},NC=J(Vn,"mergeMap"),vC=Bn(J(Vn,"mergeMapTo")),ed=class extends $r{dispose(){this.context.resetNext(),super.dispose()}},Un=class extends Fr{next(i){this.next=Te,this.subInner(i,ed)}},DC=J(Un,"exhaustMap"),OC=Bn(J(Un,"exhaustMapTo")),td=class extends H{constructor(i,e){super(i),this.f=e,this.groups=new Map}next(i){let e=this.f(i),t=this.groups.get(e);typeof t=="undefined"&&(t=Oc(),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)}},MC=J(td,"groupBy"),id=class extends H{constructor(){super(...arguments),this.start=new Date}next(i){this.sink.next({value:i,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},kC=J(id,"timeInterval"),rd=class extends H{constructor(i,e){super(i),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(i){this.buffer.push(i)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},LC=J(rd,"bufferTime"),sd=class extends H{constructor(i,e){super(i),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(i){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:t,data:s}=e;super.next(s),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(t))}},i)}next(i){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:i})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},xC=J(sd,"delay"),od=class extends H{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},PC=J(od,"catchError");var nd=class extends H{constructor(i,e){super(i),e instanceof Function?this.next=t=>{e(t),i.next(t)}:(e.next&&(this.next=t=>{e.next(t),i.next(t)}),e.complete&&(this.complete=()=>{e.complete(),i.complete()}),e.error&&(this.error=t=>{e.error(t),i.error(t)}))}},BC=J(nd,"tap"),ad=class extends H{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new kn(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},$C=J(ad,"timeout");var rR=_u(fu(250),Eu(()=>performance.now()),Ln());var Hr=new Map;g.on(E.JOIN_SUCCESS,({room:r})=>{ae(r.userId,{eventId:32788})});g.on(E.LEAVE_START,({room:r})=>{ae(r.userId,{eventId:32789})});g.on(E.LOCAL_TRACK_PUBLISHED,({track:r})=>{if(r.room){let i=32769;r.mediaType===4?i=32768:r.mediaType===2&&(i=32805),ae(r.room.userId,{eventId:i})}});g.on(E.LOCAL_TRACK_UNPUBLISHED,({track:r})=>{if(r.room){let i=32771;r.mediaType===4?i=32770:r.mediaType===2&&(i=32806),ae(r.room.userId,{eventId:i})}});g.on(E.TRACK_MUTED,({track:r})=>{r.room&&(r.kind===h.AUDIO?ae(r.room.userId,{eventId:r.isRemote?32785:32772,remoteUserId:r.isRemote?r.userId:void 0}):ae(r.room.userId,{eventId:r.isRemote?32784:32773,remoteUserId:r.isRemote?r.userId:void 0}))});g.on(E.TRACK_UNMUTED,({track:r})=>{r.room&&(r.kind===h.AUDIO?ae(r.room.userId,{eventId:r.isRemote?32787:32774,remoteUserId:r.isRemote?r.userId:void 0}):ae(r.room.userId,{eventId:r.isRemote?32786:32775,remoteUserId:r.isRemote?r.userId:void 0}))});g.on(E.REMOTE_TRACK_SUBSCRIBED,({track:r})=>{!r.room||(r.mediaType===1&&ae(r.room.userId,{eventId:32777,remoteUserId:r.userId}),r.mediaType===4&&ae(r.room.userId,{eventId:32776,remoteUserId:r.userId}),r.mediaType===8&&ae(r.room.userId,{eventId:32803,remoteUserId:r.userId}))});g.on(E.REMOTE_TRACK_UNSUBSCRIBED,({track:r})=>{!r.room||(r.mediaType===1&&ae(r.room.userId,{eventId:32779,remoteUserId:r.userId}),r.mediaType===4&&ae(r.room.userId,{eventId:32778,remoteUserId:r.userId}),r.mediaType===8&&ae(r.room.userId,{eventId:32804,remoteUserId:r.userId}))});g.on(E.SWITCH_DEVICE_SUCCESS,({track:r})=>{r.room&&ae(r.room.userId,{eventId:r.kind===h.VIDEO?32780:32781})});g.on(E.LOCAL_TRACK_REPLACED,({track:r})=>{r.room&&ae(r.room.userId,{eventId:r.kind===h.VIDEO?32782:32783})});g.on(E.SIGNAL_CONNECTION_STATE_CHANGED,({room:r,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&&ae(r.userId,{eventId:t})});g.on(E.PEER_CONNECTION_STATE_CHANGED,({room:r,prevState:i,state:e,remoteUserId:t})=>{let s=!!t,o;switch(e){case"CONNECTED":i==="RECONNECTING"?o=s?32801:32798:o=s?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(o=s?32802:32799);break;case"RECONNECTING":o=s?32800:32797;break}o&&ae(r.userId,{eventId:o,remoteUserId:t})});g.on(E.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({userId:r,remoteUserId:i,codec:e,isHWCodec:t,prevImplementation:s,streamType:o})=>{let n=t?1:0;s||(n=t?3:2);let a=e==="h264"?0:2,c={eventId:4004,param1:n,param2:a,streamType:o||2};i&&(c.remoteUserId=i,c.eventId=4005),ae(r,c),D.addEnum({key:i?514701:513701,value:n}),D.addEnum({key:i?514700:513700,value:a})});g.on(E.LOCAL_TRACK_RECAPTURE,({track:r,error:i})=>{if(r.userId){let e={eventId:2003,param1:0};r.kind===h.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=r.streamType==="auxiliary"?7:2,i&&(e.param1=8)),ae(r.userId,e)}});function ae(r,i){let e=P(N({},i),{timestamp:is()});Hr.has(r)?Hr.get(r).push(e):Hr.set(r,[e])}function gu(r){if(Hr.has(r)){let i=Hr.get(r).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 Hr.delete(r),i}return[]}var Tu=Se(Ne(),1);var $n=class extends Tu.EventEmitter{constructor(e,t,s="userId"){super();this.mySelfId=e;this._log=t;this.key=s;l(this,"userMap",new Map);l(this,"remotePublishedUserMap",new Map)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:s,tinyId:o,role:n}=e;if(this.userMap.has(t))return;let a={userId:s,tinyId:o,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let s=this.userMap.get(e);if(!s)return;let o=`peer leave [${e}]`;T(t)||(o+=`:${Ra[t]}`),this._log.info(o);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",s.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(s=>s[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 s=t[this.key];if(e.findIndex(o=>o[this.key]===t[this.key])<0){this._log.info(`remote [${s}] unpublish`);let o=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(s),this.emit("6",{prevMuteState:o,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var u;let s=t[this.key];if(s===this.mySelfId)return;let{flag:o,userId:n,tinyId:a}=t,c=Ri(o,n),d=(u=this.remotePublishedUserMap.get(s))==null?void 0:u.muteState;if(d){let p=this.remotePublishedUserMap.get(s);p&&p.flag!==o&&(p.flag=o,this._log.info(`remote publish updated: ${JSON.stringify(p.muteState)}`),this.emit("6",{prevMuteState:d,muteState:c,flag:o}))}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:Ri(0,n),muteState:c,flag:o})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function cd({timesInSecond:r,maxSizeInSecond:i,getSize:e}){return W((t,s)=>{let o=new Map;return g.on(E.ROOM_DESTROY,({room:n})=>o.delete(n)),function(...n){let a=o.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.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>=r||a.totalSizeInSecond>i))throw new b({code:A.INVALID_OPERATION,message:L({key:M.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=r,isSize:a.totalSizeInSecond>i,name:s,timesInSecond:r,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var Su=!0,Iu=function(){var r;Su&&(Su=!1,I.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Ct}/en/index.html`),console.info(`* Changelog: ${Ct}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),I.info("TRTC Web SDK Version:",Re),I.info("UA:",navigator.userAgent),I.info(`URL: ${location.href}${((r=self.frameElement)==null?void 0:r.tagName)==="IFRAME"?" in iframe":""}`),As().then(i=>{i&&I.info(lt)}))};var ot={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"};function Cu({code:r,params:i,enableDocLink:e=!1}){let t="",s,o=rt[r];try{s=Au[o]}catch(n){s=Au.UNKNOWN_ERROR}return K(s)?t=s(i):z(s)&&(t=s),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var Au=P(N({},Ae),{INVALID_PARAMETER({fnName:r}){return`the parameters of the '${r}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:r,rule:i,fnName:e,value:t}){let s=`${r||i.name}`,o="";return Array.isArray(i.type)?o=i.type.join("|"):o=i.type,`'${s}' must be type of ${o} when calling ${e}(), received type: ${fe(t)}.`},INVALID_PARAMETER_EMPTY({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:r,rule:i,fnName:e,value:t}){let s=`${r||i.name}`,o=`${i.instanceOf.name||i.instanceOf}`;return`'${s}' must be instanceof ${o} when calling ${e}(), received type: ${fe(t)}.`},INVALID_PARAMETER_RANGE({key:r,rule:i,fnName:e,value:t}){return`'${r||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:r,rule:i,fnName:e}){return`'${r||i.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:r,rule:i,value:e}){return`the min value of ${r||i.name} is ${i.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:r,rule:i,value:e}){return`the max value of ${r||i.name} is ${i.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:r,fnName:i}){return`'${r}' is not found in the document object when calling ${i}().`},INVALID_ELEMENT_ID_TYPE({key:r,fnName:i,type:e}){return`the element corresponding to '${r}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`},INVALID_STREAM_ID({key:r}){return`'${r}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:r}){return`'${r}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:r}){return`'${r}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:r}){return`'${r}' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.`},INVALID_ROOM_ID_REQUIED(){return"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required."},INVALID_STREAM_TYPE:({fnName:r})=>`'streamType' is required when 'userId' is not '*', calling ${r}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:r}){return`the API '${r}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:r}){return`cannot ${r} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:r,value:i}){return`cannot ${r} because remote user(userId: ${i.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:r,value:i}){return`cannot ${r} because remote user(userId: ${i.userId}) does not publishing ${i.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:r}){return`you are already ${r}(), cannot repeated call '${r}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:r}){return`cannot call '${r}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:r}){return`cannot call '${r}' because the microphone is not turned on.`},INVALID_BUFFER_EMPTY:({key:r})=>`the buffer size of paramerter '${r}' 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:r})=>`you need to call ${r}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:r}){return`the current browser does not support the capability of the function '${r}' 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:r}){return`cannot call ${r} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:r,error:i}){return`'${r}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:r,deviceType:i=Yi(r),error:e}){return`NotFoundError, no ${i} detected, please check your device and the configuration on '${r}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:r,deviceType:i=Yi(r),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:r,deviceType:i=Yi(r),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:r,deviceType:i=Yi(r),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:r,deviceType:i=Yi(r),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:r,deviceType:i=Yi(r),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:r,deviceType:i=Yi(r),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:r}){return`camera recover capture failed ${(r==null?void 0:r.name)||""}: ${(r==null?void 0:r.originMessage)||(r==null?void 0:r.message)}`},MICROPHONE_RECOVER_FAILED({error:r}){return`microphone recover capture failed ${(r==null?void 0:r.name)||""}: ${(r==null?void 0:r.originMessage)||(r==null?void 0:r.message)}`},OPERATION_FAILED({fnName:r,error:i}){return`'${r}' 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:r}){return`an error was caught on trtc.on('${r}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:r,error:i}){return`video context error ${r} ${(i==null?void 0:i.name)||""} ${(i==null?void 0:i.message)||""}`},SERVER_ERROR({fnName:r,error:i}){return`'${r}' got server error: ${i==null?void 0:i.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:r,url:i}){return`You need to buy packages for ${r}. Refer to: ${i}`},ACCOUNT_NO_MONEY:({fnParams:r})=>`your TRTC account run out of credit, please recharge.${r.sdkAppId?` SDKAppId: ${r.sdkAppId}`:""}`,OPERATION_ABORT({fnName:r}){return`'${r}' abort`},UNKNOWN_ERROR({fnName:r,error:i}){return`'${r}' throw unknown exception${i?`, error: ${i.toString()}.`:"."}`}});function Yi(r){if(!r)return"camera";let i=r.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var Ki=class extends Error{constructor({code:e,extraCode:t,message:s="",messageParams:o,fnName:n="",originError:a}){var d;let c;s?c=s:c=Cu({code:t||e,params:N({fnName:n,error:a},o)});super(c);l(this,"name","RtcError");l(this,"code");l(this,"extraCode");l(this,"functionName");l(this,"message");l(this,"handler");l(this,"originError");this.name=rt[e],this.code=e,this.extraCode=t,this.functionName=n,this.originError=a,this.message=c,this.extraCode===5302&&((d=this.originError)==null?void 0:d.message.includes("system"))&&(this.handler=()=>{let u={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},p={startLocalVideo:"webcam",startLocalAudio:"microphone"},m=document.createElement("a");Ti?m.href=`ms-settings:privacy-${p[this.functionName]}`:bt&&(m.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${u[this.functionName]}`),m.href.length>0&&m.click()})}static convertFrom(e,t,s){let o=e;if(e instanceof b){let{stack:n}=e,a={code:w.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case A.INVALID_PARAMETER:a.code=w.INVALID_PARAMETER,a.message=e.message;break;case A.INVALID_OPERATION:a.code=w.INVALID_OPERATION;break;case A.NOT_SUPPORTED:case A.NOT_SUPPORTED_H264:a.code=w.ENV_NOT_SUPPORTED,e.getCode()===A.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(Ae.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case A.JOIN_ROOM_FAILED:a.messageParams={fnParams:s};case A.SERVER_TIMEOUT:case A.SWITCH_ROLE_FAILED:a.code=w.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case A.API_CALL_ABORTED:a.code=w.OPERATION_ABORT;break;case A.DEVICE_NOT_FOUND:case A.DEVICE_AUTO_RECOVER_FAILED:case A.INITIALIZE_FAILED:a.code=5300,e.name&&(a.extraCode=p_(e.name));break;case A.UNKNOWN:break;default:a.code=w.OPERATION_FAILED}o=new Ki(a),n&&(o.stack+=n.substr(n.indexOf(`
|
|
62
|
+
`)))}else{if(e instanceof Ki)return e;o=new Ki({code:w.UNKNOWN_ERROR,fnName:t,originError:e})}return o}};function p_(r){let i;switch(r){case"NotFoundError":i=5301;break;case"NotAllowedError":i=5302;break;case"NotReadableError":i=5303;break;case"OverconstrainedError":i=5304;break;case"InvalidStateError":i=5305;break;case"SecurityError":i=5306;break;case"AbortError":i=5307;break;default:i=5300}return i}var k=Ki;var Ru={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},yu={type:"object",properties:{systemAudio:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},profile:{type:["string","object"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack},audioTrack:{instanceOf:MediaStreamTrack}}},Gr={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(r,i,e){if(z(r)&&!document.getElementById(r))throw new k({code:w.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},bu={name:"userId",required:!0,type:"string"},Nu={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[ot.AUDIO_PROFILE_STANDARD,ot.AUDIO_PROFILE_STANDARD_STEREO,ot.AUDIO_PROFILE_HIGH,ot.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function to(r,i){if(!r)throw new k({code:w.INVALID_OPERATION,extraCode:5101,fnName:i})}function vu(r,i,e){if(!r)throw new k({code:w.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}var qy={type:"number",notLessThanZero:!0},__={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(r,i,e){if(this._room.isJoined)throw new k({code:w.INVALID_OPERATION,extraCode:5104,fnName:e});if(r.roomId){if(z(r.roomId))throw new k({code:w.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});if(!(/^[1-9]\d*$/.test(String(r.roomId))&&r.roomId<4294967295))throw new k({code:w.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:i}})}else if(r.strRoomId){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(r.strRoomId))throw new k({code:w.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:i}})}else throw new k({code:w.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:Gr,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:Ru},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.videoTrack)&&ri())throw new k({code:w.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:P(N({},Gr),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:Ru}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:Nu},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.audioTrack)&&ri())throw new k({code:w.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:Nu}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:Gr,publish:{type:"boolean"},option:yu},validate(r,i,e,t,s){var o;if(!((o=r==null?void 0:r.option)!=null&&o.videoTrack)&&ri())throw new k({code:w.ENV_NOT_SUPPORTED,extraCode:5201});if(!xs())throw new k({code:w.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:Gr,publish:{type:"boolean"},option:yu}},muteRemoteAudio:[bu,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[bu,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:Gr,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(r,i,e){to(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(vu(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new k({code:w.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:r}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:P(N({},Gr),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(r,i,e){to(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(vu(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new k({code:w.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:r}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(r,i,e){if(r.userId!=="*"&&T(r.streamType))throw new k({code:w.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(r,i,e){to(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(r,i,e,t){if(!Gi)throw new k({code:w.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new k({code:w.INVALID_OPERATION,fnName:e,extraCode:5108});if(r.byteLength>1e3)throw new k({code:w.INVALID_PARAMETER,extraCode:5018,fnName:e});if(r.byteLength===0)throw new k({code:w.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});to(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(r,i,e){if(!r&&!this._room.isMainStreamPublished||r&&!this._room.isAuxStreamPublished)throw new k({code:w.INVALID_OPERATION,extraCode:5109,messageParams:{key:i},fnName:e})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(r,i,e,t){if(r.byteLength>1e3)throw new k({code:w.INVALID_PARAMETER,extraCode:5018,fnName:e});if(r.byteLength===0)throw new k({code:w.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(r,i,e){if(to(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new k({code:w.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}}},Ce={TRTC:__};var Me=class extends Error{};function f_(r,i){let e=Nr(r);for(let t=0;t<i.length;t++)ei(e[t],i[t]);return e}function E_(r){this._resolve=Promise.resolve(r)}function g_(r){this._reject=Promise.reject(r)}var Zi=class{constructor(i,e){this.instance=i;this.group=e;this.started=!1;this.ops=[];this.startSame=()=>!0;this.mergeUpdate=f_;let t=Zi.instances.get(i);t?t.set(e,this):Zi.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=Zi.instances.get(i);return t&&t.get(e)||new Zi(i,e)}static gets(i,e){let t=Zi.instances.get(i),s=[];return t&&t.forEach((o,n)=>{e.test(n)&&s.push(o)}),s}action(i,e,t){let s=a=>{var c;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),a},o=a=>{var c,d;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new Me("start failed")),(d=this.currentOp)==null||d.action(),a},n={type:i,action:()=>e(...n.args).then(s,o),args:t,resolve:E_,reject:g_};try{switch(this.state){case 1:if(i===0)throw new Me("already started");break;case 4:if(i===2)throw new Me("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(s,o)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new Me("already start");break;case 3:switch(i.type){case 2:throw new Me("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Me("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new Me("keep stop");if(this.ops.slice(1).forEach(s=>s.reject(t)),this.ops=this.ops.slice(0,1),this.state===3)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,i.args),this.lastOp.promise;case 3:throw new Me("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Me("start not allowed after update");case 0:throw new Me("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new Me("keep start")),new Me("already start")}}i.promise=new Promise((t,s)=>{i._resolve?i._resolve.then(t):i.resolve=t,i._reject?i._reject.catch(s):i.reject=s});let{action:e}=i;return i.action=()=>e().then(i.resolve,i.reject),this.ops.push(i),i.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}},Gt=Zi;Gt.instances=new WeakMap;var Hn=new WeakMap,Gn=(r,i)=>{if(i instanceof Me){let{stack:e}=i;i=new k({code:w.OPERATION_ABORT,message:`${r} abort: ${i.message}`,fnName:r}),e&&(i.stack+=e.substr(e.indexOf(`
|
|
63
|
+
`)))}throw i};function Mi(r,i){return W((e,t)=>function(...s){let o=Gt.get(this,typeof r=="string"?r:r.call(this,...s));return o?(i&&(o.startSame=i.bind(this)),o.action(0,e.bind(this),s).catch(Gn.bind(null,t))):e.apply(this,s)})}function er(r,i){let{merge:e,debounce:t}=i||{};return W((s,o)=>function(...n){let a=Gt.get(this,typeof r=="string"?r:r.call(this,...n));if(!a)return s.apply(this,n);if(e&&(a.mergeUpdate=e.bind(this)),t&&t.isNeedToDebounce.apply(this,n)){let{delay:c,getKey:d}=t;return new Promise((u,p)=>{var R,C;let m=(R=Hn.get(this))==null?void 0:R.get(d(...n));if(m){let{timeoutId:v,resolve:U}=m;clearTimeout(v),U()}let f=setTimeout(()=>{if(a.state===3||a.state===4)return u();a.action(2,s.bind(this),n).catch(Gn.bind(null,o)).then(u,p)},c);Hn.has(this)?(C=Hn.get(this))==null||C.set(d(...n),{timeoutId:f,resolve:u}):Hn.set(this,new Map([[d(...n),{timeoutId:f,resolve:u}]]))})}return a.action(2,s.bind(this),n).catch(Gn.bind(null,o))})}function ki(r){return W((i,e)=>function(...t){let s=typeof r=="function"?r.call(this,...t):r;if(s instanceof RegExp)return Promise.all(Gt.gets(this,s).map(n=>n.action(3,()=>Promise.resolve(),t))).then(()=>i.call(this,...t));let o=Gt.get(this,s);return o?o.action(3,i.bind(this),t).catch(Gn.bind(null,e)):i.apply(this,t)})}var $={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",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"};function tr(r){return r==="sub"?"auxiliary":r==="auxiliary"?"sub":"main"}function ir(r){return r===ot.QOS_PREFERENCE_CLEAR?"detail":r===ot.QOS_PREFERENCE_SMOOTH?"motion":""}var T_=r=>r.startsWith("data:application/octet-stream;base64,"),S_=r=>r.startsWith("file://"),Wn=class{constructor(){l(this,"_log");this._log=I.createLogger({id:"fd"})}download(i,e){return _(this,null,function*(){let{type:t="blob"}=e||{};try{let s=x(),o;if(K(fetch)?o=yield this.downloadWithFetch(i,t):o=yield this.downloadWithXHR(i,t),!o||!o.data)throw new Error("data is empty");let n=x()-s;return this._log.info(`downloaded: ${i}, return type: ${t}, cost: ${n}ms`),D.addSuccessEvent({key:522700,cost:x()-s}),o.data}catch(s){throw this._log.error(`failed to download: ${i}, error: ${s}`),D.addFailedEvent({key:522700,error:s}),s}})}downloadWithFetch(i,e){return _(this,null,function*(){this._log.info(`download with fetch: ${i}, return type: ${e}`);try{let t=yield fetch(i);if(!t.ok)throw new Error("network response was not ok");let s;return e==="arraybuffer"?s=yield t.arrayBuffer():s=yield t.blob(),{data:s}}catch(t){throw t}})}downloadWithXHR(i,e){return this._log.info(`download with xhr: ${i}, return type: ${e}`),new Promise((t,s)=>{let o=new XMLHttpRequest;o.open("GET",i,!0),o.responseType=e,o.onload=()=>{o.status===200||o.status===0&&o.response?t({data:o.response}):s(new Error("XHR failed"))},o.onerror=s,o.send(null)})}loadWasm(i,e){return _(this,null,function*(){this._log.info(`loadWasm ${i}, importObject: ${JSON.stringify(e)}`);let t=x(),s=null,o=null;if(K(WebAssembly.instantiateStreaming)&&!T_(i)&&!S_(i)&&K(fetch))try{let n=fetch(i);s=(yield WebAssembly.instantiateStreaming(n,e)).instance}catch(n){o=n}if(!s)try{let n=yield this.download(i,{type:"arraybuffer"});s=(yield WebAssembly.instantiate(n,e)).instance}catch(n){o=n}if(s){let n=x()-t;return this._log.info(`loadedWasm ${i}, cost: ${n}ms`),D.addSuccessEvent({key:522701,cost:n}),s}throw this._log.error(`failed to loadWasm ${i}, error: ${o}`),D.addFailedEvent({key:522701,error:o}),o})}};y([it({settings:{timeout:0,retries:3},onRetrying(r){this._log.warn(`download retrying: ${r}`)}})],Wn.prototype,"download",1);var Du=new Wn;function Ou({TRTC:r,room:i,errorModule:e,assetsPath:t}){return{TRTC:r,room:i,assetsPath:t,fileDownloader:Du,innerEmitter:g,constants:ya,environment:Rr,utils:we,eventLogger:Z,log:this.room.getLogger(),loggerManager:I,errorModule:e,kvStatManager:D,rtcDectection:Et,trtc:this,clearStarted:(s,o)=>{let n=s.getAlias(),a=Gt.instances.get(this);if(!!a)if(o){let c=a.get(n+o);if(!c)return;c.started=!1}else a.forEach((c,d)=>{d.startsWith(n)&&(c.started=!1)})}}}var Mu=(r,i)=>{let{emit:e}=r;return r.emit=(...t)=>{try{return e.apply(r,t)}catch(s){let o=L({key:M.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return I.warn(`${o}
|
|
64
64
|
|
|
65
|
-
${s.stack}`),!1}},r};var Wn=new WeakMap;function kl(r,i){return J((e,t)=>function(...s){var a,c;let o=(a=Wn.get(this))==null?void 0:a.get(i(...s));o&&o>0&&clearTimeout(o);let n=window.setTimeout(()=>{e.apply(this,s)},r);Wn.has(this)?(c=Wn.get(this))==null||c.set(i(...s),n):Wn.set(this,new Map([[i(...s),n]]))})}var Ll="5.8.2-beta.2";function ke(...r){return J((i,e)=>function(...t){try{jn.call(this,r,t,e,this._name)}catch(s){return Promise.reject(s)}return i.apply(this,t)})}function dd(...r){return J((i,e)=>function(...t){try{jn.call(this,r,t,e,this._name)}catch(s){throw s}return i.apply(this,t)})}function jn(r,i,e,t){if(he(r))for(let s=0;s<r.length;s++)Jn.call(this,{rule:r[s],value:i[s],key:r[s].name,fnName:e,className:t});else Jn.call(this,{rule:r,value:i[0],key:r.name,fnName:e,className:t})}function Jn({rule:r,value:i,key:e,fnName:t,className:s}){function o(c){return{code:w.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:r,value:i}}}if(T(i)){if(r.required)throw new k(o(5001));if(T(r.defaultValue)){W(r.validate)&&r.validate.call(this,i,e,t,s,this);return}i=r.defaultValue}if(Array.isArray(r.type)){let c=!1;for(let d=0;d<r.type.length;d++)r.type[d]===null&&i===null&&(c=!0),W(r.type[d])&&i instanceof r.type[d]&&(c=!0),Y(r.type[d])&&fe(i)===r.type[d].toLowerCase()&&(c=!0);if(!c)throw new k({code:w.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:r.type.map(d=>Ns(d)?zo(d):Y(d)?d:fe(d))},value:i}})}else if(!T(r.type)&&fe(i)!==r.type)throw new k(o(5002));if(r.allowEmpty===!1){let c=ee(i)&&(i===0||Number.isNaN(i)),d=Y(i)&&i.trim()==="";if(c||d)throw new k(o(5003))}if(r.notLessThanZero&&ee(i)&&i<0)throw new k(o(5006));if(!T(r.min)&&ee(i)&&i<r.min)throw new k(o(5007));if(!T(r.max)&&ee(i)&&i>r.max)throw new k(o(5008));if(Y(r.instanceOf)){if(!i||i._name!==r.instanceOf)throw new k(o(5004))}else if(W(r.instanceOf)&&!(i instanceof r.instanceOf))throw new k(o(5004));if(Array.isArray(r.values)&&!r.values.includes(i))throw new k(o(5005));let{properties:n}=r;Je(n)&&mt(i)&&Object.keys(n).forEach(c=>{Jn.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:s})});let{arrayItem:a}=r;Je(a)&&he(i)&&i.forEach((c,d)=>{Jn.call(this,{rule:a,value:c,key:`${e}[${d}]`,fnName:t,className:s})}),W(r.validate)&&r.validate.call(this,i,e,t,s,this)}function oe(r={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t}=r;return J((s,o)=>function(...n){function a(l,p,m){if(m&&m.includes(l))return"hided";if(e){let f=e(...n);if(n[f.argIndex]===p)return f.value}if(p===n||l in n)return p;try{return p instanceof HTMLElement?`id: ${p.id} type:${fe(p)}`:(JSON.stringify(p),p)}catch(f){return`type:${fe(p)}`}}let c=this._log||I;n.length>0?c.info(`${o}() ${JSON.stringify(n,(l,p)=>a(l,p,["userSig","privateMapKey"]))}`):c.info(`${o}()`);let d=t?t(...n):un[o];try{let l=s.apply(this,n),p=x();return bs(l)?l.then(m=>(c.info(`${o}() success ${i.call(this,...n)}`),D.addSuccessEvent({key:d,cost:x()-p}),m)).catch(m=>{throw m=k.convertFrom.call(this,m,o,n.length===1?n[0]:n),c.error(`${o}() failed ${i.call(this,...n)} ${m} params: ${JSON.stringify(n,a)}`),D.addFailedEvent({key:d,error:m}),m}):(D.addSuccessEvent({key:d}),l)}catch(l){throw l=k.convertFrom.call(this,l,o),c.error(`${o}() failed ${l} params: ${JSON.stringify(n,a)}`),D.addFailedEvent({key:d,error:l}),l}})}var qn=r=>J((i,e)=>function(t,s){return _(this,null,function*(){let o=this._plugins.get(t);if(!o)throw this._log.error(`plugin ${String(t)} is not found`),new k({code:w.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(W(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new k({code:w.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return jn.call(this,o.getValidateRule(r),[s],e,"TRTC"),i.call(this,o,s)})});var Xn=0,ud=class{constructor(i,e){u(this,"player");u(this,"publisher");u(this,"mixInput");this.mixInput=new kr(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)}}reset(){this.seek(0),this.mixInput.connect()}seek(i){!this.player||i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i)}play(){var i,e;return(i=this.publisher)==null||i.play(),(e=this.player)==null?void 0:e.play()}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function Hr(r,i){if(i&&typeof i!="function")throw new k({code:w.INVALID_PARAMETER,message:`start audioMixer plugin: param ${r} should be a function.`})}var Gr=class{constructor(i){this.core=i;u(this,"log");u(this,"mixedMusicMap",new Map);u(this,"cacheMusicMap",new Map);Xn=Xn+1,this.log=i.log.createChild({id:`${this.getAlias()}${Xn}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Xn}`),this.core=i}getName(){return Gr.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return Gr.startValidateRule;case"update":return Gr.updateValidateRule;case"stop":return Gr.stopValidateRule}}start(i){return _(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:s}=i;if(this.mixedMusicMap.has(t))return;let o=this.cacheMusicMap.get(t);o?i.url?o.reset():(o.mixInput.replaceSource(i.track),o.mixInput.connect()):(o=new ud(i,e.audioManager),this.cacheMusicMap.set(t,o)),o.updateListener(i),o.updateSettings(i),yield o.play(),this.mixedMusicMap.set(t,o),this.log.info(`start mix audio track ${t} success.`),D.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return _(this,null,function*(){let{id:e,operation:t,seekFrom:s,playbackRate:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),T(t)||n.setOperation(t),T(s)||n.seek(s),this.kvUpload(i)})}stop(e){return _(this,arguments,function*({id:i}){var t;this.mixedMusicMap.has(i)&&(this.log.info(`remove music source, music id: ${i}`),(t=this.mixedMusicMap.get(i))==null||t.stop(),this.mixedMusicMap.delete(i)),i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:s,playbackRate:o,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:d,onEnded:l}=i;e&&D.addCount({key:502711}),t&&D.addCount({key:502703}),s&&D.addCount({key:502704}),o&&D.addCount({key:502705}),n&&D.addCount({key:502706}),a&&D.addCount({key:502707}),typeof c!="function"&&D.addCount({key:502709}),typeof l!="function"&&D.addCount({key:502710}),typeof d!="function"&&D.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>this.stop({id:e}))}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}},Mi=Gr;u(Mi,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let s=i.url.split("?")[0],o=["mp3","ogg","wav","flac"],n=s.split(".").pop(),a=o.indexOf(n)>=0,c=s.startsWith("blob"),d=s.startsWith("data");if(!(a||c||d))throw new k({code:w.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new k({code:w.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});Hr("onTimeUpdate",i.onTimeUpdate),Hr("onEnded",i.onEnded),Hr("onDurationChange",i.onDurationChange)}}),u(Mi,"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){Hr("onTimeUpdate",i.onTimeUpdate),Hr("onEnded",i.onEnded),Hr("onDurationChange",i.onDurationChange)}}),u(Mi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),u(Mi,"Name","AudioMixer");var A_=r=>(r=Number(r),r>0&&r<14e8),Qn=0,ld,Wr=class{constructor(i){this.core=i;u(this,"log");u(this,"audioContext",qe("denoiser"));u(this,"workletNode");Qn=Qn+1,this.log=i.log.createChild({id:`${this.getAlias()}${Qn}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${Qn}`),i.assetsPath&&this.preload(`${i.assetsPath}/denoiser-wasm.js`)}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,s,o){if(!i.room.audioManager.hasAudioTrack)throw new k({code:w.INVALID_OPERATION,extraCode:5106,fnName:s})}}}preload(i){return ld||(ld=this.doPreload(i)),ld}doPreload(i){return _(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Gi(this.audioContext,t)}finally{URL.revokeObjectURL(t)}})}getName(){return Wr.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return Wr.startValidateRule(this.core);case"update":return Wr.updateValidateRule;case"stop":return Wr.stopValidateRule}}start(i){return _(this,null,function*(){let{room:e}=this.core;if(yield this.preload(`${i.assetsPath}/denoiser-wasm.js`),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:s,sign:o,status:n,message:a}=yield R_(P(N({},i),{timestamp:t}));if(!s)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${s}. Message: ${a}`),new k({code:w.INVALID_PARAMETER,message:a});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:t,sign:o,status:n}}),this.workletNode.port.onmessage=c=>{let{data:d}=c;d.type==="cost"&&this.log.debug(`[RTCAIDenoiser] ${d.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return _(this,null,function*(){})}stop(){return _(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}destroy(){}},tr=Wr;u(tr,"updateValidateRule",{type:"object"}),u(tr,"stopValidateRule",{type:"object"}),u(tr,"Name","AIDenoiser");var xl={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};function C_(r){let i;return A_(r)?i=xl.MAIN_OVERSEA:i=xl.MAIN,i}function R_(s){return _(this,arguments,function*({sdkAppId:r,userId:i,userSig:e,timestamp:t}){let n=`https://${C_(r)}/api/v1/audioAiAuth?sdkAppId=${r}&userId=${i}&userSig=${e}×tamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:d,sign:l,status:p}}=yield a.json();if(p==="1")return{auth:!0,sign:l,status:p,message:d};let m="Init RTCAIDenoiser failed.",f="";switch(c){case 1:f="Please check your params.";break;case 2:f="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:f="Server is invalid. Please contact our engineer. ";break;case 4:f="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:f="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:f="Your version is not supported.";break}return{auth:!1,status:p,message:d?`${m} Reason: ${d}. ${f}`:`${m}, ${f}`}})}var Pl=Se(Ne(),1);var hd=class extends Pl.EventEmitter{constructor(){super();this.state="nominal";this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return _(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!pe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){Z.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,s=e[e.length-1];this.state=s.state,(this.stateNum>3||t>3)&&I.info(`${s.source}: ${s.state}`),this.emit("state-changed",{type:s.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){Z.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},y_=new hd,md=y_;var pd=0,Ed=class{constructor(i){this.core=i;u(this,"log");u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(this,"_subStreamSeiMessageList",[]);u(this,"_seiWorker");pd++,this.log=i.log.createChild({id:`${this.getAlias()}${pd}`}),this.log.info(`[sei] created id=${this.getAlias()}${pd}`),this.core=i}encode(i,e){try{let t=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList,s=_d(i,t);s&&this.log.debug(`${s} sei sent`)}catch(t){this.log.warn(t)}return i}decode(i,e){return fd(i).forEach(t=>{this.core.trtc.emit($.SEI_MESSAGE,{seiPayloadType:t.seiPayloadType,data:t.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})}),i}destroy(){}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(i){yi?(this._seiWorker=b_(),this._seiWorker.onmessage=e=>{this.core.trtc.emit($.SEI_MESSAGE,P(N({},e.data),{streamType:Zi(e.data.streamType)}))},this._seiWorker.onerror=e=>{this.log.error("seiWorker error: ",e.message)},this.core.room.videoManager.enableSEI({seiWorker:this._seiWorker})):this.core.room.videoManager.enableSEI({encoder:this.encode.bind(this),decoder:this.decode.bind(this)})}stop(i){this.core.room.videoManager.disableSEI()}update({buffer:i,options:e}){var o;let t=[e.seiPayloadType,i],s=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),s&&this._smallSeiMessageList.push(t)),this.core.innerEmitter.emit("265",{room:this.core.room,data:t,isMain:!e.toSubStream}),(o=this._seiWorker)==null||o.postMessage({message:t,isMain:!e.toSubStream,small:s})}getName(){return Ed.Name}getAlias(){return"sei"}getGroup(){return"sei"}},to=Ed;u(to,"Name","SEI");function Ul([r,i]){let e=i.byteLength,t=parseInt(String(e/255),10),s=e%255,o=[];o.push(0,0,0,1,6,r);for(let a=0;a<t;a++)o.push(255);o.push(s);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Ni(new DataView(new Uint8Array(o).buffer),!0)}function Bl(r){return r.type==="empty"||r.data.byteLength===0}function $l(r){return r.getInt32(0)===1&&r.getInt8(4)===6}function Fl(r){let i=0,e=0,t=new DataView(r);for(let s=0;s<r.byteLength;s++)switch(t.getUint8(s)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function _d(r,i){if(i.length>0&&r.data.byteLength>0){let e=Fl(r.data),t=9-e;if(t<=0)return 0;let s=i.splice(0,t).reverse().map(Ul),o=s.reduce((l,p)=>l+p.dataView.byteLength,0),n=new ArrayBuffer(o+r.data.byteLength),a=new DataView(n),c=new DataView(r.data),d=0;for(let l=0;l<s.length;l++)for(let p=0;p<s[l].dataView.byteLength;p++)a.setInt8(d++,s[l].dataView.getInt8(p));for(let l=0;l<r.data.byteLength;l++)a.setInt8(d++,c.getInt8(l));return r.data=n,s.length}return 0}function fd(r){try{let i=new DataView(r.data);if(Bl(r)||!$l(i))return[];let e=[],t=0,s=-1,o=-1;for(let n=0;n<r.data.byteLength;n++){let a=i.getUint8(n);if(a===0)t++;else if(a===1){if(t===2||t===3){let c=n-t;if(s===-1?s=c:o===-1&&(o=c,e.push(new Ni(new DataView(i.buffer.slice(s,o)))),s=c,o=-1),!(i.getUint8(n+1)===6)){r.data=i.buffer.slice(c);break}}t=0}else t=0}return e.reverse()}catch(i){return[]}}function wl(r){return new TransformStream({transform(i,e){_d(i,r),e.enqueue(i)}})}function Vl(r,i){return new TransformStream({transform(e,t){fd(e).forEach(s=>{self.postMessage({seiPayloadType:s.seiPayloadType,data:s.seiPayload.buffer,userId:r,streamType:i})}),t.enqueue(e)}})}function b_(){let r=[Ni],i=[Fl,Bl,$l,Ul,_d,fd,wl,Vl],e=()=>{let a=[],c=[],d=[];self.onmessage=l=>{l.data.isMain?(a.push(l.data.message),l.data.small&&d.push(l.data.message)):c.push(l.data.message)},self.onrtctransform=l=>{let{options:p}=l.transformer,m=p.isReceiver?Vl(p.userId,p.streamType):wl(p.isMain?p.small?d:a:c);l.transformer.readable.pipeThrough(m).pipeTo(l.transformer.writable)}},t=`(()=>{${r.map(a=>`const ${a.name}=(()=>${a.toString()})()`).join(`
|
|
65
|
+
${s.stack}`),!1}},r};var Jn=new WeakMap;function ku(r,i){return W((e,t)=>function(...s){var a,c;let o=(a=Jn.get(this))==null?void 0:a.get(i(...s));o&&o>0&&clearTimeout(o);let n=window.setTimeout(()=>{e.apply(this,s)},r);Jn.has(this)?(c=Jn.get(this))==null||c.set(i(...s),n):Jn.set(this,new Map([[i(...s),n]]))})}var Lu="5.8.2-beta.4";function ke(...r){return W((i,e)=>function(...t){try{qn.call(this,r,t,e,this._name)}catch(s){return Promise.reject(s)}return i.apply(this,t)})}function ud(...r){return W((i,e)=>function(...t){try{qn.call(this,r,t,e,this._name)}catch(s){throw s}return i.apply(this,t)})}function qn(r,i,e,t){if(he(r))for(let s=0;s<r.length;s++)jn.call(this,{rule:r[s],value:i[s],key:r[s].name,fnName:e,className:t});else jn.call(this,{rule:r,value:i[0],key:r.name,fnName:e,className:t})}function jn({rule:r,value:i,key:e,fnName:t,className:s}){function o(c){return{code:w.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:r,value:i}}}if(T(i)){if(r.required)throw new k(o(5001));if(T(r.defaultValue)){K(r.validate)&&r.validate.call(this,i,e,t,s,this);return}i=r.defaultValue}if(Array.isArray(r.type)){let c=!1;for(let d=0;d<r.type.length;d++)r.type[d]===null&&i===null&&(c=!0),K(r.type[d])&&i instanceof r.type[d]&&(c=!0),z(r.type[d])&&fe(i)===r.type[d].toLowerCase()&&(c=!0);if(!c)throw new k({code:w.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:r.type.map(d=>vs(d)?Yo(d):z(d)?d:fe(d))},value:i}})}else if(!T(r.type)&&fe(i)!==r.type)throw new k(o(5002));if(r.allowEmpty===!1){let c=ee(i)&&(i===0||Number.isNaN(i)),d=z(i)&&i.trim()==="";if(c||d)throw new k(o(5003))}if(r.notLessThanZero&&ee(i)&&i<0)throw new k(o(5006));if(!T(r.min)&&ee(i)&&i<r.min)throw new k(o(5007));if(!T(r.max)&&ee(i)&&i>r.max)throw new k(o(5008));if(z(r.instanceOf)){if(!i||i._name!==r.instanceOf)throw new k(o(5004))}else if(K(r.instanceOf)&&!(i instanceof r.instanceOf))throw new k(o(5004));if(Array.isArray(r.values)&&!r.values.includes(i))throw new k(o(5005));let{properties:n}=r;Je(n)&&pt(i)&&Object.keys(n).forEach(c=>{jn.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:s})});let{arrayItem:a}=r;Je(a)&&he(i)&&i.forEach((c,d)=>{jn.call(this,{rule:a,value:c,key:`${e}[${d}]`,fnName:t,className:s})}),K(r.validate)&&r.validate.call(this,i,e,t,s,this)}function oe(r={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t}=r;return W((s,o)=>function(...n){function a(u,p,m){if(m&&m.includes(u))return"hided";if(e){let f=e(...n);if(n[f.argIndex]===p)return f.value}if(p===n||u in n)return p;try{return p instanceof HTMLElement?`id: ${p.id} type:${fe(p)}`:(JSON.stringify(p),p)}catch(f){return`type:${fe(p)}`}}let c=this._log||I;n.length>0?c.info(`${o}() ${JSON.stringify(n,(u,p)=>a(u,p,["userSig","privateMapKey"]))}`):c.info(`${o}()`);let d=t?t(...n):un[o];try{let u=s.apply(this,n),p=x();return Ns(u)?u.then(m=>(c.info(`${o}() success ${i.call(this,...n)}`),D.addSuccessEvent({key:d,cost:x()-p}),m)).catch(m=>{throw m=k.convertFrom.call(this,m,o,n.length===1?n[0]:n),c.error(`${o}() failed ${i.call(this,...n)} ${m} params: ${JSON.stringify(n,a)}`),D.addFailedEvent({key:d,error:m}),m}):(D.addSuccessEvent({key:d}),u)}catch(u){throw u=k.convertFrom.call(this,u,o),c.error(`${o}() failed ${u} params: ${JSON.stringify(n,a)}`),D.addFailedEvent({key:d,error:u}),u}})}var Xn=r=>W((i,e)=>function(t,s){return _(this,null,function*(){let o=this._plugins.get(t);if(!o)throw this._log.error(`plugin ${String(t)} is not found`),new k({code:w.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(K(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new k({code:w.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return qn.call(this,o.getValidateRule(r),[s],e,"TRTC"),i.call(this,o,s)})});var Qn=0,hd=class{constructor(i,e){l(this,"player");l(this,"publisher");l(this,"mixInput");this.mixInput=new xr(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)}}reset(){this.seek(0),this.mixInput.connect()}seek(i){!this.player||i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i)}play(){var i,e;return(i=this.publisher)==null||i.play(),(e=this.player)==null?void 0:e.play()}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function Wr(r,i){if(i&&typeof i!="function")throw new k({code:w.INVALID_PARAMETER,message:`start audioMixer plugin: param ${r} should be a function.`})}var Jr=class{constructor(i){this.core=i;l(this,"log");l(this,"mixedMusicMap",new Map);l(this,"cacheMusicMap",new Map);Qn=Qn+1,this.log=i.log.createChild({id:`${this.getAlias()}${Qn}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Qn}`),this.core=i}getName(){return Jr.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return Jr.startValidateRule;case"update":return Jr.updateValidateRule;case"stop":return Jr.stopValidateRule}}start(i){return _(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:s}=i;if(this.mixedMusicMap.has(t))return;let o=this.cacheMusicMap.get(t);o?i.url?o.reset():(o.mixInput.replaceSource(i.track),o.mixInput.connect()):(o=new hd(i,e.audioManager),this.cacheMusicMap.set(t,o)),o.updateListener(i),o.updateSettings(i),yield o.play(),this.mixedMusicMap.set(t,o),this.log.info(`start mix audio track ${t} success.`),D.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return _(this,null,function*(){let{id:e,operation:t,seekFrom:s,playbackRate:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),T(t)||n.setOperation(t),T(s)||n.seek(s),this.kvUpload(i)})}stop(e){return _(this,arguments,function*({id:i}){var t;this.mixedMusicMap.has(i)&&(this.log.info(`remove music source, music id: ${i}`),(t=this.mixedMusicMap.get(i))==null||t.stop(),this.mixedMusicMap.delete(i)),i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:s,playbackRate:o,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:d,onEnded:u}=i;e&&D.addCount({key:502711}),t&&D.addCount({key:502703}),s&&D.addCount({key:502704}),o&&D.addCount({key:502705}),n&&D.addCount({key:502706}),a&&D.addCount({key:502707}),typeof c!="function"&&D.addCount({key:502709}),typeof u!="function"&&D.addCount({key:502710}),typeof d!="function"&&D.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((i,e)=>this.stop({id:e}))}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}},Li=Jr;l(Li,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let s=i.url.split("?")[0],o=["mp3","ogg","wav","flac"],n=s.split(".").pop(),a=o.indexOf(n)>=0,c=s.startsWith("blob"),d=s.startsWith("data");if(!(a||c||d))throw new k({code:w.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new k({code:w.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});Wr("onTimeUpdate",i.onTimeUpdate),Wr("onEnded",i.onEnded),Wr("onDurationChange",i.onDurationChange)}}),l(Li,"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){Wr("onTimeUpdate",i.onTimeUpdate),Wr("onEnded",i.onEnded),Wr("onDurationChange",i.onDurationChange)}}),l(Li,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),l(Li,"Name","AudioMixer");var A_=r=>(r=Number(r),r>0&&r<14e8),zn=0,md,jr=class{constructor(i){this.core=i;l(this,"log");l(this,"audioContext",qe("denoiser"));l(this,"workletNode");zn=zn+1,this.log=i.log.createChild({id:`${this.getAlias()}${zn}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${zn}`),i.assetsPath&&this.preload(`${i.assetsPath}/denoiser-wasm.js`)}static startValidateRule(i){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(e,t,s,o){if(!i.room.audioManager.hasAudioTrack)throw new k({code:w.INVALID_OPERATION,extraCode:5106,fnName:s})}}}preload(i){return md||(md=this.doPreload(i)),md}doPreload(i){return _(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Ji(this.audioContext,t)}finally{URL.revokeObjectURL(t)}})}getName(){return jr.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return jr.startValidateRule(this.core);case"update":return jr.updateValidateRule;case"stop":return jr.stopValidateRule}}start(i){return _(this,null,function*(){let{room:e}=this.core;if(yield this.preload(`${i.assetsPath}/denoiser-wasm.js`),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:s,sign:o,status:n,message:a}=yield R_(P(N({},i),{timestamp:t}));if(!s)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${s}. Message: ${a}`),new k({code:w.INVALID_PARAMETER,message:a});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:t,sign:o,status:n}}),this.workletNode.port.onmessage=c=>{let{data:d}=c;d.type==="cost"&&this.log.debug(`[RTCAIDenoiser] ${d.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return _(this,null,function*(){})}stop(){return _(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}destroy(){}},rr=jr;l(rr,"updateValidateRule",{type:"object"}),l(rr,"stopValidateRule",{type:"object"}),l(rr,"Name","AIDenoiser");var xu={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};function C_(r){let i;return A_(r)?i=xu.MAIN_OVERSEA:i=xu.MAIN,i}function R_(s){return _(this,arguments,function*({sdkAppId:r,userId:i,userSig:e,timestamp:t}){let n=`https://${C_(r)}/api/v1/audioAiAuth?sdkAppId=${r}&userId=${i}&userSig=${e}×tamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:d,sign:u,status:p}}=yield a.json();if(p==="1")return{auth:!0,sign:u,status:p,message:d};let m="Init RTCAIDenoiser failed.",f="";switch(c){case 1:f="Please check your params.";break;case 2:f="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:f="Server is invalid. Please contact our engineer. ";break;case 4:f="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:f="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:f="Your version is not supported.";break}return{auth:!1,status:p,message:d?`${m} Reason: ${d}. ${f}`:`${m}, ${f}`}})}var Pu=Se(Ne(),1);var pd=class extends Pu.EventEmitter{constructor(){super();this.state="nominal";this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return _(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!pe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){Z.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,s=e[e.length-1];this.state=s.state,(this.stateNum>3||t>3)&&I.info(`${s.source}: ${s.state}`),this.emit("state-changed",{type:s.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){Z.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},y_=new pd,_d=y_;var fd=0,Td=class{constructor(i){this.core=i;l(this,"log");l(this,"_seiMessageList",[]);l(this,"_smallSeiMessageList",[]);l(this,"_subStreamSeiMessageList",[]);l(this,"_seiWorker");fd++,this.log=i.log.createChild({id:`${this.getAlias()}${fd}`}),this.log.info(`[sei] created id=${this.getAlias()}${fd}`),this.core=i}encode(i,e){try{let t=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList,s=Ed(i,t);s&&this.log.debug(`${s} sei sent`)}catch(t){this.log.warn(t)}return i}decode(i,e){return gd(i).forEach(t=>{this.core.trtc.emit($.SEI_MESSAGE,{seiPayloadType:t.seiPayloadType,data:t.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})}),i}destroy(){}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(i){Ni?(this._seiWorker=b_(),this._seiWorker.onmessage=e=>{this.core.trtc.emit($.SEI_MESSAGE,P(N({},e.data),{streamType:tr(e.data.streamType)}))},this._seiWorker.onerror=e=>{this.log.error("seiWorker error: ",e.message)},this.core.room.videoManager.enableSEI({seiWorker:this._seiWorker})):this.core.room.videoManager.enableSEI({encoder:this.encode.bind(this),decoder:this.decode.bind(this)})}stop(i){this.core.room.videoManager.disableSEI()}update({buffer:i,options:e}){var o;let t=[e.seiPayloadType,i],s=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),s&&this._smallSeiMessageList.push(t)),this.core.innerEmitter.emit("265",{room:this.core.room,data:t,isMain:!e.toSubStream}),(o=this._seiWorker)==null||o.postMessage({message:t,isMain:!e.toSubStream,small:s})}getName(){return Td.Name}getAlias(){return"sei"}getGroup(){return"sei"}},io=Td;l(io,"Name","SEI");function Uu([r,i]){let e=i.byteLength,t=parseInt(String(e/255),10),s=e%255,o=[];o.push(0,0,0,1,6,r);for(let a=0;a<t;a++)o.push(255);o.push(s);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Di(new DataView(new Uint8Array(o).buffer),!0)}function Bu(r){return r.type==="empty"||r.data.byteLength===0}function $u(r){return r.getInt32(0)===1&&r.getInt8(4)===6}function Fu(r){let i=0,e=0,t=new DataView(r);for(let s=0;s<r.byteLength;s++)switch(t.getUint8(s)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function Ed(r,i){if(i.length>0&&r.data.byteLength>0){let e=Fu(r.data),t=9-e;if(t<=0)return 0;let s=i.splice(0,t).reverse().map(Uu),o=s.reduce((u,p)=>u+p.dataView.byteLength,0),n=new ArrayBuffer(o+r.data.byteLength),a=new DataView(n),c=new DataView(r.data),d=0;for(let u=0;u<s.length;u++)for(let p=0;p<s[u].dataView.byteLength;p++)a.setInt8(d++,s[u].dataView.getInt8(p));for(let u=0;u<r.data.byteLength;u++)a.setInt8(d++,c.getInt8(u));return r.data=n,s.length}return 0}function gd(r){try{let i=new DataView(r.data);if(Bu(r)||!$u(i))return[];let e=[],t=0,s=-1,o=-1;for(let n=0;n<r.data.byteLength;n++){let a=i.getUint8(n);if(a===0)t++;else if(a===1){if(t===2||t===3){let c=n-t;if(s===-1?s=c:o===-1&&(o=c,e.push(new Di(new DataView(i.buffer.slice(s,o)))),s=c,o=-1),!(i.getUint8(n+1)===6)){r.data=i.buffer.slice(c);break}}t=0}else t=0}return e.reverse()}catch(i){return[]}}function wu(r){return new TransformStream({transform(i,e){Ed(i,r),e.enqueue(i)}})}function Vu(r,i){return new TransformStream({transform(e,t){gd(e).forEach(s=>{self.postMessage({seiPayloadType:s.seiPayloadType,data:s.seiPayload.buffer,userId:r,streamType:i})}),t.enqueue(e)}})}function b_(){let r=[Di],i=[Fu,Bu,$u,Uu,Ed,gd,wu,Vu],e=()=>{let a=[],c=[],d=[];self.onmessage=u=>{u.data.isMain?(a.push(u.data.message),u.data.small&&d.push(u.data.message)):c.push(u.data.message)},self.onrtctransform=u=>{let{options:p}=u.transformer,m=p.isReceiver?Vu(p.userId,p.streamType):wu(p.isMain?p.small?d:a:c);u.transformer.readable.pipeThrough(m).pipeTo(u.transformer.writable)}},t=`(()=>{${r.map(a=>`const ${a.name}=(()=>${a.toString()})()`).join(`
|
|
66
66
|
`)}
|
|
67
67
|
${i.map(a=>a.toString()).join(`
|
|
68
|
-
`)};(${e})()})()`,s=new Blob([t],{type:"text/javascript"}),o=URL.createObjectURL(s),n=new Worker(o);return URL.revokeObjectURL(o),n}var Hl=0,zn=new Set,Le=null;ha(Ll);var N_={RtcError:k,ErrorCode:w,ErrorCodeDictionary:It},Jr=class extends Gl.EventEmitter{constructor(e,t){super();u(this,"_room");u(this,"_eventListened",new Set);u(this,"_localVideoTrack",null);u(this,"_localAudioTrack",null);u(this,"_localScreenTrack",null);u(this,"_localScreenAudioTrack",null);u(this,"_localVideoConfig",null);u(this,"_localScreenConfig",null);u(this,"_localAudioConfig",null);u(this,"_remoteVideoConfigMap",new Map);u(this,"_remoteAudioConfigMap",new Map);u(this,"_remoteAudioMuteMap",new Map);u(this,"_mediaTrackMap",new WeakMap);u(this,"_log",I.createLogger({id:`t${++Hl}`}));u(this,"_plugins",new Map);u(this,"_networkQuality",null);u(this,"_speakerId");this._room=new e(N({logger:this._log,frameWorkType:Jr.frameWorkType},t)),this._log.debug(`TRTC.create() ${JSON.stringify(t,(s,o)=>s==="plugins"?o.map(n=>n.Name):o)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(s){return this._room.audioManager.dump(s)}}}),t.plugins&&t.plugins.forEach(s=>{this._use(s,t.assetsPath)}),this._use(Mi,t.assetsPath),this._use(tr,t.assetsPath),t.enableSEI&&Fi&&(this._use(to),this.startPlugin("SEI")),this._room.on("audio-volume",s=>{!s.find(o=>o.userId==="")&&this._localAudioTrack&&s.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),this.emit($.AUDIO_VOLUME,{result:s.sort((o,n)=>n.volume-o.volume)})}),this._room.videoManager.on("error",({reason:s,error:o})=>{this._log.error(new k({code:w.OPERATION_FAILED,extraCode:5504,messageParams:{reason:s,error:o}}))}),this._listenEvents(),this._initActiveSpeaker(),Ml(this,"trtc")}static create(e){}static _create(e,t){Il();let s=new Jr(e,t||{});return zn.add(s),s}get room(){return this._room}_listenEvents(){De(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit($.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit($.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{this._exitRoom().then(()=>{this.emit($.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().then(()=>{this.emit($.ERROR,k.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit($.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e,this.emit($.NETWORK_QUALITY,e)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{De(s,s).add("player-state-changed",o=>{let n=P(N({},o),{userId:e.userId});s.kind===h.VIDEO&&(n.streamType=Zi(s.streamType)),this.emit(s.kind===h.AUDIO?$.AUDIO_PLAY_STATE_CHANGED:$.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",o=>{o.getCode()===A.PLAY_NOT_ALLOWED&&this.emit($.AUTOPLAY_FAILED,{userId:s.userId})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{me(s)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:s}=t,o=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:c}=t;a||this._remoteAudioConfigMap.delete(s),c||this._remoteVideoConfigMap.delete(`${s}_${"main"}`),t.hasAuxiliary||this._remoteVideoConfigMap.delete(`${s}_${"sub"}`),o!==a&&(this.emit(a?$.REMOTE_AUDIO_AVAILABLE:$.REMOTE_AUDIO_UNAVAILABLE,{userId:s}),a?this._onAudioAvailable({userId:s}):this._onAudioUnavailable({userId:s,muteState:t})),n!==c&&(this.emit(c?$.REMOTE_VIDEO_AVAILABLE:$.REMOTE_VIDEO_UNAVAILABLE,{userId:s,streamType:"main"}),c?this._onVideoAvailable({userId:s,streamType:"main"}):this._onVideoUnavailable({userId:s,streamType:"main"})),e.hasAuxiliary!==t.hasAuxiliary&&(this.emit(t.hasAuxiliary?$.REMOTE_VIDEO_AVAILABLE:$.REMOTE_VIDEO_UNAVAILABLE,{userId:s,streamType:"sub"}),t.hasAuxiliary?this._onVideoAvailable({userId:s,streamType:"sub"}):this._onVideoUnavailable({userId:s,streamType:"sub"}))}).add("sei-message",e=>{this.emit($.SEI_MESSAGE,P(N({},e),{streamType:Zi(e.streamType)}))}).add("firewall-restriction",()=>{this.emit($.ERROR,new k({code:w.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var o,n,a,c,d,l,p;let t={2:"big",3:"small",7:"sub"},s={rtt:e.msg_up_stream_info.msg_network_status.uint32_rtt||((o=e.msg_down_stream_info[0])==null?void 0:o.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,upLoss:((c=this._networkQuality)==null?void 0:c.uplinkLoss)||0,downLoss:((d=this._networkQuality)==null?void 0:d.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((l=e.msg_up_stream_info.msg_audio_status)==null?void 0:l.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((p=e.msg_up_stream_info.msg_audio_status)==null?void 0:p.uint32_audio_level)||0)/ct},video:e.msg_up_stream_info.msg_video_status.filter(m=>t[m.uint32_video_stream_type]).map(m=>({bitrate:(m.uint32_video_codec_bitrate||0)/1e3,width:m.uint32_video_width,height:m.uint32_video_height,frameRate:m.uint32_video_enc_fps,videoType:t[m.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(m=>({userId:m.msg_user_info.str_identifier,audio:{bitrate:(m.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(m.msg_audio_status.uint32_audio_level||0)/ct},video:m.msg_video_status.map(f=>({bitrate:(f.uint32_video_codec_bitrate||0)/1e3,width:f.uint32_video_width,height:f.uint32_video_height,frameRate:f.uint32_video_dec_fps,videoType:t[f.uint32_video_stream_type]}))}))};this.emit($.STATISTICS,s)}).add("custom-message",e=>{this.emit($.CUSTOM_MESSAGE,e)}),De(this,ge).add("audioInputAdded",e=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>_(this,null,function*(){if(this.emit($.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Le&&Le.deviceId===cs){let t=(yield ji()).find(s=>s.deviceId===cs);t&&Le.groupId!==t.groupId&&(Le=t,this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>_(this,null,function*(){this.emit($.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield ji())[0];t&&Le&&(Le.deviceId===e.deviceId||Le.deviceId===cs&&Le.groupId!==t.groupId)&&(Le=t,this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))}use(e){let t,s;"plugin"in e?(t=e.plugin,s=e.assetsPath):t=e,this._use(t,s||"https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/")}_use(e,t){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let o=new e(Ol.call(this,{TRTC:Jr,room:this._room,errorModule:N_,assetsPath:t}));this._plugins.set(e.Name,o),e.autoStart&&(this.startPlugin(e.Name),this._log.info("auto start plugin",e.Name))}enterRoom(e){return _(this,null,function*(){var c,d;let{scene:t="rtc",enableAutoPlayDialog:s=!0,autoReceiveAudio:o=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!Y(e.proxy)&&e.proxy.turnServer&&((d=(c=this._room).setTurnServer)==null||d.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=s,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=n,de(e.preferHW)&&(this._room.preferHW=e.preferHW);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,Jr.frameWorkType),this._checkTrackToPublish(),md.start()})}exitRoom(){return _(this,null,function*(){return yield this._exitRoom()})}switchRole(e,t){return _(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(){me(this),this.removeAllListeners(),this._room.destroy(),zn.delete(this),zn.size===0&&md.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)})}startLocalAudio(){return _(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,mute:s,option:o}=e,n=new Oe(this._room.audioManager),a={},c={muted:!0};o&&(T(o.microphoneId)?T(o.audioTrack)||(a.customSource=o.audioTrack):a.deviceId=o.microphoneId,o&&ee(o.captureVolume)&&n.setCaptureVolume(o.captureVolume),T(o.profile)||(Y(o.profile)?Ro[o.profile]&&n.setProfile(Ro[o.profile]):n.setProfile(o.profile)),ee(o.earMonitorVolume)&&(c.muted=!(o.earMonitorVolume>0),c.volume=o.earMonitorVolume),T(o.echoCancellation)||(n.profile.echoCancellation=o.echoCancellation),T(o.noiseSuppression)||(n.profile.noiseSuppression=o.noiseSuppression),T(o.autoGainControl)||(n.profile.autoGainControl=o.autoGainControl)),n.on("5",d=>{this.emit($.ERROR,new k({code:w.DEVICE_ERROR,extraCode:5309,messageParams:{error:d}}))}),n.on("2",d=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"active",device:d})}),n.on("4",d=>{let l;d.error&&(l=k.convertFrom(d.error)),this.emit($.PUBLISH_STATE_CHANGED,P(N({},d),{error:l}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),T(s)||n.setMute(s),De(n,n).add("player-state-changed",d=>{this.emit($.AUDIO_PLAY_STATE_CHANGED,P(N({},d),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=P(N({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:n})})}updateLocalAudio(e){return _(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:s,option:o}=e,n={};o&&(o.microphoneId?yield this._localAudioTrack.switchDevice(o.microphoneId):T(o.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(o.audioTrack)),T(o.captureVolume)||this._localAudioTrack.setCaptureVolume(o.captureVolume),T(o.earMonitorVolume)||(n.muted=!(o.earMonitorVolume>0),n.volume=o.earMonitorVolume),yield this._localAudioTrack.update3A(o)),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(s)||this._localAudioTrack.setMute(s),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Kt(this._localAudioConfig,e)})}stopLocalAudio(){return _(this,null,function*(){!this._localAudioTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),me(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return _(this,arguments,function*(e={publish:!0,view:null}){if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:t,publish:s=!0,mute:o,option:n}=e,a=new le(this._room.videoManager),c={},d={};if(n&&(n.cameraId?c.deviceId=n.cameraId:T(n.useFrontCamera)?T(n.videoTrack)||(c.customSource=n.videoTrack):c.facingMode=n.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT,T(n.profile)||(Y(n.profile)?Ze[n.profile]&&a.setProfile(Ze[n.profile]):a.setProfile(n.profile)),T(n.fillMode)||(d.objectFit=n.fillMode),T(n.mirror)||(d.mirror=n.mirror),T(n.small)||(xs()?Y(n.small)?a.small=Ze[n.small]:n.small===!0?a.small=Ze["120p"]:a.small=n.small:this._log.warn("small stream is not supported"))),a.on("5",l=>{this.emit($.ERROR,new k({code:w.DEVICE_ERROR,extraCode:5308,messageParams:{error:l}}))}),a.on("2",l=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"active",device:l})}),a.on("4",l=>{let p;l.error&&(p=k.convertFrom(l.error)),this.emit($.PUBLISH_STATE_CHANGED,P(N({},l),{error:p}))}),this._listenOutputTrackChanged(a),yield a.capture(c),T(o)||(yield a.setMute(o)),a.mediaTrack)if(n!=null&&n.qosPreference){let l=er(n.qosPreference);a.mediaTrack.contentHint=l}else n!=null&&n.videoTrack||(a.mediaTrack.contentHint=er(st.QOS_PREFERENCE_SMOOTH));De(a,a).add("player-state-changed",l=>{this.emit($.VIDEO_PLAY_STATE_CHANGED,P(N({},l),{userId:"",streamType:"main"}))}),s&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localVideoTrack=a,this._localVideoConfig=P(N({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:a})})}updateLocalVideo(e){return _(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:s,mute:o,option:n}=e,a={};if(n){if(T(n.profile)||(Y(n.profile)?Ze[n.profile]&&this._localVideoTrack.setProfile(Ze[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&T(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):T(n.useFrontCamera)?T(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT),T(n.fillMode)||(a.objectFit=n.fillMode),T(n.mirror)||(a.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack){let c=er(n.qosPreference);this._localVideoTrack.mediaTrack.contentHint=c}if(n.small){let c=!this._localVideoTrack.small;xs()?(n.small===!0?this._localVideoTrack.small=Ze["120p"]:Y(n.small)?this._localVideoTrack.small=Ze[n.small]:this._localVideoTrack.small=n.small,this._room.videoManager.update(),c&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else n.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1))}this._room.isJoined&&!T(s)&&(s&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!s&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),T(o)||(yield this._localVideoTrack.setMute(o)),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Kt(this._localVideoConfig,e)})}stopLocalVideo(){return _(this,null,function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),me(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return _(this,arguments,function*(e={publish:!0,view:null}){if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:t=null,publish:s=!0,option:o}=e,n=new ze(this._room.videoManager);n.on("4",p=>{let m;p.error&&(m=k.convertFrom(p.error)),this.emit($.PUBLISH_STATE_CHANGED,P(N({},p),{error:m}))}),this._listenOutputTrackChanged(n);let a=null,c={},d={};o&&(T(o.profile)||(Y(o.profile)?yo[o.profile]&&n.setProfile(yo[o.profile]):n.setProfile(o.profile)),o.systemAudio&&(c.systemAudio=!0,c.echoCancellation=o.echoCancellation,c.noiseSuppression=o.noiseSuppression,c.autoGainControl=o.autoGainControl),T(o.fillMode)||(d.objectFit=o.fillMode),o.videoTrack&&(c.videoTrack=o.videoTrack),o.audioTrack&&(c.audioTrack=o.audioTrack),o.captureElement&&(c.captureElement=o.captureElement),o.preferDisplaySurface&&(c.preferDisplaySurface=o.preferDisplaySurface));let l=yield n.capture(c);if(o!=null&&o.qosPreference){let p=er(o.qosPreference);n.mediaTrack.contentHint=p}else o!=null&&o.videoTrack||(n.mediaTrack.contentHint=er(st.QOS_PREFERENCE_CLEAR));if(n.mediaTrack.addEventListener(h.ENDED,()=>{this._stopScreenShare(),this.emit($.SCREEN_SHARE_STOPPED)}),l.getAudioTracks()[0]&&(a=new Ft(this._room.audioManager),a.setInputMediaStreamTrack(l.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),De(n,n).add("player-state-changed",p=>{this.emit($.VIDEO_PLAY_STATE_CHANGED,P(N({},p),{userId:"",streamType:"sub"}))}),s&&this._room.isJoined){let p=[n];a&&p.push(a),this._room.publish(...p).catch(()=>{})}this._localScreenTrack=n,this._localScreenAudioTrack=a,this._localScreenConfig=P(N({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:n})})}updateScreenShare(e){return _(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:s,option:o}=e,n={};if(o&&(T(o.fillMode)||(n.objectFit=o.fillMode),o.qosPreference)){let a=er(o.qosPreference);this._localScreenTrack.mediaTrack.contentHint=a}this._room.isJoined&&!T(s)&&(s&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!s&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:t,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),Kt(this._localScreenConfig,e)})}stopScreenShare(){return _(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return _(this,null,function*(){let{view:t,userId:s,streamType:o,option:n}=e,a=`${s}_${o}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${s}, streamType:${o}`);return}let c=this._room.remotePublishedUserMap.get(s);if(!c)return;let d={},l=o==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;this._listenOutputTrackChanged(l),n&&(T(n.fillMode)||(d.objectFit=n.fillMode),T(n.mirror)||(d.mirror=n.mirror),d.canvasRender=n.canvasRender,o==="main"&&!T(n.small)&&(c.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,l.user))),yield this._room.subscribe(l),yield this._updateVideoPlayOption({view:t,playOption:d,track:l}),this._emitTrackEvent(l),this._remoteVideoConfigMap.set(a,{config:e}),n&&!T(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:l,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return _(this,null,function*(){var v,U;let{view:t,userId:s,streamType:o,option:n}=e,a=`${s}_${o}`,c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(s))return;let d={};n&&(T(n.fillMode)||(d.objectFit=n.fillMode),T(n.mirror)||(d.mirror=n.mirror));let l=null,p=this._room.remotePublishedUserMap.get(s);if(o==="main"&&(p==null?void 0:p.muteState.hasVideo)&&(l=p.remoteVideoTrack),o==="sub"&&(p==null?void 0:p.muteState.hasAuxiliary)&&(l=p.remoteAuxiliaryTrack),!l)return;let{config:m}=c;o==="main"&&n&&!T(n.small)&&this._room.changeType(n.small,l.user),yield this._updateVideoPlayOption({view:t,playOption:d,track:l,prevConfig:m}),Kt(m,e);let f=T(n==null?void 0:n.receiveWhenViewVisible)?(v=m.option)==null?void 0:v.receiveWhenViewVisible:n.receiveWhenViewVisible,R=T(t)?m.view:t,C=T(n==null?void 0:n.viewRoot)?(U=m.option)==null?void 0:U.viewRoot:n.viewRoot;this._observeView({remoteTrack:l,view:R,receiveWhenViewVisible:f,viewRoot:C})})}stopRemoteVideo(e){return _(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return _(this,null,function*(){let s=[],o=this._room.remotePublishedUserMap.get(e.userId);if(o){let{muteState:a,remoteVideoTrack:c,remoteAuxiliaryTrack:d}=o;e.streamType==="main"&&(c.stop(),a.hasVideo&&s.push(c)),e.streamType==="sub"&&(d.stop(),a.hasAuxiliary&&s.push(d))}for(let a of s)t&&(yield this._room.unsubscribe(a),this._mediaTrackMap.get(a.outMediaTrack)===a.userId&&this._mediaTrackMap.delete(a.outMediaTrack));let n=this._remoteVideoConfigMap.get(`${e.userId}_${e.streamType}`);n&&n.observer&&n.observer.disconnect(),this._remoteVideoConfigMap.delete(`${e.userId}_${e.streamType}`)})}muteRemoteAudio(e,t){return _(this,null,function*(){if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let s=[...this._room.remotePublishedUserMap.values()];for(let o of s)o.muteState.hasAudio&&!this._remoteAudioConfigMap.has(o.userId)&&(yield this._startRemoteAudio({userId:o.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}));this._remoteAudioMuteMap.set(e,t)})}setRemoteAudioVolume(e,t){if(e==="*"){let s=[...this._room.remotePublishedUserMap.values()];for(let o of s)this._updateAudioPlayOption({playOption:{volume:t},track:o.remoteAudioTrack})}else if(e){let s=this._room.remotePublishedUserMap.get(e);s&&this._updateAudioPlayOption({playOption:{volume:t},track:s.remoteAudioTrack})}}startPlugin(e,t){return _(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return _(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return _(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,s){return this.listeners(e).includes(t)?this:(this._log.debug("on",e),super.on(e,t,s),this._eventListened.add(e),this)}off(e,t,s){return this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,t,s),this}getAudioTrack(e={userId:"",streamType:"main"}){var o,n;let t,s="main";if(Y(e)?t=e:(t=e.userId,e.streamType&&(s=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);if(a)return a.remoteAudioTrack.mediaTrack}else return s==="sub"?((o=this._localScreenAudioTrack)==null?void 0:o.mediaTrack)||null:((n=this._localAudioTrack)==null?void 0:n.mediaTrack)||null;return null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:s="main"}=e;if(t===""){if(s==="main"&&this._localVideoTrack)return this._localVideoTrack.mediaTrack;if(s==="sub"&&this._localScreenTrack)return this._localScreenTrack.mediaTrack}else{let o=this._room.remotePublishedUserMap.get(t);if(o)return s==="main"?o.remoteVideoTrack.mediaTrack:o.remoteAuxiliaryTrack.mediaTrack}return null}getVideoSnapshot(e={}){let{userId:t,streamType:s="main"}=e;if(t){let o=this._room.remotePublishedUserMap.get(t);if(s==="main"&&(o==null?void 0:o.muteState.hasVideo))return o.remoteVideoTrack.getVideoFrame();if(s==="sub"&&(o==null?void 0:o.muteState.hasAuxiliary))return o.remoteAuxiliaryTrack.getVideoFrame()}else{if(s==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(s==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}setCurrentSpeaker(e){var t,s;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(s=this._localScreenAudioTrack)==null||s.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(o=>o.remoteAudioTrack.setAudioOutput(e))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return _(this,null,function*(){let{userId:t,option:s}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let o=this._room.remotePublishedUserMap.get(t);if(!o)return;let n={};s&&(T(s.volume)||(n.volume=s.volume));let a=o.remoteAudioTrack;this._listenOutputTrackChanged(a),this._speakerId&&a.setAudioOutput(this._speakerId);try{this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(a),yield this._updateAudioPlayOption({playOption:n,track:a})}catch(c){throw this._remoteAudioConfigMap.delete(t),c}this._emitTrackEvent(a)})}_stopRemoteAudio(e,t=!0){return _(this,null,function*(){let s=this._room.remotePublishedUserMap.get(e.userId);s&&(s.remoteAudioTrack.stop(),s.muteState.hasAudio&&t&&(yield this._room.unsubscribe(s.remoteAudioTrack)),this._mediaTrackMap.get(s.remoteAudioTrack.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(s.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`)})}_updateVideoPlayOption(n){return _(this,arguments,function*({view:e,playOption:t,track:s,prevConfig:o}){if(s.setMirror(t.mirror),T(e)&&o&&o.view&&!Ga(t)){let a=Ds(o.view);a.length>0&&(yield s.play(a,t))}if(!T(e)){let a=Ds(e);a.length>0?yield s.play(a,t):s.stop()}})}_updateAudioPlayOption(o){return _(this,arguments,function*({playOption:e={},track:t,prevConfig:s}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}T(e.muted)||t.setPlayerMute(e.muted),T(e.volume)||t.setAudioVolume(e.volume/100)})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,t=!0){let s=e.isRemote?e.userId:"";!e.outMediaTrack||t&&this._mediaTrackMap.get(e.outMediaTrack)===s||(this._mediaTrackMap.set(e.outMediaTrack,s),this.emit($.TRACK,{userId:s,streamType:Zi(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var t,s,o;let e=[];if(((t=this._localAudioConfig)==null?void 0:t.publish)&&this._localAudioTrack&&e.push(this._localAudioTrack),((s=this._localVideoConfig)==null?void 0:s.publish)&&this._localVideoTrack&&e.push(this._localVideoTrack),(o=this._localScreenConfig)!=null&&o.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:s=!1,viewRoot:o}){if(T(t))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${Zi(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||he(t)&&t.length===0||!s){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let d=n.visibleViewMap||new Map,l=-1;(!a||a.root!==o)&&(a==null||a.disconnect(),d.clear(),a=new IntersectionObserver(m=>{m.forEach(f=>{d.set(f.target,f.isIntersecting)}),clearTimeout(l),l=window.setTimeout(()=>{[...d.values()].find(R=>R)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:o}));let p=new Set(Ds(t));d.forEach((m,f)=>{p.has(f)||(a.unobserve(f),d.delete(f))}),p.forEach(m=>{d.set(m,!0),a.observe(m)}),a.takeRecords().forEach(m=>{d.set(m.target,m.isIntersecting)}),n.visibleViewMap=d,n.observer=a}_exitRoom(){return _(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let t=e.includes("main")?"main":"sub",s=e.split(`_${t}`)[0];s&&this._stopRemoteVideo({userId:s,streamType:t}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._room.remotePublishedUserMap.forEach(e=>{me(e.remoteAudioTrack),me(e.remoteVideoTrack),me(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return _(this,null,function*(){var e;if(!!this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...t).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),me(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_initActiveSpeaker(){return _(this,null,function*(){if(Le&&!Lr(Le))this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:Le});else{let e=yield ji();if(e[0]&&!Lr(e[0]))Le=e[0],this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let t=({track:s})=>{s.kind==="audio"&&(!Le||Lr(Le))&&(this._initActiveSpeaker(),g.off("102",this._initActiveSpeaker))};g.on("102",t)}}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let s=this._room.remotePublishedUserMap.get(e);if(s){let o=t==="main"?s.remoteVideoTrack:s.remoteAuxiliaryTrack;this._room.subscribe(o).then(()=>{this._emitTrackEvent(o)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:t}){t.hasAudio&&t.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:t}){this._stopRemoteVideo({userId:e,streamType:t},!1).catch(()=>{})}sendSEIMessage(e,t){var o;let s=this._plugins.get("SEI");s&&(s.update({buffer:e,options:P(N({seiPayloadType:243},t),{small:!!((o=this._localVideoTrack)!=null&&o.small)})}),D.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,s;(s=(t=this._room).sendCustomMessage)==null||s.call(t,e),D.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){I.setLogLevel(e),T(t)||(t?I.enableUploadLog():I.disableUploadLog())}static isSupported(){return on()}static getCameraList(e=!0){return Xe(e)}static getMicrophoneList(e=!0){return Be(e)}static getSpeakerList(e=!0){return ji(e)}static setCurrentSpeaker(e){return _(this,null,function*(){(yield ji()).forEach(s=>{s.deviceId===e&&(zn.forEach(o=>{o.setCurrentSpeaker(e),o.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:s})}),Le=s)})})}static _addKVStat({type:e,key:t,value:s,base:o,useUV:n,version:a}){switch(a&&(Hi.version=a),e){case"count":Hi.addCount({key:t,useUV:n});break;case"enum":Hi.addEnum({key:t,value:s,useUV:n});break;case"number":Hi.addNumber({key:t,value:s,split:o});break}}},Q=Jr;u(Q,"_loggerManager",I),u(Q,"EVENT",$),u(Q,"ERROR_CODE",w),u(Q,"TYPE",st),u(Q,"frameWorkType",30),y([oe({replaceArg:r=>({argIndex:0,value:{name:"plugin"in r?r.plugin.Name:r.Name,assetsPath:"assetsPath"in r?r==null?void 0:r.assetsPath:"default"}})})],Q.prototype,"use",1),y([ke(Ce.TRTC.enterRoom),Di("room",([r],[i])=>(r.roomId||r.strRoomId)===(i.roomId||i.strRoomId)&&r.userId===i.userId&&r.sdkAppId===i.sdkAppId),J(r=>function(i){return this._log.setUserId(i.userId),this._log.setSdkAppId(i.sdkAppId),r.call(this,i)}),oe()],Q.prototype,"enterRoom",1),y([oe()],Q.prototype,"exitRoom",1),y([ke(Ce.TRTC.switchRole),Ki("room",{merge:(r,i)=>i}),oe()],Q.prototype,"switchRole",1),y([oe()],Q.prototype,"destroy",1),y([ke(Ce.TRTC.startLocalAudio),Di("audio",([r],[i])=>{var e,t;return((e=r==null?void 0:r.option)==null?void 0:e.microphoneId)===((t=i==null?void 0:i.option)==null?void 0:t.microphoneId)}),oe()],Q.prototype,"startLocalAudio",1),y([ke(Ce.TRTC.updateLocalAudio),Ki("audio",{debounce:{delay:200,getKey:()=>`${Hl}-localAudio`,isNeedToDebounce:r=>{var i;return!T((i=r.option)==null?void 0:i.captureVolume)}}}),oe()],Q.prototype,"updateLocalAudio",1),y([Oi("audio"),oe()],Q.prototype,"stopLocalAudio",1),y([ke(Ce.TRTC.startLocalVideo),Di("video",([r],[i])=>{var e,t;return((e=r==null?void 0:r.option)==null?void 0:e.cameraId)===((t=i==null?void 0:i.option)==null?void 0:t.cameraId)}),oe()],Q.prototype,"startLocalVideo",1),y([ke(Ce.TRTC.updateLocalVideo),Ki("video"),oe()],Q.prototype,"updateLocalVideo",1),y([Oi("video"),oe()],Q.prototype,"stopLocalVideo",1),y([ke(Ce.TRTC.startScreenShare),Di("screen",()=>!0),oe()],Q.prototype,"startScreenShare",1),y([ke(Ce.TRTC.updateScreenShare),Ki("screen"),oe()],Q.prototype,"updateScreenShare",1),y([oe()],Q.prototype,"stopScreenShare",1),y([ke(Ce.TRTC.startRemoteVideo),Di(r=>`v${r.userId}${r.streamType}`,()=>!0),oe({getRemoteId:r=>`${r.userId}_${r.streamType}`})],Q.prototype,"startRemoteVideo",1),y([ke(Ce.TRTC.updateRemoteVideo),Ki(r=>`v${r.userId}${r.streamType}`),oe({getRemoteId:r=>`${r.userId}_${r.streamType}`})],Q.prototype,"updateRemoteVideo",1),y([ke(Ce.TRTC.stopRemoteVideo),J(r=>function(i){return _(this,null,function*(){if(i.userId==="*"){let e=[];return this._room.remotePublishedUserMap.forEach(t=>{this._remoteVideoConfigMap.has(`${t.userId}_${"main"}`)&&e.push(this.stopRemoteVideo({streamType:"main",userId:t.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${t.userId}_${"sub"}`)&&e.push(this.stopRemoteVideo({streamType:"sub",userId:t.userId}).catch(()=>{}))}),Promise.all(e)}return r.call(this,i)})}),oe({getRemoteId:r=>`${r.userId}_${r.streamType}`})],Q.prototype,"stopRemoteVideo",1),y([Oi(r=>`v${r.userId}${r.streamType}`)],Q.prototype,"_stopRemoteVideo",1),y([ke(...Ce.TRTC.muteRemoteAudio),oe({getRemoteId:r=>r})],Q.prototype,"muteRemoteAudio",1),y([dd(...Ce.TRTC.setRemoteAudioVolume),kl(200,r=>r),oe({getRemoteId:r=>r})],Q.prototype,"setRemoteAudioVolume",1),y([qn("start"),gt(r=>{var i;return(i=r.afterStart)==null?void 0:i.call(r)}),Di((r,i)=>r.getAlias()+r.getGroup(i)),oe({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>oc[r.getName()]})],Q.prototype,"startPlugin",1),y([qn("update"),Ki((r,i)=>r.getAlias()+r.getGroup(i)),oe({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>nc[r.getName()]})],Q.prototype,"updatePlugin",1),y([qn("stop"),Oi((r,i)=>{let e=r.getGroup(i),t=r.getAlias();return e==="*"?new RegExp(`${t}.*`):t+e}),oe({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>ac[r.getName()]})],Q.prototype,"stopPlugin",1),y([dd(...Ce.TRTC.enableAudioVolumeEvaluation)],Q.prototype,"enableAudioVolumeEvaluation",1),y([oe()],Q.prototype,"getVideoSnapshot",1),y([oe()],Q.prototype,"setCurrentSpeaker",1),y([Di(r=>`a${r.userId}`,()=>!0)],Q.prototype,"_startRemoteAudio",1),y([J(r=>function(i){return _(this,null,function*(){return i.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(e=>this._stopRemoteAudio(P(N({},i),{userId:e.userId})).catch(()=>{}))):r.call(this,i)})}),Oi(r=>`a${r.userId}`)],Q.prototype,"_stopRemoteAudio",1),y([Oi("room")],Q.prototype,"_exitRoom",1),y([Oi("screen")],Q.prototype,"_stopScreenShare",1),y([ke(...Ce.TRTC.sendSEIMessage),nd({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...r)=>r[0].byteLength})],Q.prototype,"sendSEIMessage",1),y([ke(Ce.TRTC.sendCustomMessage),nd({timesInSecond:30,maxSizeInSecond:8e3,getSize:r=>r.data.byteLength})],Q.prototype,"sendCustomMessage",1),y([ke(Ce.TRTC.create)],Q,"_create",1);var io=Q;var gd=class{constructor(){this._set=new Set;g.on(E.LEAVE_SUCCESS,this.delete,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,s){return`${t}_${e}_${i}_${s}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:s}){return s.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,s.useStringRoomId))}};function v_(){return _(this,null,function*(){let r,i;try{let p=yield Be();r=p&&p.length}catch(p){}try{let p=yield Xe();i=p&&p.length}catch(p){}let e={microphone:r,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:s,isH264DecodeSupported:o,isVp8DecodeSupported:n}=this.checkSystemResult.detail,a=ft.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:t,h264Decode:o,vp8Encode:s,vp8Decode:n},d={browser:a.browser,os:a.os,trtc:c,devices:e},l={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};Z.uploadEvent({log:`trtcstats-${JSON.stringify(d)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(d)}`),Z.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(l)}`,userId:this.userId})})}function Wl(){return J(r=>{let i=new gd;return function(e,t,s){return _(this,null,function*(){let o=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=t,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new b({code:A.INVALID_OPERATION,message:L({key:M.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new b({code:A.INVALID_OPERATION,message:L({key:M.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:o}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${o} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),g.emit(E.JOIN_START,{room:this,roomId:o,params:e}),this.checkSystemResult=yield ft.checkSystemRequirementsInternal(),this.checkDestroy();let n=we.getEnv();n||(n=jt.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(bo.OLD_CLOUD_LADDER)?n=jt.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(bo.WEBRTC)&&(n=jt.WEBRTC))),Z.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),v_.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!ft.isWebRTCSupported()||!a&&!c)throw new b({code:A.NOT_SUPPORTED,message:L({key:M.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!we.getEnv()&&(yield this.schedule(e,s));let d=yield r.call(this,e,t,s);return this.roomId=o,this._joinedTimestamp=we.performanceNow(),g.emit(E.JOIN_SUCCESS,{room:this}),s===30&&!e.component&&Z.uploadEvent({log:`stat-conv-${Number(zt)}-${location.hostname}`,userId:this.userId}),d}catch(d){throw i.delete({room:this,roomId:o}),g.emit(E.JOIN_FAILED,{room:this,error:d}),d}})}})}var Jl=()=>J(r=>function(...i){return _(this,null,function*(){g.emit(E.LEAVE_START,{room:this}),yield r.call(this),g.emit(E.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function jl(){return J(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var Xl=Se(Ne());var _e={SETUP_SUCCESS:"1",SETUP_FAILED:"5",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",DISCONNECTED:"5",RECONNECT_FAILED:"4"};var Gt={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140},ql=[Gt.UPDATE_REMOTE_MUTE_STAT,Gt.UPLINK_NETWORK_STATS,Gt.USER_LIST_RES,Gt.MUTE_RESULT,Gt.SERVER_FIRST_PACKAGE_RECEIVED],V={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg"},q={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3",ABILITY_STATUS_REPORT:"ability_status_report",RECONNECT_WS:"reconnect",SEND_CUSTOM_MSG:"channel_msg"};var Yn=new Set;function Ql(r){let i=[...Yn.values()].find(e=>e.room.userId===r&&!e.room.isJoined);return i||null}var jr=class extends Xl.default{constructor(e){var s,o;super();u(this,"room");u(this,"url");u(this,"backupUrl");u(this,"race");u(this,"destroyed",!1);u(this,"_socketInUse");u(this,"_socket");u(this,"_backupSocket");u(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0});u(this,"_currentState","DISCONNECTED");u(this,"_isReconnecting",!1);u(this,"_seq",0);u(this,"_log");u(this,"_lastMessageTime",-1);u(this,"_connnectStartTime",-1);u(this,"_stopConnectRetry");u(this,"bytesSent",0);u(this,"bytesReceived",0);u(this,"keepAlive",!1);u(this,"signalDomainWhenUnifiedProxy");this.room=e.room,this.race=T(e.race)?!0:e.race,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy,(((o=(s=this.room.scheduleResult)==null?void 0:s.config)==null?void 0:o.keepAliveClient)||0)-Yn.size>0&&this.room.enableSPC&&(this.keepAlive=!0,Yn.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=I.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;return this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`),this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get sdkAppId(){return this.room.sdkAppId}get userId(){return this.room.userId}get userSig(){return this.room.userSig}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return _(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}]${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connnectStartTime=x();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 Rs(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?h.BACKUP:h.MAIN),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:s}){let o=new WebSocket(e);this.bindSocket(o),s?this._socket=o:this._backupSocket=o;let n=-1;return new Promise((a,c)=>{o.onclose=c,o.onerror=c,o.onopen=()=>a(o),t&&(n=setTimeout(()=>{this.unbindAndCloseSocket(s?h.MAIN:h.BACKUP),c(new b({code:A.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{o.onclose=null,o.onerror=null,o.onopen=null,clearTimeout(n)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===h.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}onclose(e){if(e.target===this._socketInUse&&(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),!e.wasClean||e.code!==1e3)){this._socketInUse.onclose=null,this._socketInUse.close(4011);let t=this._socketInUse===this._socket;this.unbindAndCloseSocket(t?h.MAIN:h.BACKUP),this._socketInUse=null,this.reconnect()}}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this._socketInUse=null,this.reconnect())}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=Yo(e.data);let t=JSON.parse(e.data),{cmd:s,data:o}=t,n=Object.values(Gt),c=Object.keys(Gt)[n.indexOf(s)],d=V[c]||s;switch(ql.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),d&&this._log.info(`Received event: [ ${d} ]`)),s){case Gt.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=o.clientIp,this._signalInfo.signalIp=o.signalInnerIp,o.svrTime&&Qd(o.svrTime),this._log.info("ChannelSetup Success"),D.addSuccessEvent({key:521701,cost:x()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(_e.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let l=new b({code:A.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:L({key:M.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),D.addFailedEvent({key:521701,error:l}),this.emit(_e.SETUP_FAILED,l)}break}case Gt.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=o.relayOuterIp,this._signalInfo.relayInnerIp=o.relayInnerIp,this._signalInfo.relayPort=o.relayPort,this._signalInfo.tinyId=t.tinyId,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(d,{data:t});break}default:this.emit(String(d),{data:t});break}}reGetSignalChannelUrl(){return _(this,null,function*(){try{if(!this.room.joinParams)return;Mt(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}reconnect(){return _(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive){this.close();return}this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:s,relayInnerIp:o,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:q.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:o,relayOuterIp:s,relayPort:n},responseCommand:V.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),D.addSuccessEvent({key:521702,cost:x()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(D.addFailedEvent({key:521702,error:a.code}),this._log.warn(`reconnect failed, ${a.code} ${a.message}`),this.room.reJoin())}catch(e){this._log.error(e),this.room.reJoin()}}})}send(e,t={}){if(this.isConnected&&!this.room.isLeft){let s={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},o=JSON.stringify(s);return this._socketInUse.send(o),this.bytesSent+=Yo(o),s.seq}}sendWaitForResponse({command:e,data:t,timeout:s=5e3,responseCommand:o,commandDesc:n,enableLog:a=!0}){return new Promise((c,d)=>{let l=setTimeout(()=>{this.off(o,p);let f=new b({code:A.API_CALL_TIMEOUT,message:L({key:M.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(f),d(f)},s),p=f=>{f.data.seq===m&&(clearTimeout(l),this.off(o,p),c(f))};this.on(o,p);let m=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:s,retries:o=0,retryTimeout:n=0}=e;return vt({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${s} when connected`),this.once(_e.CONNECTED,a))},onRetrying:a=>{this._log.warn(`${t||s} timeout observed, retrying [${a}/${o}]`)},settings:{retries:o,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),Yn.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`);let t=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(V.JOIN_ROOM_RESULT,s)},e*1e3),s=o=>{o.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(t),this.off(V.JOIN_ROOM_RESULT,s))};this.on(V.JOIN_ROOM_RESULT,s)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(_e.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(_e.CONNECTED):e==="DISCONNECTED"&&this.emit(_e.DISCONNECTED))}};y([it({settings:{retries:1/0,timeout:2e3},onError(r,i){!this.room.isDestroyed&&!this.destroyed&&i()},onRetrying(r,i){this._log.warn(`retrying to connect ${r}`),r>=3&&r%3===0&&this.reGetSignalChannelUrl(),i&&(this._stopConnectRetry=i,(this.room.isDestroyed||this.destroyed)&&i())}})],jr.prototype,"connect",1);var zl=Se(Ne());var Td=0,Sd=!1,Kn=new Set,O_=r=>Td>2&&!Sd&&Kn.size===0&&r,Id=!1,Ke=class{constructor(i){u(this,"userId");u(this,"tinyId");u(this,"_sdpSemantics");u(this,"_isUplink");u(this,"_room");u(this,"_log");u(this,"_signalChannel");u(this,"_isErrorObserved",!1);u(this,"_waitForPeerConnectionConnectedPromise");u(this,"_waitForPeerConnectionConnectedPromiseReject",null);u(this,"_peerConnection",null);u(this,"_emitter",new zl.default);u(this,"_currentState","DISCONNECTED");u(this,"_isReconnecting",!1);u(this,"_reconnectionCount",0);u(this,"_reconnectionTimer",-1);u(this,"_isFirstConnection",!0);u(this,"_prevTime",-1);u(this,"_localAddress");u(this,"_remoteAddress");this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=I.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=x())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,D.addSuccessEvent({key:521705,cost:Math.min(x()-this._prevTime,30*1e3)})):this._isReconnecting&&D.addSuccessEvent({key:521706,cost:x()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,D.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&D.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(),Kn.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 b({code:A.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return nt;let i=null;if(this._isUplink){if(!Ri()||this._peerConnection.getSenders().length===0)return nt;i=this._peerConnection.getSenders()[0].transport}else{if(!$i()||this._peerConnection.getReceivers().length===0)return nt;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:nt}onConnectionStateChange(i){let e=this._peerConnection.iceConnectionState,t=this.getDTLSTransportState();if(this._log.info(`connectionState: ${i.target.connectionState}, ICE: ${e}, DTLS: ${t}`),i.target.connectionState===se.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===se.FAILED||i.target.connectionState===se.CLOSED){let s=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,o=new b({message:s,code:A.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",o)}(i.target.connectionState===se.CONNECTED||i.target.connectionState===se.COMPLETED)&&(this.logSelectedCandidate(),Z.logSuccessEvent({userId:this._room.userId,eventType:Ve.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(Td=0,Sd=!1,Id=!0,Kn.add(this)):Kn.delete(this),g.emit(E.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:i,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:i}),this._currentState=i,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return _(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(Ci(e)){let t=i.get(e.localCandidateId),s=i.get(e.remoteCandidateId);t&&(this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.candidateType==="relay"?`relayProtocol:${t.relayProtocol}`:""}`),this._localAddress=`${t.ip||t.address}:${t.port}`),s&&(this._log.info(`remote candidate: ${s.candidateType} ${s.protocol}:${s.ip||s.address}:${s.port}`),this._remoteAddress=`${s.protocol}:${s.ip||s.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(n),o(),i())},s=({room:a})=>{a===this._room&&(clearTimeout(n),o(),e(new b({code:A.API_CALL_ABORTED,message:L({key:M.CONNECTION_ABORTED,data:"leave room"})})))},o=()=>{g.off(E.LEAVE_SUCCESS,s,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{o();let a=new b({code:A.API_CALL_TIMEOUT,message:"connection timeout"});Td+=1,O_(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Sd=!0,this._emitter.emit("firewall-restriction")),e(a)},as);g.on(E.LEAVE_SUCCESS,s,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(_e.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=qt()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new b({code:this._isUplink?A.UPLINK_RECONNECTION_FAILED:A.DOWNLINK_RECONNECTION_FAILED,message:L({key:this._isUplink?M.UPLINK_RECONNECTION_FAILED:M.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(_e.CONNECTED,this.reconnect,this),-1)}on(i,e,t){this._emitter.on(i,e,t)}off(i,e,t){this._emitter.off(i,e,t)}getIsReconnecting(){return this._isReconnecting}get isH264(){var i,e;return!!((e=(i=this._peerConnection)==null?void 0:i.remoteDescription)!=null&&e.sdp.includes("H264"))}};var yd=Se(Rd());var ce=function(r){return yd.default.parse(r)},He=function(r){return yd.default.write(r)},sh=function(r){let i=ce(r);return i.media.forEach(e=>{e.type===h.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),He(i)};function oh(r){let i=ce(r);return i.media.forEach(e=>{var t,s;if(e.type===h.VIDEO){let o=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&o.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let d=c.match(/apt=(\d+)/);d&&d[1]&&o.has(Number(d[1]))&&o.add(a)});let n=({payload:a})=>!o.has(a);e.rtp=e.rtp.filter(n),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=(s=e.payloads)==null?void 0:s.split(" ").filter(a=>!o.has(Number(a))).join(" ")}}),He(i)}function Zn(r){return Object.keys(r).filter(i=>r[i])}var Nd=class extends Ke{constructor(e){super(P(N({},e),{isUplink:!1}));u(this,"_flag",0);u(this,"role","anchor");u(this,"remoteAudioTrack");u(this,"remoteVideoTrack");u(this,"remoteAuxiliaryTrack");u(this,"ssrc",{audio:0,video:0,auxiliary:0});u(this,"_isSDPExchanging",!1);this.flag=e.flag,this.remoteAudioTrack=e.remoteAudioTrack||new oi(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new Tt(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Vr(this._room,this)}get videoCodec(){var t,s;let e=(s=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:s.sdp;return e?e.includes("H264")?"h264":"vp8":"h264"}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return Ai(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,s,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===h.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),s}onTrack(e){let t=e.streams[0],{track:s}=e,o=t.id===ns?h.MAIN:h.AUXILIARY;this._log.debug(`ontrack ${o} ${s.kind}`);let n=h.AUDIO;s.kind===h.VIDEO&&(n=o===h.MAIN?h.VIDEO:h.AUXILIARY);let a=this.remoteAudioTrack;n===h.VIDEO?a=this.remoteVideoTrack:n===h.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(s)}addRRTRLine(e){let t=e.split(`\r
|
|
68
|
+
`)};(${e})()})()`,s=new Blob([t],{type:"text/javascript"}),o=URL.createObjectURL(s),n=new Worker(o);return URL.revokeObjectURL(o),n}var Hu=0,Yn=new Set,Le=null;ma(Lu);var N_={RtcError:k,ErrorCode:w,ErrorCodeDictionary:rt},di=class extends Gu.EventEmitter{constructor(e,t){super();l(this,"_room");l(this,"_eventListened",new Set);l(this,"_localVideoTrack",null);l(this,"_localAudioTrack",null);l(this,"_localScreenTrack",null);l(this,"_localScreenAudioTrack",null);l(this,"_localVideoConfig",null);l(this,"_localScreenConfig",null);l(this,"_localAudioConfig",null);l(this,"_remoteVideoConfigMap",new Map);l(this,"_remoteAudioConfigMap",new Map);l(this,"_remoteAudioMuteMap",new Map);l(this,"_mediaTrackMap",new WeakMap);l(this,"_log",I.createLogger({id:`t${++Hu}`}));l(this,"_plugins",new Map);l(this,"_networkQuality",null);l(this,"_speakerId");l(this,"_getPCMAbortCtrl");this._room=new e(N({logger:this._log,frameWorkType:di.frameWorkType},t)),this._log.debug(`TRTC.create() ${JSON.stringify(t,(s,o)=>s==="plugins"?o.map(n=>n.Name):o)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(s){return this._room.audioManager.dump(s)}}}),t.plugins&&t.plugins.forEach(s=>{this._use(s,t.assetsPath)}),this._use(Li,t.assetsPath),this._use(rr,t.assetsPath),t.enableSEI&&Gi&&(this._use(io),this.startPlugin("SEI")),this._room.on("audio-volume",s=>{!s.find(o=>o.userId==="")&&this._localAudioTrack&&s.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),this.emit($.AUDIO_VOLUME,{result:s.sort((o,n)=>n.volume-o.volume)})}),this._room.videoManager.on("error",({reason:s,error:o})=>{this._log.error(new k({code:w.OPERATION_FAILED,extraCode:5504,messageParams:{reason:s,error:o}}))}),this._listenEvents(),this._initActiveSpeaker(),Mu(this,"trtc")}static create(e){}static _create(e,t){Iu();let s=new di(e,t||{});return Yn.add(s),s}get room(){return this._room}_listenEvents(){De(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit($.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit($.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{this._exitRoom().then(()=>{this.emit($.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().then(()=>{this.emit($.ERROR,k.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit($.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e,this.emit($.NETWORK_QUALITY,e)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{De(s,s).add("player-state-changed",o=>{let n=P(N({},o),{userId:e.userId});s.kind===h.VIDEO&&(n.streamType=tr(s.streamType)),this.emit(s.kind===h.AUDIO?$.AUDIO_PLAY_STATE_CHANGED:$.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",o=>{o.getCode()===A.PLAY_NOT_ALLOWED&&this.emit($.AUTOPLAY_FAILED,{userId:s.userId})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{me(s)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:s}=t,o=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:c}=t;a||this._remoteAudioConfigMap.delete(s),c||this._remoteVideoConfigMap.delete(`${s}_${"main"}`),t.hasAuxiliary||this._remoteVideoConfigMap.delete(`${s}_${"sub"}`),o!==a&&(this.emit(a?$.REMOTE_AUDIO_AVAILABLE:$.REMOTE_AUDIO_UNAVAILABLE,{userId:s}),a?this._onAudioAvailable({userId:s}):this._onAudioUnavailable({userId:s,muteState:t})),n!==c&&(this.emit(c?$.REMOTE_VIDEO_AVAILABLE:$.REMOTE_VIDEO_UNAVAILABLE,{userId:s,streamType:"main"}),c?this._onVideoAvailable({userId:s,streamType:"main"}):this._onVideoUnavailable({userId:s,streamType:"main"})),e.hasAuxiliary!==t.hasAuxiliary&&(this.emit(t.hasAuxiliary?$.REMOTE_VIDEO_AVAILABLE:$.REMOTE_VIDEO_UNAVAILABLE,{userId:s,streamType:"sub"}),t.hasAuxiliary?this._onVideoAvailable({userId:s,streamType:"sub"}):this._onVideoUnavailable({userId:s,streamType:"sub"}))}).add("sei-message",e=>{this.emit($.SEI_MESSAGE,P(N({},e),{streamType:tr(e.streamType)}))}).add("firewall-restriction",()=>{this.emit($.ERROR,new k({code:w.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var o,n,a,c,d,u,p;let t={2:"big",3:"small",7:"sub"},s={rtt:e.msg_up_stream_info.msg_network_status.uint32_rtt||((o=e.msg_down_stream_info[0])==null?void 0:o.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,upLoss:((c=this._networkQuality)==null?void 0:c.uplinkLoss)||0,downLoss:((d=this._networkQuality)==null?void 0:d.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((u=e.msg_up_stream_info.msg_audio_status)==null?void 0:u.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((p=e.msg_up_stream_info.msg_audio_status)==null?void 0:p.uint32_audio_level)||0)/dt},video:e.msg_up_stream_info.msg_video_status.filter(m=>t[m.uint32_video_stream_type]).map(m=>({bitrate:(m.uint32_video_codec_bitrate||0)/1e3,width:m.uint32_video_width,height:m.uint32_video_height,frameRate:m.uint32_video_enc_fps,videoType:t[m.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(m=>({userId:m.msg_user_info.str_identifier,audio:{bitrate:(m.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(m.msg_audio_status.uint32_audio_level||0)/dt},video:m.msg_video_status.map(f=>({bitrate:(f.uint32_video_codec_bitrate||0)/1e3,width:f.uint32_video_width,height:f.uint32_video_height,frameRate:f.uint32_video_dec_fps,videoType:t[f.uint32_video_stream_type]}))}))};this.emit($.STATISTICS,s)}).add("custom-message",e=>{this.emit($.CUSTOM_MESSAGE,e)}),De(this,ge).add("audioInputAdded",e=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>_(this,null,function*(){if(this.emit($.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Le&&Le.deviceId===ds){let t=(yield Xi()).find(s=>s.deviceId===ds);t&&Le.groupId!==t.groupId&&(Le=t,this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>_(this,null,function*(){this.emit($.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield Xi())[0];t&&Le&&(Le.deviceId===e.deviceId||Le.deviceId===ds&&Le.groupId!==t.groupId)&&(Le=t,this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))}use(e){let t,s;"plugin"in e?(t=e.plugin,s=e.assetsPath):t=e,this._use(t,s||"https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/")}_use(e,t){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let o=new e(Ou.call(this,{TRTC:di,room:this._room,errorModule:N_,assetsPath:t}));this._plugins.set(e.Name,o),e.autoStart&&(this.startPlugin(e.Name),this._log.info("auto start plugin",e.Name))}enterRoom(e){return _(this,null,function*(){var c,d;let{scene:t="rtc",enableAutoPlayDialog:s=!0,autoReceiveAudio:o=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!z(e.proxy)&&e.proxy.turnServer&&((d=(c=this._room).setTurnServer)==null||d.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=s,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=n,de(e.preferHW)&&(this._room.preferHW=e.preferHW);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,di.frameWorkType),this._checkTrackToPublish(),_d.start()})}exitRoom(){return _(this,null,function*(){return yield this._exitRoom()})}switchRole(e,t){return _(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(){me(this),this.removeAllListeners(),this._room.destroy(),Yn.delete(this),Yn.size===0&&_d.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)})}startLocalAudio(){return _(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,mute:s,option:o}=e,n=new Oe(this._room.audioManager),a={},c={muted:!0};o&&(T(o.microphoneId)?T(o.audioTrack)||(a.customSource=o.audioTrack):a.deviceId=o.microphoneId,o&&ee(o.captureVolume)&&n.setCaptureVolume(o.captureVolume),T(o.profile)||(z(o.profile)?yo[o.profile]&&n.setProfile(yo[o.profile]):n.setProfile(o.profile)),ee(o.earMonitorVolume)&&(c.muted=!(o.earMonitorVolume>0),c.volume=o.earMonitorVolume),T(o.echoCancellation)||(n.profile.echoCancellation=o.echoCancellation),T(o.noiseSuppression)||(n.profile.noiseSuppression=o.noiseSuppression),T(o.autoGainControl)||(n.profile.autoGainControl=o.autoGainControl)),n.on("5",d=>{this.emit($.ERROR,new k({code:w.DEVICE_ERROR,extraCode:5309,messageParams:{error:d}}))}),n.on("2",d=>{this.emit($.DEVICE_CHANGED,{type:"microphone",action:"active",device:d})}),n.on("4",d=>{let u;d.error&&(u=k.convertFrom(d.error)),this.emit($.PUBLISH_STATE_CHANGED,P(N({},d),{error:u}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),T(s)||n.setMute(s),De(n,n).add("player-state-changed",d=>{this.emit($.AUDIO_PLAY_STATE_CHANGED,P(N({},d),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=P(N({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:n})})}updateLocalAudio(e){return _(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:s,option:o}=e,n={};o&&(o.microphoneId?yield this._localAudioTrack.switchDevice(o.microphoneId):T(o.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(o.audioTrack)),T(o.captureVolume)||this._localAudioTrack.setCaptureVolume(o.captureVolume),T(o.earMonitorVolume)||(n.muted=!(o.earMonitorVolume>0),n.volume=o.earMonitorVolume),yield this._localAudioTrack.update3A(o)),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(s)||this._localAudioTrack.setMute(s),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),ei(this._localAudioConfig,e)})}stopLocalAudio(){return _(this,null,function*(){!this._localAudioTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),me(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return _(this,arguments,function*(e={publish:!0,view:null}){if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:t,publish:s=!0,mute:o,option:n}=e,a=new ue(this._room.videoManager),c={},d={};if(n&&(n.cameraId?c.deviceId=n.cameraId:T(n.useFrontCamera)?T(n.videoTrack)||(c.customSource=n.videoTrack):c.facingMode=n.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT,T(n.profile)||(z(n.profile)?Ze[n.profile]&&a.setProfile(Ze[n.profile]):a.setProfile(n.profile)),T(n.fillMode)||(d.objectFit=n.fillMode),T(n.mirror)||(d.mirror=n.mirror),T(n.small)||(Ps()?z(n.small)?a.small=Ze[n.small]:n.small===!0?a.small=Ze["120p"]:a.small=n.small:this._log.warn("small stream is not supported"))),a.on("5",u=>{this.emit($.ERROR,new k({code:w.DEVICE_ERROR,extraCode:5308,messageParams:{error:u}}))}),a.on("2",u=>{this.emit($.DEVICE_CHANGED,{type:"camera",action:"active",device:u})}),a.on("4",u=>{let p;u.error&&(p=k.convertFrom(u.error)),this.emit($.PUBLISH_STATE_CHANGED,P(N({},u),{error:p}))}),this._listenOutputTrackChanged(a),yield a.capture(c),T(o)||(yield a.setMute(o)),a.mediaTrack)if(n!=null&&n.qosPreference){let u=ir(n.qosPreference);a.mediaTrack.contentHint=u}else n!=null&&n.videoTrack||(a.mediaTrack.contentHint=ir(ot.QOS_PREFERENCE_SMOOTH));De(a,a).add("player-state-changed",u=>{this.emit($.VIDEO_PLAY_STATE_CHANGED,P(N({},u),{userId:"",streamType:"main"}))}),s&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localVideoTrack=a,this._localVideoConfig=P(N({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:a})})}updateLocalVideo(e){return _(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:s,mute:o,option:n}=e,a={};if(n){if(T(n.profile)||(z(n.profile)?Ze[n.profile]&&this._localVideoTrack.setProfile(Ze[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&T(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):T(n.useFrontCamera)?T(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT),T(n.fillMode)||(a.objectFit=n.fillMode),T(n.mirror)||(a.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack){let c=ir(n.qosPreference);this._localVideoTrack.mediaTrack.contentHint=c}if(n.small){let c=!this._localVideoTrack.small;Ps()?(n.small===!0?this._localVideoTrack.small=Ze["120p"]:z(n.small)?this._localVideoTrack.small=Ze[n.small]:this._localVideoTrack.small=n.small,this._room.videoManager.update(),c&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else n.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1))}this._room.isJoined&&!T(s)&&(s&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!s&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),T(o)||(yield this._localVideoTrack.setMute(o)),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),ei(this._localVideoConfig,e)})}stopLocalVideo(){return _(this,null,function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),me(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return _(this,arguments,function*(e={publish:!0,view:null}){if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:t=null,publish:s=!0,option:o}=e,n=new ze(this._room.videoManager);n.on("4",p=>{let m;p.error&&(m=k.convertFrom(p.error)),this.emit($.PUBLISH_STATE_CHANGED,P(N({},p),{error:m}))}),this._listenOutputTrackChanged(n);let a=null,c={},d={};o&&(T(o.profile)||(z(o.profile)?bo[o.profile]&&n.setProfile(bo[o.profile]):n.setProfile(o.profile)),o.systemAudio&&(c.systemAudio=!0,c.echoCancellation=o.echoCancellation,c.noiseSuppression=o.noiseSuppression,c.autoGainControl=o.autoGainControl),T(o.fillMode)||(d.objectFit=o.fillMode),o.videoTrack&&(c.videoTrack=o.videoTrack),o.audioTrack&&(c.audioTrack=o.audioTrack),o.captureElement&&(c.captureElement=o.captureElement),o.preferDisplaySurface&&(c.preferDisplaySurface=o.preferDisplaySurface));let u=yield n.capture(c);if(o!=null&&o.qosPreference){let p=ir(o.qosPreference);n.mediaTrack.contentHint=p}else o!=null&&o.videoTrack||(n.mediaTrack.contentHint=ir(ot.QOS_PREFERENCE_CLEAR));if(n.mediaTrack.addEventListener(h.ENDED,()=>{this._stopScreenShare(),this.emit($.SCREEN_SHARE_STOPPED)}),u.getAudioTracks()[0]&&(a=new Ht(this._room.audioManager),a.setInputMediaStreamTrack(u.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),De(n,n).add("player-state-changed",p=>{this.emit($.VIDEO_PLAY_STATE_CHANGED,P(N({},p),{userId:"",streamType:"sub"}))}),s&&this._room.isJoined){let p=[n];a&&p.push(a),this._room.publish(...p).catch(()=>{})}this._localScreenTrack=n,this._localScreenAudioTrack=a,this._localScreenConfig=P(N({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:n})})}updateScreenShare(e){return _(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:s,option:o}=e,n={};if(o&&(T(o.fillMode)||(n.objectFit=o.fillMode),o.qosPreference)){let a=ir(o.qosPreference);this._localScreenTrack.mediaTrack.contentHint=a}this._room.isJoined&&!T(s)&&(s&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!s&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:t,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),ei(this._localScreenConfig,e)})}stopScreenShare(){return _(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return _(this,null,function*(){let{view:t,userId:s,streamType:o,option:n}=e,a=`${s}_${o}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${s}, streamType:${o}`);return}let c=this._room.remotePublishedUserMap.get(s);if(!c)return;let d={},u=o==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;this._listenOutputTrackChanged(u),n&&(T(n.fillMode)||(d.objectFit=n.fillMode),T(n.mirror)||(d.mirror=n.mirror),d.canvasRender=n.canvasRender,o==="main"&&!T(n.small)&&(c.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,u.user))),yield this._room.subscribe(u),yield this._updateVideoPlayOption({view:t,playOption:d,track:u}),this._emitTrackEvent(u),this._remoteVideoConfigMap.set(a,{config:e}),n&&!T(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:u,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return _(this,null,function*(){var v,U;let{view:t,userId:s,streamType:o,option:n}=e,a=`${s}_${o}`,c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(s))return;let d={};n&&(T(n.fillMode)||(d.objectFit=n.fillMode),T(n.mirror)||(d.mirror=n.mirror));let u=null,p=this._room.remotePublishedUserMap.get(s);if(o==="main"&&(p==null?void 0:p.muteState.hasVideo)&&(u=p.remoteVideoTrack),o==="sub"&&(p==null?void 0:p.muteState.hasAuxiliary)&&(u=p.remoteAuxiliaryTrack),!u)return;let{config:m}=c;o==="main"&&n&&!T(n.small)&&this._room.changeType(n.small,u.user),yield this._updateVideoPlayOption({view:t,playOption:d,track:u,prevConfig:m}),ei(m,e);let f=T(n==null?void 0:n.receiveWhenViewVisible)?(v=m.option)==null?void 0:v.receiveWhenViewVisible:n.receiveWhenViewVisible,R=T(t)?m.view:t,C=T(n==null?void 0:n.viewRoot)?(U=m.option)==null?void 0:U.viewRoot:n.viewRoot;this._observeView({remoteTrack:u,view:R,receiveWhenViewVisible:f,viewRoot:C})})}stopRemoteVideo(e){return _(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return _(this,null,function*(){let s=[],o=this._room.remotePublishedUserMap.get(e.userId);if(o){let{muteState:a,remoteVideoTrack:c,remoteAuxiliaryTrack:d}=o;e.streamType==="main"&&(c.stop(),a.hasVideo&&s.push(c)),e.streamType==="sub"&&(d.stop(),a.hasAuxiliary&&s.push(d))}for(let a of s)t&&(yield this._room.unsubscribe(a),this._mediaTrackMap.get(a.outMediaTrack)===a.userId&&this._mediaTrackMap.delete(a.outMediaTrack));let n=this._remoteVideoConfigMap.get(`${e.userId}_${e.streamType}`);n&&n.observer&&n.observer.disconnect(),this._remoteVideoConfigMap.delete(`${e.userId}_${e.streamType}`)})}muteRemoteAudio(e,t){return _(this,null,function*(){if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let s=[...this._room.remotePublishedUserMap.values()];for(let o of s)o.muteState.hasAudio&&!this._remoteAudioConfigMap.has(o.userId)&&(yield this._startRemoteAudio({userId:o.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}));this._remoteAudioMuteMap.set(e,t)})}setRemoteAudioVolume(e,t){if(e==="*"){let s=[...this._room.remotePublishedUserMap.values()];for(let o of s)this._updateAudioPlayOption({playOption:{volume:t},track:o.remoteAudioTrack})}else if(e){let s=this._room.remotePublishedUserMap.get(e);s&&this._updateAudioPlayOption({playOption:{volume:t},track:s.remoteAudioTrack})}}startPlugin(e,t){return _(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return _(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return _(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,s){return this.listeners(e).includes(t)?this:(this._log.debug("on",e),super.on(e,t,s),this._eventListened.add(e),e===di.EVENT.AUDIO_FRAME&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(o=>{this.emit(di.EVENT.AUDIO_FRAME,{data:o})})),this)}off(e,t,s){var o,n;return this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners(),(o=this._getPCMAbortCtrl)==null||o.abort("off")):(super.off(e,t,s),e===di.EVENT.AUDIO_FRAME&&((n=this._getPCMAbortCtrl)==null||n.abort("off"))),this}getAudioTrack(e={userId:"",streamType:"main"}){var o,n;let t,s="main";if(z(e)?t=e:(t=e.userId,e.streamType&&(s=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);if(a)return a.remoteAudioTrack.mediaTrack}else return s==="sub"?((o=this._localScreenAudioTrack)==null?void 0:o.mediaTrack)||null:((n=this._localAudioTrack)==null?void 0:n.mediaTrack)||null;return null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:s="main"}=e;if(t===""){if(s==="main"&&this._localVideoTrack)return this._localVideoTrack.mediaTrack;if(s==="sub"&&this._localScreenTrack)return this._localScreenTrack.mediaTrack}else{let o=this._room.remotePublishedUserMap.get(t);if(o)return s==="main"?o.remoteVideoTrack.mediaTrack:o.remoteAuxiliaryTrack.mediaTrack}return null}getVideoSnapshot(e={}){let{userId:t,streamType:s="main"}=e;if(t){let o=this._room.remotePublishedUserMap.get(t);if(s==="main"&&(o==null?void 0:o.muteState.hasVideo))return o.remoteVideoTrack.getVideoFrame();if(s==="sub"&&(o==null?void 0:o.muteState.hasAuxiliary))return o.remoteAuxiliaryTrack.getVideoFrame()}else{if(s==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(s==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}setCurrentSpeaker(e){var t,s;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(s=this._localScreenAudioTrack)==null||s.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(o=>o.remoteAudioTrack.setAudioOutput(e))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return _(this,null,function*(){let{userId:t,option:s}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let o=this._room.remotePublishedUserMap.get(t);if(!o)return;let n={};s&&(T(s.volume)||(n.volume=s.volume));let a=o.remoteAudioTrack;this._listenOutputTrackChanged(a),this._speakerId&&a.setAudioOutput(this._speakerId);try{this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(a),yield this._updateAudioPlayOption({playOption:n,track:a})}catch(c){throw this._remoteAudioConfigMap.delete(t),c}this._emitTrackEvent(a)})}_stopRemoteAudio(e,t=!0){return _(this,null,function*(){let s=this._room.remotePublishedUserMap.get(e.userId);s&&(s.remoteAudioTrack.stop(),s.muteState.hasAudio&&t&&(yield this._room.unsubscribe(s.remoteAudioTrack)),this._mediaTrackMap.get(s.remoteAudioTrack.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(s.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`)})}_updateVideoPlayOption(n){return _(this,arguments,function*({view:e,playOption:t,track:s,prevConfig:o}){if(s.setMirror(t.mirror),T(e)&&o&&o.view&&!Wa(t)){let a=Os(o.view);a.length>0&&(yield s.play(a,t))}if(!T(e)){let a=Os(e);a.length>0?yield s.play(a,t):s.stop()}})}_updateAudioPlayOption(o){return _(this,arguments,function*({playOption:e={},track:t,prevConfig:s}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}T(e.muted)||t.setPlayerMute(e.muted),T(e.volume)||t.setAudioVolume(e.volume/100)})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,t=!0){let s=e.isRemote?e.userId:"";!e.outMediaTrack||t&&this._mediaTrackMap.get(e.outMediaTrack)===s||(this._mediaTrackMap.set(e.outMediaTrack,s),this.emit($.TRACK,{userId:s,streamType:tr(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var t,s,o;let e=[];if(((t=this._localAudioConfig)==null?void 0:t.publish)&&this._localAudioTrack&&e.push(this._localAudioTrack),((s=this._localVideoConfig)==null?void 0:s.publish)&&this._localVideoTrack&&e.push(this._localVideoTrack),(o=this._localScreenConfig)!=null&&o.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:s=!1,viewRoot:o}){if(T(t))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${tr(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||he(t)&&t.length===0||!s){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let d=n.visibleViewMap||new Map,u=-1;(!a||a.root!==o)&&(a==null||a.disconnect(),d.clear(),a=new IntersectionObserver(m=>{m.forEach(f=>{d.set(f.target,f.isIntersecting)}),clearTimeout(u),u=window.setTimeout(()=>{[...d.values()].find(R=>R)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:o}));let p=new Set(Os(t));d.forEach((m,f)=>{p.has(f)||(a.unobserve(f),d.delete(f))}),p.forEach(m=>{d.set(m,!0),a.observe(m)}),a.takeRecords().forEach(m=>{d.set(m.target,m.isIntersecting)}),n.visibleViewMap=d,n.observer=a}_exitRoom(){return _(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let t=e.includes("main")?"main":"sub",s=e.split(`_${t}`)[0];s&&this._stopRemoteVideo({userId:s,streamType:t}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._room.remotePublishedUserMap.forEach(e=>{me(e.remoteAudioTrack),me(e.remoteVideoTrack),me(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return _(this,null,function*(){var e;if(!!this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...t).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),me(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_initActiveSpeaker(){return _(this,null,function*(){if(Le&&!Pr(Le))this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:Le});else{let e=yield Xi();if(e[0]&&!Pr(e[0]))Le=e[0],this.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let t=({track:s})=>{s.kind==="audio"&&(!Le||Pr(Le))&&(this._initActiveSpeaker(),g.off("102",this._initActiveSpeaker))};g.on("102",t)}}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let s=this._room.remotePublishedUserMap.get(e);if(s){let o=t==="main"?s.remoteVideoTrack:s.remoteAuxiliaryTrack;this._room.subscribe(o).then(()=>{this._emitTrackEvent(o)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:t}){t.hasAudio&&t.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:t}){this._stopRemoteVideo({userId:e,streamType:t},!1).catch(()=>{})}sendSEIMessage(e,t){var o;let s=this._plugins.get("SEI");s&&(s.update({buffer:e,options:P(N({seiPayloadType:243},t),{small:!!((o=this._localVideoTrack)!=null&&o.small)})}),D.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,s;(s=(t=this._room).sendCustomMessage)==null||s.call(t,e),D.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){I.setLogLevel(e),T(t)||(t?I.enableUploadLog():I.disableUploadLog())}static isSupported(){return nn()}static getCameraList(e=!0){return Xe(e)}static getMicrophoneList(e=!0){return Be(e)}static getSpeakerList(e=!0){return Xi(e)}static setCurrentSpeaker(e){return _(this,null,function*(){(yield Xi()).forEach(s=>{s.deviceId===e&&(Yn.forEach(o=>{o.setCurrentSpeaker(e),o.emit($.DEVICE_CHANGED,{type:"speaker",action:"active",device:s})}),Le=s)})})}static _addKVStat({type:e,key:t,value:s,base:o,useUV:n,version:a}){switch(a&&(Wi.version=a),e){case"count":Wi.addCount({key:t,useUV:n});break;case"enum":Wi.addEnum({key:t,value:s,useUV:n});break;case"number":Wi.addNumber({key:t,value:s,split:o});break}}},X=di;l(X,"_loggerManager",I),l(X,"EVENT",$),l(X,"ERROR_CODE",w),l(X,"TYPE",ot),l(X,"frameWorkType",30),y([oe({replaceArg:r=>({argIndex:0,value:{name:"plugin"in r?r.plugin.Name:r.Name,assetsPath:"assetsPath"in r?r==null?void 0:r.assetsPath:"default"}})})],X.prototype,"use",1),y([ke(Ce.TRTC.enterRoom),Mi("room",([r],[i])=>(r.roomId||r.strRoomId)===(i.roomId||i.strRoomId)&&r.userId===i.userId&&r.sdkAppId===i.sdkAppId),W(r=>function(i){return this._log.setUserId(i.userId),this._log.setSdkAppId(i.sdkAppId),r.call(this,i)}),oe()],X.prototype,"enterRoom",1),y([oe()],X.prototype,"exitRoom",1),y([ke(Ce.TRTC.switchRole),er("room",{merge:(r,i)=>i}),oe()],X.prototype,"switchRole",1),y([oe()],X.prototype,"destroy",1),y([ke(Ce.TRTC.startLocalAudio),Mi("audio",([r],[i])=>{var e,t;return((e=r==null?void 0:r.option)==null?void 0:e.microphoneId)===((t=i==null?void 0:i.option)==null?void 0:t.microphoneId)}),oe()],X.prototype,"startLocalAudio",1),y([ke(Ce.TRTC.updateLocalAudio),er("audio",{debounce:{delay:200,getKey:()=>`${Hu}-localAudio`,isNeedToDebounce:r=>{var i;return!T((i=r.option)==null?void 0:i.captureVolume)}}}),oe()],X.prototype,"updateLocalAudio",1),y([ki("audio"),oe()],X.prototype,"stopLocalAudio",1),y([ke(Ce.TRTC.startLocalVideo),Mi("video",([r],[i])=>{var e,t;return((e=r==null?void 0:r.option)==null?void 0:e.cameraId)===((t=i==null?void 0:i.option)==null?void 0:t.cameraId)}),oe()],X.prototype,"startLocalVideo",1),y([ke(Ce.TRTC.updateLocalVideo),er("video"),oe()],X.prototype,"updateLocalVideo",1),y([ki("video"),oe()],X.prototype,"stopLocalVideo",1),y([ke(Ce.TRTC.startScreenShare),Mi("screen",()=>!0),oe()],X.prototype,"startScreenShare",1),y([ke(Ce.TRTC.updateScreenShare),er("screen"),oe()],X.prototype,"updateScreenShare",1),y([oe()],X.prototype,"stopScreenShare",1),y([ke(Ce.TRTC.startRemoteVideo),Mi(r=>`v${r.userId}${r.streamType}`,()=>!0),oe({getRemoteId:r=>`${r.userId}_${r.streamType}`})],X.prototype,"startRemoteVideo",1),y([ke(Ce.TRTC.updateRemoteVideo),er(r=>`v${r.userId}${r.streamType}`),oe({getRemoteId:r=>`${r.userId}_${r.streamType}`})],X.prototype,"updateRemoteVideo",1),y([ke(Ce.TRTC.stopRemoteVideo),W(r=>function(i){return _(this,null,function*(){if(i.userId==="*"){let e=[];return this._room.remotePublishedUserMap.forEach(t=>{this._remoteVideoConfigMap.has(`${t.userId}_${"main"}`)&&e.push(this.stopRemoteVideo({streamType:"main",userId:t.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${t.userId}_${"sub"}`)&&e.push(this.stopRemoteVideo({streamType:"sub",userId:t.userId}).catch(()=>{}))}),Promise.all(e)}return r.call(this,i)})}),oe({getRemoteId:r=>`${r.userId}_${r.streamType}`})],X.prototype,"stopRemoteVideo",1),y([ki(r=>`v${r.userId}${r.streamType}`)],X.prototype,"_stopRemoteVideo",1),y([ke(...Ce.TRTC.muteRemoteAudio),oe({getRemoteId:r=>r})],X.prototype,"muteRemoteAudio",1),y([ud(...Ce.TRTC.setRemoteAudioVolume),ku(200,r=>r),oe({getRemoteId:r=>r})],X.prototype,"setRemoteAudioVolume",1),y([Xn("start"),Tt(r=>{var i;return(i=r.afterStart)==null?void 0:i.call(r)}),Mi((r,i)=>r.disableRandomCall?null:r.getAlias()+r.getGroup(i)),oe({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>nc[r.getName()]})],X.prototype,"startPlugin",1),y([Xn("update"),er((r,i)=>r.disableRandomCall?null:r.getAlias()+r.getGroup(i)),oe({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>ac[r.getName()]})],X.prototype,"updatePlugin",1),y([Xn("stop"),ki((r,i)=>{if(r.disableRandomCall)return null;let e=r.getGroup(i),t=r.getAlias();return e==="*"?new RegExp(`${t}.*`):t+e}),oe({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>cc[r.getName()]})],X.prototype,"stopPlugin",1),y([ud(...Ce.TRTC.enableAudioVolumeEvaluation)],X.prototype,"enableAudioVolumeEvaluation",1),y([oe()],X.prototype,"getVideoSnapshot",1),y([oe()],X.prototype,"setCurrentSpeaker",1),y([Mi(r=>`a${r.userId}`,()=>!0)],X.prototype,"_startRemoteAudio",1),y([W(r=>function(i){return _(this,null,function*(){return i.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(e=>this._stopRemoteAudio(P(N({},i),{userId:e.userId})).catch(()=>{}))):r.call(this,i)})}),ki(r=>`a${r.userId}`)],X.prototype,"_stopRemoteAudio",1),y([ki("room")],X.prototype,"_exitRoom",1),y([ki("screen")],X.prototype,"_stopScreenShare",1),y([ke(...Ce.TRTC.sendSEIMessage),cd({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...r)=>r[0].byteLength})],X.prototype,"sendSEIMessage",1),y([ke(Ce.TRTC.sendCustomMessage),cd({timesInSecond:30,maxSizeInSecond:8e3,getSize:r=>r.data.byteLength})],X.prototype,"sendCustomMessage",1),y([ke(Ce.TRTC.create)],X,"_create",1);var ro=X;var Sd=class{constructor(){this._set=new Set;g.on(E.LEAVE_SUCCESS,this.delete,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,s){return`${t}_${e}_${i}_${s}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:s}){return s.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,s.useStringRoomId))}};function v_(){return _(this,null,function*(){let r,i;try{let p=yield Be();r=p&&p.length}catch(p){}try{let p=yield Xe();i=p&&p.length}catch(p){}let e={microphone:r,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:s,isH264DecodeSupported:o,isVp8DecodeSupported:n}=this.checkSystemResult.detail,a=Et.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:t,h264Decode:o,vp8Encode:s,vp8Decode:n},d={browser:a.browser,os:a.os,trtc:c,devices:e},u={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};Z.uploadEvent({log:`trtcstats-${JSON.stringify(d)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(d)}`),Z.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(u)}`,userId:this.userId})})}function Wu(){return W(r=>{let i=new Sd;return function(e,t,s){return _(this,null,function*(){let o=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=t,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new b({code:A.INVALID_OPERATION,message:L({key:M.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new b({code:A.INVALID_OPERATION,message:L({key:M.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:o}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${o} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),g.emit(E.JOIN_START,{room:this,roomId:o,params:e}),this.checkSystemResult=yield Et.checkSystemRequirementsInternal(),this.checkDestroy();let n=we.getEnv();n||(n=qt.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(No.OLD_CLOUD_LADDER)?n=qt.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(No.WEBRTC)&&(n=qt.WEBRTC))),Z.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),v_.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!Et.isWebRTCSupported()||!a&&!c)throw new b({code:A.NOT_SUPPORTED,message:L({key:M.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!we.getEnv()&&(yield this.schedule(e,s));let d=yield r.call(this,e,t,s);return this.roomId=o,this._joinedTimestamp=we.performanceNow(),g.emit(E.JOIN_SUCCESS,{room:this}),s===30&&!e.component&&Z.uploadEvent({log:`stat-conv-${Number(Yt)}-${location.hostname}`,userId:this.userId}),d}catch(d){throw i.delete({room:this,roomId:o}),g.emit(E.JOIN_FAILED,{room:this,error:d}),d}})}})}var Ju=()=>W(r=>function(...i){return _(this,null,function*(){g.emit(E.LEAVE_START,{room:this}),yield r.call(this),g.emit(E.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function ju(){return W(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var Xu=Se(Ne());var _e={SETUP_SUCCESS:"1",SETUP_FAILED:"5",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",DISCONNECTED:"5",RECONNECT_FAILED:"4"};var Wt={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140},qu=[Wt.UPDATE_REMOTE_MUTE_STAT,Wt.UPLINK_NETWORK_STATS,Wt.USER_LIST_RES,Wt.MUTE_RESULT,Wt.SERVER_FIRST_PACKAGE_RECEIVED],V={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg"},j={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3",ABILITY_STATUS_REPORT:"ability_status_report",RECONNECT_WS:"reconnect",SEND_CUSTOM_MSG:"channel_msg"};var Kn=new Set;function Qu(r){let i=[...Kn.values()].find(e=>e.room.userId===r&&!e.room.isJoined);return i||null}var qr=class extends Xu.default{constructor(e){var s,o;super();l(this,"room");l(this,"url");l(this,"backupUrl");l(this,"race");l(this,"destroyed",!1);l(this,"_socketInUse");l(this,"_socket");l(this,"_backupSocket");l(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0});l(this,"_currentState","DISCONNECTED");l(this,"_isReconnecting",!1);l(this,"_seq",0);l(this,"_log");l(this,"_lastMessageTime",-1);l(this,"_connnectStartTime",-1);l(this,"_stopConnectRetry");l(this,"bytesSent",0);l(this,"bytesReceived",0);l(this,"keepAlive",!1);l(this,"signalDomainWhenUnifiedProxy");this.room=e.room,this.race=T(e.race)?!0:e.race,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy,(((o=(s=this.room.scheduleResult)==null?void 0:s.config)==null?void 0:o.keepAliveClient)||0)-Kn.size>0&&this.room.enableSPC&&(this.keepAlive=!0,Kn.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=I.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;return this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`),this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get sdkAppId(){return this.room.sdkAppId}get userId(){return this.room.userId}get userSig(){return this.room.userSig}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return _(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}]${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connnectStartTime=x();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 ys(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?h.BACKUP:h.MAIN),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:s}){let o=new WebSocket(e);this.bindSocket(o),s?this._socket=o:this._backupSocket=o;let n=-1;return new Promise((a,c)=>{o.onclose=c,o.onerror=c,o.onopen=()=>a(o),t&&(n=setTimeout(()=>{this.unbindAndCloseSocket(s?h.MAIN:h.BACKUP),c(new b({code:A.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{o.onclose=null,o.onerror=null,o.onopen=null,clearTimeout(n)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===h.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}onclose(e){if(e.target===this._socketInUse&&(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),!e.wasClean||e.code!==1e3)){this._socketInUse.onclose=null,this._socketInUse.close(4011);let t=this._socketInUse===this._socket;this.unbindAndCloseSocket(t?h.MAIN:h.BACKUP),this._socketInUse=null,this.reconnect()}}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this._socketInUse=null,this.reconnect())}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=Ko(e.data);let t=JSON.parse(e.data),{cmd:s,data:o}=t,n=Object.values(Wt),c=Object.keys(Wt)[n.indexOf(s)],d=V[c]||s;switch(qu.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),d&&this._log.info(`Received event: [ ${d} ]`)),s){case Wt.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=o.clientIp,this._signalInfo.signalIp=o.signalInnerIp,o.svrTime&&Yd(o.svrTime),this._log.info("ChannelSetup Success"),D.addSuccessEvent({key:521701,cost:x()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(_e.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let u=new b({code:A.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:L({key:M.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),D.addFailedEvent({key:521701,error:u}),this.emit(_e.SETUP_FAILED,u)}break}case Wt.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=o.relayOuterIp,this._signalInfo.relayInnerIp=o.relayInnerIp,this._signalInfo.relayPort=o.relayPort,this._signalInfo.tinyId=t.tinyId,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(d,{data:t});break}default:this.emit(String(d),{data:t});break}}reGetSignalChannelUrl(){return _(this,null,function*(){try{if(!this.room.joinParams)return;kt(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}reconnect(){return _(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive){this.close();return}this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:s,relayInnerIp:o,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:j.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:o,relayOuterIp:s,relayPort:n},responseCommand:V.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),D.addSuccessEvent({key:521702,cost:x()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(D.addFailedEvent({key:521702,error:a.code}),this._log.warn(`reconnect failed, ${a.code} ${a.message}`),this.room.reJoin())}catch(e){this._log.error(e),this.room.reJoin()}}})}send(e,t={}){if(this.isConnected&&!this.room.isLeft){let s={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},o=JSON.stringify(s);return this._socketInUse.send(o),this.bytesSent+=Ko(o),s.seq}}sendWaitForResponse({command:e,data:t,timeout:s=5e3,responseCommand:o,commandDesc:n,enableLog:a=!0}){return new Promise((c,d)=>{let u=setTimeout(()=>{this.off(o,p);let f=new b({code:A.API_CALL_TIMEOUT,message:L({key:M.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(f),d(f)},s),p=f=>{f.data.seq===m&&(clearTimeout(u),this.off(o,p),c(f))};this.on(o,p);let m=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:s,retries:o=0,retryTimeout:n=0}=e;return Dt({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${s} when connected`),this.once(_e.CONNECTED,a))},onRetrying:a=>{this._log.warn(`${t||s} timeout observed, retrying [${a}/${o}]`)},settings:{retries:o,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),Kn.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(h.MAIN),this.unbindAndCloseSocket(h.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`);let t=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(V.JOIN_ROOM_RESULT,s)},e*1e3),s=o=>{o.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(t),this.off(V.JOIN_ROOM_RESULT,s))};this.on(V.JOIN_ROOM_RESULT,s)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(_e.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(_e.CONNECTED):e==="DISCONNECTED"&&this.emit(_e.DISCONNECTED))}};y([it({settings:{retries:1/0,timeout:2e3},onError(r,i){!this.room.isDestroyed&&!this.destroyed&&i()},onRetrying(r,i){this._log.warn(`retrying to connect ${r}`),r>=3&&r%3===0&&this.reGetSignalChannelUrl(),i&&(this._stopConnectRetry=i,(this.room.isDestroyed||this.destroyed)&&i())}})],qr.prototype,"connect",1);var zu=Se(Ne());var Id=0,Ad=!1,Zn=new Set,O_=r=>Id>2&&!Ad&&Zn.size===0&&r,Cd=!1,Ke=class{constructor(i){l(this,"userId");l(this,"tinyId");l(this,"_sdpSemantics");l(this,"_isUplink");l(this,"_room");l(this,"_log");l(this,"_signalChannel");l(this,"_isErrorObserved",!1);l(this,"_waitForPeerConnectionConnectedPromise");l(this,"_waitForPeerConnectionConnectedPromiseReject",null);l(this,"_peerConnection",null);l(this,"_emitter",new zu.default);l(this,"_currentState","DISCONNECTED");l(this,"_isReconnecting",!1);l(this,"_reconnectionCount",0);l(this,"_reconnectionTimer",-1);l(this,"_isFirstConnection",!0);l(this,"_prevTime",-1);l(this,"_localAddress");l(this,"_remoteAddress");this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=I.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=x())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,D.addSuccessEvent({key:521705,cost:Math.min(x()-this._prevTime,30*1e3)})):this._isReconnecting&&D.addSuccessEvent({key:521706,cost:x()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,D.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&D.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(),Zn.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 b({code:A.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return at;let i=null;if(this._isUplink){if(!bi()||this._peerConnection.getSenders().length===0)return at;i=this._peerConnection.getSenders()[0].transport}else{if(!Hi()||this._peerConnection.getReceivers().length===0)return at;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:at}onConnectionStateChange(i){let e=this._peerConnection.iceConnectionState,t=this.getDTLSTransportState();if(this._log.info(`connectionState: ${i.target.connectionState}, ICE: ${e}, DTLS: ${t}`),i.target.connectionState===se.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===se.FAILED||i.target.connectionState===se.CLOSED){let s=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,o=new b({message:s,code:A.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",o)}(i.target.connectionState===se.CONNECTED||i.target.connectionState===se.COMPLETED)&&(this.logSelectedCandidate(),Z.logSuccessEvent({userId:this._room.userId,eventType:Ve.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(Id=0,Ad=!1,Cd=!0,Zn.add(this)):Zn.delete(this),g.emit(E.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:i,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:i}),this._currentState=i,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return _(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(yi(e)){let t=i.get(e.localCandidateId),s=i.get(e.remoteCandidateId);t&&(this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.candidateType==="relay"?`relayProtocol:${t.relayProtocol}`:""}`),this._localAddress=`${t.ip||t.address}:${t.port}`),s&&(this._log.info(`remote candidate: ${s.candidateType} ${s.protocol}:${s.ip||s.address}:${s.port}`),this._remoteAddress=`${s.protocol}:${s.ip||s.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(n),o(),i())},s=({room:a})=>{a===this._room&&(clearTimeout(n),o(),e(new b({code:A.API_CALL_ABORTED,message:L({key:M.CONNECTION_ABORTED,data:"leave room"})})))},o=()=>{g.off(E.LEAVE_SUCCESS,s,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{o();let a=new b({code:A.API_CALL_TIMEOUT,message:"connection timeout"});Id+=1,O_(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Ad=!0,this._emitter.emit("firewall-restriction")),e(a)},cs);g.on(E.LEAVE_SUCCESS,s,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(_e.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Xt()){this._log.warn(`SDK has tried reconnect for ${this._reconnectionCount} times, but all failed, please check your network`),this.stopReconnection();let i=new b({code:this._isUplink?A.UPLINK_RECONNECTION_FAILED:A.DOWNLINK_RECONNECTION_FAILED,message:L({key:this._isUplink?M.UPLINK_RECONNECTION_FAILED:M.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(_e.CONNECTED,this.reconnect,this),-1)}on(i,e,t){this._emitter.on(i,e,t)}off(i,e,t){this._emitter.off(i,e,t)}getIsReconnecting(){return this._isReconnecting}get isH264(){var i,e;return!!((e=(i=this._peerConnection)==null?void 0:i.remoteDescription)!=null&&e.sdp.includes("H264"))}};var Nd=Se(bd());var ce=function(r){return Nd.default.parse(r)},He=function(r){return Nd.default.write(r)},sh=function(r){let i=ce(r);return i.media.forEach(e=>{e.type===h.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),He(i)};function oh(r){let i=ce(r);return i.media.forEach(e=>{var t,s;if(e.type===h.VIDEO){let o=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&o.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let d=c.match(/apt=(\d+)/);d&&d[1]&&o.has(Number(d[1]))&&o.add(a)});let n=({payload:a})=>!o.has(a);e.rtp=e.rtp.filter(n),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=(s=e.payloads)==null?void 0:s.split(" ").filter(a=>!o.has(Number(a))).join(" ")}}),He(i)}function ea(r){return Object.keys(r).filter(i=>r[i])}var Dd=class extends Ke{constructor(e){super(P(N({},e),{isUplink:!1}));l(this,"_flag",0);l(this,"role","anchor");l(this,"remoteAudioTrack");l(this,"remoteVideoTrack");l(this,"remoteAuxiliaryTrack");l(this,"ssrc",{audio:0,video:0,auxiliary:0});l(this,"_isSDPExchanging",!1);this.flag=e.flag,this.remoteAudioTrack=e.remoteAudioTrack||new ni(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new St(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Br(this._room,this)}get videoCodec(){var t,s;let e=(s=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:s.sdp;return e?e.includes("H264")?"h264":"vp8":"h264"}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return Ri(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,s,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===h.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),s}onTrack(e){let t=e.streams[0],{track:s}=e,o=t.id===as?h.MAIN:h.AUXILIARY;this._log.debug(`ontrack ${o} ${s.kind}`);let n=h.AUDIO;s.kind===h.VIDEO&&(n=o===h.MAIN?h.VIDEO:h.AUXILIARY);let a=this.remoteAudioTrack;n===h.VIDEO?a=this.remoteVideoTrack:n===h.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(s)}addRRTRLine(e){let t=e.split(`\r
|
|
69
69
|
`),s=new Map;t.forEach((n,a)=>{/^a=rtcp-fb:/.test(n)&&t[a+1]&&!/^a=rtcp-fb:/.test(t[a+1])&&s.set(a+1,`${n.match(/^a=rtcp-fb:\d+/)[0]} rrtr`)});let o=[...s];for(let n=0;n<o.length;n++){let[a,c]=o[n];t.splice(a+n,0,c)}return t.join(`\r
|
|
70
|
-
`)}addSPSDescription(e){let t=ce(e);return t.media.forEach(s=>{s.type===h.VIDEO&&s.fmtp.forEach(o=>{o.config+=";sps-pps-idr-in-keyframe=1"})}),He(t)}removeSDESDescription(e){let t=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],s=ce(e);return s.media.forEach(o=>{!o.ext||(o.ext=o.ext.filter(n=>!t.includes(n.uri)))}),He(s)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return _(this,null,function*(){var s,o;try{if((((s=this._peerConnection)==null?void 0:s.connectionState)===se.NEW||((o=this._peerConnection)==null?void 0:o.connectionState)===se.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e)){this._peerConnection||(this.initialize(),yield this.connect(e));return}if(this._log.info(`subscribe ${t} ${JSON.stringify(e)}`),this._peerConnection||this._isSDPExchanging){let 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 b({code:A.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}unsubscribe(s){return _(this,arguments,function*({remoteTracks:e,streamType:t}){if(this._currentState==="CONNECTED"&&(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed)){this._log.info(`${t} stream already unsubscribed`);return}let o=N({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(a=>a===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${Zn(o)}]`),yield this.sendSubscription(n,o),n==="unsubscribe"&&(this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,t=this.subscribeState){let s={srcTinyId:this.tinyId,srcUserId:this.userId},o=q.UNSUBSCRIBE,n=V.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(s={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=q.SUBSCRIBE_CHANGE,n=V.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:o,data:s,responseCommand:n,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new b({code:a.code,message:L({key:M.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}connect(){return _(this,arguments,function*(e=this.subscribeState){try{yield this.exchangeSDP(e),yield this.waitForPeerConnectionConnected()}catch(t){throw this.closePeerConnection(!0),t}})}exchangeSDP(e){return _(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:s}=this._peerConnection.localDescription,o={type:t,sdp:s,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:q.SUBSCRIBE,commandDesc:"exchange sdp",data:o,responseCommand:V.SUBSCRIBE_RESULT,timeout:Ia});if(!this._peerConnection){let a=new b({code:A.INVALID_OPERATION,message:L({key:M.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return _(this,null,function*(){let e={voiceActivityDetection:!1};tt()&&this._sdpSemantics===pi?(this._peerConnection.addTransceiver(h.AUDIO,{direction:z.RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:z.RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:z.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:s}=yield sn();s||(this._log.warn("remove h264 desc from sdp"),t.sdp=oh(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=sh(t.sdp),this._sdpSemantics===pi&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this._peerConnection.setLocalDescription(t)})}onSubscribeResult(e){return _(this,null,function*(){let{code:t,message:s=""}=e&&e.data||{},{type:o,sdp:n}=e&&e.data&&e.data.data||{};if(t===Pi)throw new b({code:A.NOT_SUPPORTED_H264,message:L({key:M.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new b({code:t,message:L({key:M.EXCHANGE_SDP_FAILED,data:{errMsg:s}})});this._log.debug(`accept remote answer: ${n}`),yield this._peerConnection.setRemoteDescription({type:o,sdp:n}),this.updateSSRC(n)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{ce(e).media.forEach(s=>{if(!!s.ssrcs)if(s.type===h.AUDIO){let o=s.ssrcs.find(n=>{var a;return(a=n.value)==null?void 0:a.includes(ns)});o&&(this.ssrc.audio=Number(o.id))}else{let o=s.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(ns)}),n=s.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(fa)});o&&(this.ssrc.video=Number(o.id)),n&&(this.ssrc.auxiliary=Number(n.id))}})}catch(t){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return _(this,null,function*(){if(!(Ie(Nd.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(t){let s=kt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${s/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},s)}})}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}},oo=Nd;y([J(r=>function(...i){return new Promise((e,t)=>{let s=o=>{this._emitter.off("closed",s),t(new b({code:A.API_CALL_ABORTED,message:L({key:M.CONNECTION_ABORTED,data:o})}))};this._emitter.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this._emitter.off("closed",s)})})})],oo.prototype,"subscribe",1),y([gt(Ke.prototype.afterConnect),In(Ke.prototype.beforeConnect)],oo.prototype,"connect",1);var bd=oo;var ah={voiceActivityDetection:!1},vd=class extends Ke{constructor(e){super(P(N({},e),{isUplink:!0}));u(this,"localMainAudioTrack",null);u(this,"localMainVideoTrack",null);u(this,"localAuxAudioTrack",null);u(this,"localAuxVideoTrack",null);u(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});u(this,"_isPublishingAux",!1);u(this,"_publishingLocalAudioTrack");u(this,"_publishingLocalVideoTrack");u(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});u(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,s,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(Lt()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((s=a[1])!=null&&s.track),e.smallVideo=!!((o=a[2])!=null&&o.track),e.auxVideo=!!((n=a[3])!=null&&n.track)):a.forEach(c=>{c.track&&(c.track.kind===h.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var n,a,c;let s=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:s,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:s,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:s,state:e}))),o}publish(o){return _(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:s}){this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),t&&(this._publishingLocalVideoTrack=t),this._isPublishingAux=s;let n;t&&!s&&t.small&&(n=this._room.videoManager.smallTrack),this.sendMediaSettings(),tt()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:s}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:n}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,s?(t&&(this.localAuxVideoTrack=t),e&&(this.localAuxAudioTrack=e)):(t&&(this.localMainVideoTrack=t),e&&(this.localMainAudioTrack=e)),this.installTrackMuteEvents(e,t),this.sendMutedFlag()})}publishByTransceiver(n){return _(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:s,isAuxiliary:o}){this._log.info("publish by transceiver");let a=new MediaStream,c=t==null?void 0:t.outMediaTrack,d=e==null?void 0:e.outMediaTrack;d&&a.addTrack(d),c&&a.addTrack(c);let l=this._peerConnection.getTransceivers();if(l.length===0)this._peerConnection.addTransceiver(d||h.AUDIO,{direction:z.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?h.VIDEO:c||h.VIDEO,{direction:z.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s||h.VIDEO,{direction:z.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?c||h.VIDEO:h.VIDEO,{direction:z.SENDONLY,streams:[a]}),yield this.connect();else{let p=[];if(d&&(l[0].sender.track||p.push(0),yield l[0].sender.replaceTrack(d),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:h.AUDIO})),c){let m=o?3:1;yield l[m].sender.replaceTrack(c),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:h.VIDEO,videoType:o?h.AUXILIARY:h.BIG}),p.push(m),s&&(yield l[2].sender.replaceTrack(s),yield this.setBandwidth({bandwidth:t.small.bitrate,type:h.VIDEO,videoType:h.SMALL}),p.push(2))}yield this.setTransceiverDirection(z.SENDONLY,p),yield this.doPublishChange(),t==null||t.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),t==null||t.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}})}publishByAddTrack(o){return _(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:s}){this._log.info("publish by addtrack");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack;if(this._peerConnection&&this._peerConnection.connectionState!=="new"){e&&a&&(yield this.addTrack(e)),n&&(yield this.addTrack(t));return}let c=new MediaStream;if(a&&c.addTrack(a),n&&c.addTrack(n),a&&this._peerConnection.addTrack(a,c),n&&(this._peerConnection.addTrack(n,c),s)){let d=new MediaStream;d.addTrack(s),this._peerConnection.addTrack(s,d)}yield this.connect()})}enableSmall(e){return _(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(z.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(z.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(s){return _(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!Lt()){if(e&&e.outMediaTrack&&!t&&this.localMainVideoTrack){yield this.removeTrack(e),this.localMainAudioTrack=null;return}if(t&&t.outMediaTrack&&!e&&this.localMainAudioTrack){yield this.removeTrack(t),this.localMainVideoTrack=null;return}yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),this.emitConnectionStateChangedEvent("DISCONNECTED",t);return}let o=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localAuxAudioTrack&&!this.localMainAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=P(N({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=P(N({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(z.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 _(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},s=yield this._signalChannel.sendWaitForResponse({command:q.PUBLISH_STATE_CHANGE,data:t,responseCommand:V.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(s.data.code,s.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:q.UNPUBLISH,commandDesc:"unpublish",responseCommand:V.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===A.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let s=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:o,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:o=this._publishingLocalVideoTrack),xt){if(s&&s.outMediaTrack){let a=s.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=s.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=o.profile.bitrate*1e3,o.small&&(this._mediaSettings.smallVideoWidth=o.small.width,this._mediaSettings.smallVideoHeight=o.small.height,this._mediaSettings.smallVideoFps=o.small.frameRate,this._mediaSettings.smallVideoBps=o.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else s&&s.outMediaTrack&&(this._mediaSettings.audioChannel=s.profile.channelCount,this._mediaSettings.audioBps=s.profile.bitrate*1e3,this._mediaSettings.audioFs=s.profile.sampleRate),o&&o.outMediaTrack&&(this._mediaSettings.videoWidth=o.profile.width,this._mediaSettings.videoHeight=o.profile.height,this._mediaSettings.videoFps=o.profile.frameRate,this._mediaSettings.videoBps=o.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:q.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:V.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return _(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?h.AUXILIARY:h.MAIN} stream`),tt()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return _(this,null,function*(){var o;if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield s[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)==null?void 0:o.small)&&(yield s[2].sender.replaceTrack(this._room.videoManager.smallTrack)),s[n].direction===z.INACTIVE&&(yield this.setTransceiverDirection(z.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return _(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;Lt()&&this._peerConnection.getTransceivers().findIndex(o=>o.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let s=this._peerConnection.getSenders().find(o=>o.track&&o.track.kind===t.kind);if(s&&s.track){this._log.warn("sender already exists, remove sender first");let o=s.track;this.removeSender(s),yield this.updateOffer("remove",o)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===h.VIDEO&&e instanceof le&&e.small){let o=new MediaStream,{smallTrack:n}=this._room.videoManager;o.addTrack(n),this._peerConnection.addTrack(n,o)}yield this.updateOffer("add",t)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===dr||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=ce(e);for(let s=0;s<t.media.length;s++)if(Number(t.media[s].mid)===0&&t.media[s].type===h.VIDEO)return!0;return!1}removeSender(e){let t=null;Lt()&&(t=this._peerConnection.getTransceivers().find(s=>s.sender&&s.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&W(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return _(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?h.AUXILIARY:h.MAIN} stream`),tt()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return _(this,null,function*(){if(!e.outMediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(null);else{let o=t?3:1;yield s[o].sender.replaceTrack(null),o===1&&e.small&&(yield s[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(z.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return _(this,null,function*(){if(!ie)return;let s=!1,o=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let n=this._peerConnection.getTransceivers();if(t.forEach(d=>{n[d].direction!==e&&(n[d].direction=e,s=!0)}),s){this._log.info("updating offer");let d=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(d)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
|
|
71
|
-
`).map(d=>{if(d.match(new RegExp(`a=(${
|
|
72
|
-
`);o&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:c}))})}removeTrackBySender(e){return _(this,null,function*(){if(!e.outMediaTrack)return;if(e.kind===h.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack){this.reset(),this.initialize(),yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1});return}let t=this._peerConnection.getSenders().find(s=>s.track===e.outMediaTrack);t&&(this.removeSender(t),e.kind===h.VIDEO&&e.small&&this._peerConnection.getSenders().forEach(s=>{s.track&&s.track.kind===h.VIDEO&&this.removeSender(s)})),yield this.updateOffer("remove",e.outMediaTrack)})}replaceTrack(e){return _(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders();if(!t||t.length===0||!e.mediaTrack)return!1;let s;if(tt()?s=e.kind===h.AUDIO?t[0]:t[1]:s=t.find(a=>a.track&&a.track.kind===e.kind),!s)return!1;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${e.kind} track on ${o?h.AUXILIARY:h.MAIN} stream`),e.kind===h.AUDIO?yield s.replaceTrack(e.outMediaTrack):e.kind===h.VIDEO&&(o?t[3]&&(yield t[3].replaceTrack(e.outMediaTrack)):yield s.replaceTrack(e.outMediaTrack)),!0})}updateOffer(e,t){return _(this,null,function*(){try{let s=yield this._peerConnection.createOffer(ah);ie&&s.sdp&&(s.sdp=this.setSDPDirection(s.sdp,"sendrecv")),yield this._peerConnection.setLocalDescription(s);let o=this.updateMediaSettings(),n={action:e,trackId:t.id,kind:t.kind===h.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:o,state:this.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug(`updatedOffer: ${n.sdp}`);let a=yield this._signalChannel.sendWaitForResponse({command:
|
|
70
|
+
`)}addSPSDescription(e){let t=ce(e);return t.media.forEach(s=>{s.type===h.VIDEO&&s.fmtp.forEach(o=>{o.config+=";sps-pps-idr-in-keyframe=1"})}),He(t)}removeSDESDescription(e){let t=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],s=ce(e);return s.media.forEach(o=>{!o.ext||(o.ext=o.ext.filter(n=>!t.includes(n.uri)))}),He(s)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return _(this,null,function*(){var s,o;try{if((((s=this._peerConnection)==null?void 0:s.connectionState)===se.NEW||((o=this._peerConnection)==null?void 0:o.connectionState)===se.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e)){this._peerConnection||(this.initialize(),yield this.connect(e));return}if(this._log.info(`subscribe ${t} ${JSON.stringify(e)}`),this._peerConnection||this._isSDPExchanging){let 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 b({code:A.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}unsubscribe(s){return _(this,arguments,function*({remoteTracks:e,streamType:t}){if(this._currentState==="CONNECTED"&&(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed)){this._log.info(`${t} stream already unsubscribed`);return}let o=N({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(a=>a===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${ea(o)}]`),yield this.sendSubscription(n,o),n==="unsubscribe"&&(this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,t=this.subscribeState){let s={srcTinyId:this.tinyId,srcUserId:this.userId},o=j.UNSUBSCRIBE,n=V.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(s={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=j.SUBSCRIBE_CHANGE,n=V.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:o,data:s,responseCommand:n,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new b({code:a.code,message:L({key:M.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}connect(){return _(this,arguments,function*(e=this.subscribeState){try{yield this.exchangeSDP(e),yield this.waitForPeerConnectionConnected()}catch(t){throw this.closePeerConnection(!0),t}})}exchangeSDP(e){return _(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:s}=this._peerConnection.localDescription,o={type:t,sdp:s,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:j.SUBSCRIBE,commandDesc:"exchange sdp",data:o,responseCommand:V.SUBSCRIBE_RESULT,timeout:Aa});if(!this._peerConnection){let a=new b({code:A.INVALID_OPERATION,message:L({key:M.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return _(this,null,function*(){let e={voiceActivityDetection:!1};tt()&&this._sdpSemantics===fi?(this._peerConnection.addTransceiver(h.AUDIO,{direction:Q.RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:Q.RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:Q.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:s}=yield on();s||(this._log.warn("remove h264 desc from sdp"),t.sdp=oh(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=sh(t.sdp),this._sdpSemantics===fi&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this._peerConnection.setLocalDescription(t)})}onSubscribeResult(e){return _(this,null,function*(){let{code:t,message:s=""}=e&&e.data||{},{type:o,sdp:n}=e&&e.data&&e.data.data||{};if(t===Vi)throw new b({code:A.NOT_SUPPORTED_H264,message:L({key:M.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new b({code:t,message:L({key:M.EXCHANGE_SDP_FAILED,data:{errMsg:s}})});this._log.debug(`accept remote answer: ${n}`),yield this._peerConnection.setRemoteDescription({type:o,sdp:n}),this.updateSSRC(n)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{ce(e).media.forEach(s=>{if(!!s.ssrcs)if(s.type===h.AUDIO){let o=s.ssrcs.find(n=>{var a;return(a=n.value)==null?void 0:a.includes(as)});o&&(this.ssrc.audio=Number(o.id))}else{let o=s.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(as)}),n=s.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(Ea)});o&&(this.ssrc.video=Number(o.id)),n&&(this.ssrc.auxiliary=Number(n.id))}})}catch(t){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return _(this,null,function*(){if(!(Ie(Dd.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(t){let s=Lt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${s/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},s)}})}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}},no=Dd;y([W(r=>function(...i){return new Promise((e,t)=>{let s=o=>{this._emitter.off("closed",s),t(new b({code:A.API_CALL_ABORTED,message:L({key:M.CONNECTION_ABORTED,data:o})}))};this._emitter.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this._emitter.off("closed",s)})})})],no.prototype,"subscribe",1),y([Tt(Ke.prototype.afterConnect),An(Ke.prototype.beforeConnect)],no.prototype,"connect",1);var vd=no;var ah={voiceActivityDetection:!1},Od=class extends Ke{constructor(e){super(P(N({},e),{isUplink:!0}));l(this,"localMainAudioTrack",null);l(this,"localMainVideoTrack",null);l(this,"localAuxAudioTrack",null);l(this,"localAuxVideoTrack",null);l(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});l(this,"_isPublishingAux",!1);l(this,"_publishingLocalAudioTrack");l(this,"_publishingLocalVideoTrack");l(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});l(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,s,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(xt()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((s=a[1])!=null&&s.track),e.smallVideo=!!((o=a[2])!=null&&o.track),e.auxVideo=!!((n=a[3])!=null&&n.track)):a.forEach(c=>{c.track&&(c.track.kind===h.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var n,a,c;let s=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:s,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:s,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:s,state:e}))),o}publish(o){return _(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:s}){this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),t&&(this._publishingLocalVideoTrack=t),this._isPublishingAux=s;let n;t&&!s&&t.small&&(n=this._room.videoManager.smallTrack),this.sendMediaSettings(),tt()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:s}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:n}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,s?(t&&(this.localAuxVideoTrack=t),e&&(this.localAuxAudioTrack=e)):(t&&(this.localMainVideoTrack=t),e&&(this.localMainAudioTrack=e)),this.installTrackMuteEvents(e,t),this.sendMutedFlag()})}publishByTransceiver(n){return _(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:s,isAuxiliary:o}){this._log.info("publish by transceiver");let a=new MediaStream,c=t==null?void 0:t.outMediaTrack,d=e==null?void 0:e.outMediaTrack;d&&a.addTrack(d),c&&a.addTrack(c);let u=this._peerConnection.getTransceivers();if(u.length===0)this._peerConnection.addTransceiver(d||h.AUDIO,{direction:Q.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?h.VIDEO:c||h.VIDEO,{direction:Q.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s||h.VIDEO,{direction:Q.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?c||h.VIDEO:h.VIDEO,{direction:Q.SENDONLY,streams:[a]}),yield this.connect();else{let p=[];if(d&&(u[0].sender.track||p.push(0),yield u[0].sender.replaceTrack(d),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:h.AUDIO})),c){let m=o?3:1;yield u[m].sender.replaceTrack(c),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:h.VIDEO,videoType:o?h.AUXILIARY:h.BIG}),p.push(m),s&&(yield u[2].sender.replaceTrack(s),yield this.setBandwidth({bandwidth:t.small.bitrate,type:h.VIDEO,videoType:h.SMALL}),p.push(2))}yield this.setTransceiverDirection(Q.SENDONLY,p),yield this.doPublishChange(),t==null||t.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),t==null||t.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}})}publishByAddTrack(o){return _(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:s}){this._log.info("publish by addtrack");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack;if(this._peerConnection&&this._peerConnection.connectionState!=="new"){e&&a&&(yield this.addTrack(e)),n&&(yield this.addTrack(t));return}let c=new MediaStream;if(a&&c.addTrack(a),n&&c.addTrack(n),a&&this._peerConnection.addTrack(a,c),n&&(this._peerConnection.addTrack(n,c),s)){let d=new MediaStream;d.addTrack(s),this._peerConnection.addTrack(s,d)}yield this.connect()})}enableSmall(e){return _(this,null,function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(Q.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(Q.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(s){return _(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!xt()){if(e&&e.outMediaTrack&&!t&&this.localMainVideoTrack){yield this.removeTrack(e),this.localMainAudioTrack=null;return}if(t&&t.outMediaTrack&&!e&&this.localMainAudioTrack){yield this.removeTrack(t),this.localMainVideoTrack=null;return}yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),this.emitConnectionStateChangedEvent("DISCONNECTED",t);return}let o=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localAuxAudioTrack&&!this.localMainAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=P(N({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=P(N({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(Q.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return _(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},s=yield this._signalChannel.sendWaitForResponse({command:j.PUBLISH_STATE_CHANGE,data:t,responseCommand:V.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(s.data.code,s.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:j.UNPUBLISH,commandDesc:"unpublish",responseCommand:V.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===A.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let s=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:o,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:o=this._publishingLocalVideoTrack),Pt){if(s&&s.outMediaTrack){let a=s.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=s.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=o.profile.bitrate*1e3,o.small&&(this._mediaSettings.smallVideoWidth=o.small.width,this._mediaSettings.smallVideoHeight=o.small.height,this._mediaSettings.smallVideoFps=o.small.frameRate,this._mediaSettings.smallVideoBps=o.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else s&&s.outMediaTrack&&(this._mediaSettings.audioChannel=s.profile.channelCount,this._mediaSettings.audioBps=s.profile.bitrate*1e3,this._mediaSettings.audioFs=s.profile.sampleRate),o&&o.outMediaTrack&&(this._mediaSettings.videoWidth=o.profile.width,this._mediaSettings.videoHeight=o.profile.height,this._mediaSettings.videoFps=o.profile.frameRate,this._mediaSettings.videoBps=o.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:j.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:V.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return _(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?h.AUXILIARY:h.MAIN} stream`),tt()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return _(this,null,function*(){var o;if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield s[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)==null?void 0:o.small)&&(yield s[2].sender.replaceTrack(this._room.videoManager.smallTrack)),s[n].direction===Q.INACTIVE&&(yield this.setTransceiverDirection(Q.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return _(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;xt()&&this._peerConnection.getTransceivers().findIndex(o=>o.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let s=this._peerConnection.getSenders().find(o=>o.track&&o.track.kind===t.kind);if(s&&s.track){this._log.warn("sender already exists, remove sender first");let o=s.track;this.removeSender(s),yield this.updateOffer("remove",o)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===h.VIDEO&&e instanceof ue&&e.small){let o=new MediaStream,{smallTrack:n}=this._room.videoManager;o.addTrack(n),this._peerConnection.addTrack(n,o)}yield this.updateOffer("add",t)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===ur||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=ce(e);for(let s=0;s<t.media.length;s++)if(Number(t.media[s].mid)===0&&t.media[s].type===h.VIDEO)return!0;return!1}removeSender(e){let t=null;xt()&&(t=this._peerConnection.getTransceivers().find(s=>s.sender&&s.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&K(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return _(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?h.AUXILIARY:h.MAIN} stream`),tt()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return _(this,null,function*(){if(!e.outMediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(null);else{let o=t?3:1;yield s[o].sender.replaceTrack(null),o===1&&e.small&&(yield s[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(Q.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return _(this,null,function*(){if(!ie)return;let s=!1,o=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let n=this._peerConnection.getTransceivers();if(t.forEach(d=>{n[d].direction!==e&&(n[d].direction=e,s=!0)}),s){this._log.info("updating offer");let d=yield this._peerConnection.createOffer();yield this._peerConnection.setLocalDescription(d)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
|
|
71
|
+
`).map(d=>{if(d.match(new RegExp(`a=(${Q.INACTIVE}|${Q.RECVONLY}|${Q.SENDONLY})`))&&a++,t.includes(a)){if(e===Q.INACTIVE&&d.includes(`a=${Q.RECVONLY}`))return o=!0,`a=${e}`;if(e===Q.SENDONLY&&d.includes(`a=${Q.INACTIVE}`))return o=!0,`a=${Q.RECVONLY}`}return d}).join(`\r
|
|
72
|
+
`);o&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:c}))})}removeTrackBySender(e){return _(this,null,function*(){if(!e.outMediaTrack)return;if(e.kind===h.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack){this.reset(),this.initialize(),yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1});return}let t=this._peerConnection.getSenders().find(s=>s.track===e.outMediaTrack);t&&(this.removeSender(t),e.kind===h.VIDEO&&e.small&&this._peerConnection.getSenders().forEach(s=>{s.track&&s.track.kind===h.VIDEO&&this.removeSender(s)})),yield this.updateOffer("remove",e.outMediaTrack)})}replaceTrack(e){return _(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders();if(!t||t.length===0||!e.mediaTrack)return!1;let s;if(tt()?s=e.kind===h.AUDIO?t[0]:t[1]:s=t.find(a=>a.track&&a.track.kind===e.kind),!s)return!1;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${e.kind} track on ${o?h.AUXILIARY:h.MAIN} stream`),e.kind===h.AUDIO?yield s.replaceTrack(e.outMediaTrack):e.kind===h.VIDEO&&(o?t[3]&&(yield t[3].replaceTrack(e.outMediaTrack)):yield s.replaceTrack(e.outMediaTrack)),!0})}updateOffer(e,t){return _(this,null,function*(){try{let s=yield this._peerConnection.createOffer(ah);ie&&s.sdp&&(s.sdp=this.setSDPDirection(s.sdp,"sendrecv")),yield this._peerConnection.setLocalDescription(s);let o=this.updateMediaSettings(),n={action:e,trackId:t.id,kind:t.kind===h.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:o,state:this.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug(`updatedOffer: ${n.sdp}`);let a=yield this._signalChannel.sendWaitForResponse({command:j.PUBLISH_CHANGE,data:n,responseCommand:V.UPDATE_OFFER_RESULT,timeout:Ia,commandDesc:"update offer"}),{code:c,message:d}=a.data;c!==0&&this.checkPublishResultCode(c,d),yield this.acceptAnswer(a.data.data),s.sdp&&this.updateSSRC(s.sdp)}catch(s){throw this._log.error(s),s}})}setBandwidth(n){return _(this,arguments,function*({bandwidth:e,type:t,videoType:s,sdp:o}){if(!ws())return o?t===h.VIDEO?this.updateVideoBandwidthRestriction(o,e,s):this.updateAudioBandwidthRestriction(o,e):void 0;let a,c=this._peerConnection.getSenders();if(tt()){let d=0;t===h.VIDEO&&(s===h.SMALL?d=2:s===h.AUXILIARY?d=3:d=1),a=c[d]}else a=c.find(d=>d.track&&d.track.kind===t);if(a){let d=a.getParameters();(!d.encodings||d.encodings.length===0)&&(d.encodings=[{}]),d.encodings[0].maxBitrate=e*1e3;try{return yield a.setParameters(d),this._log.info(`${s||""}${t} bandwidth ${e} kbps`),o}catch(u){if(this._log.info(`failed to set bandwidth by setting maxBitrate: ${u}`),o)return t===h.VIDEO?this.updateVideoBandwidthRestriction(o,e,s):this.updateAudioBandwidthRestriction(o,e)}}return o})}updateVideoBandwidthRestriction(e,t,s){let o="AS";ie&&(o="TIAS",t=t*1e3);let n=0,a=-1;return s===h.SMALL?n=1:s===h.AUXILIARY&&(n=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,c=>(a+=1,a===n?`${c}b=${o}:${t}\r
|
|
73
73
|
`:c)),e}updateAudioBandwidthRestriction(e,t){let s="AS";return ie&&(s="TIAS",t=t*1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,`m=audio $1\r
|
|
74
74
|
c=IN $2\r
|
|
75
75
|
b=${s}:${t}\r
|
|
76
|
-
`),e}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return _(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(e){throw this.closePeerConnection(!0),this.uninstallEvents(),e}})}exchangeSDP(){return _(this,null,function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(e){throw e}})}createOffer(){return _(this,null,function*(){try{let e=yield this._peerConnection.createOffer(ah);yield this._peerConnection.setLocalDescription(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:q.PUBLISH,responseCommand:V.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof ze||this.localAuxVideoTrack instanceof ze,state:this.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug(`sending sdp offer: ${e.data.sdp}`),this._signalChannel.sendWaitForResponse(e).then(t=>{let{code:s,message:o,data:n}=t.data;return s===0?this.acceptAnswer(n):this.checkPublishResultCode(s,o)})}setSDPDirection(e,t,s="all"){let o=ce(e);return o.media.forEach(n=>{(s==="all"||n.type===s)&&(n.direction=t)}),He(o)}acceptAnswer(e){return _(this,null,function*(){var t,s,o,n,a;try{let c;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let p=((t=this._publishingLocalVideoTrack)==null?void 0:t.profile.bitrate)||((s=this.localMainVideoTrack)==null?void 0:s.profile.bitrate),m=((o=this._publishingLocalAudioTrack)==null?void 0:o.profile.bitrate)||((n=this.localMainAudioTrack)==null?void 0:n.profile.bitrate);if(p){let f=this._isPublishingAux?h.AUXILIARY:h.BIG;c=yield this.setBandwidth({bandwidth:p,type:h.VIDEO,sdp:c,videoType:f})}m&&(c=yield this.setBandwidth({bandwidth:m,type:h.AUDIO,sdp:c}))}if(c=this.removeVideoOrientation(e.sdp),(a=this._publishingLocalVideoTrack)!=null&&a.small){let{smallStreamConfig:p}=this._room;c=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||p.bitrate,type:h.VIDEO,videoType:h.SMALL,sdp:c})}let l={type:e.type,sdp:c};yield this._peerConnection.setRemoteDescription(l),this._log.debug(`accepted answer: ${c}`)}catch(c){throw this._log.error(`failed to accept remote answer ${c}`),c}})}sendMutedFlag(e){var o,n,a;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let s={audio:!!((o=this.localMainAudioTrack)!=null&&o.muted),bigVideo:!!((n=this.localMainVideoTrack)!=null&&n.muted),auxVideo:!!((a=this.localAuxVideoTrack)!=null&&a.muted)};this._log.info(`send muted state: ${JSON.stringify(s)}`),this._signalChannel.send(q.UPDATE_MUTE_STAT,s)}getIsReconnecting(){return this._isReconnecting}reconnect(){return _(this,null,function*(){if(!(Ie(vd.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:q.UNPUBLISH,responseCommand:V.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch(t){let s=kt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${s/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},s)}})}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&g.emit(E.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{ce(e).media.forEach((s,o)=>{if(s.type===h.AUDIO){let n=s.ssrcs&&s.ssrcs[0];n&&(this.ssrc.audio=Number(n.id))}else{if(this._sdpSemantics===dr&&s.ssrcGroups){s.ssrcGroups.forEach((a,c)=>{let d=Number(a.ssrcs.split(" ")[0]);c===0?this.ssrc.video=d:c===1&&(this.ssrc.small=d)});return}let n=s.ssrcs&&s.ssrcs[0];if(!n)return;switch(o){case 1:this.ssrc.video=Number(n.id);break;case 2:this.ssrc.small=Number(n.id);break;case 3:this.ssrc.auxiliary=Number(n.id);break;default:break}}})}catch(t){}}getVideoTrackId(e=h.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===h.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===h.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===h.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===h.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Pi?(this._log.error(Ae.NOT_SUPPORTED_H264ENCODE),new b({code:A.NOT_SUPPORTED_H264,message:L({key:M.NOT_SUPPORTED_H264ENCODE})})):new b({code:A.UNKNOWN,message:L({key:M.SIGNAL_RESPONSE_FAILED,data:{signalResponse:V.PUBLISH_RESULT,code:e,message:t}})})}},no=vd;y([J(r=>function(...i){return new Promise((e,t)=>{let s=o=>{this._emitter.off("closed",s),t(new b({code:A.API_CALL_ABORTED,message:L({key:M.CONNECTION_ABORTED,data:o})}))};this._emitter.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this._emitter.off("closed",s)})})})],no.prototype,"publish",1),y([gt(Ke.prototype.afterConnect),In(Ke.prototype.beforeConnect)],no.prototype,"connect",1);var ao=no;var co=class{constructor(i,e){this.room=i;u(this,"_log");u(this,"_prevReportTime",0);u(this,"_prevReport",{});u(this,"_prevStats",null);u(this,"_prevEncoderImplementation","");u(this,"_prevAuxEncoderImpl","");u(this,"_prevQualityLimitationReason","");u(this,"_prevAuxQualityLimitationReason","");u(this,"_prevDecoderImplementationMap",new Map);u(this,"totalBytesSent",0);u(this,"totalBytesReceived",0);u(this,"_spcStats",null);this._log=e}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(i){return _(this,null,function*(){let e={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},t=i.getPeerConnection(),s=i.getSSRC();if(t)try{if((this._spcStats||(yield t.getStats())).forEach(n=>{var d,l,p;let a,c;if(n.type==="outbound-rtp")if((n.mediaType||n.kind)===h.VIDEO){if(n.ssrc===s.video?(a=h.VIDEO,c=i.localMainVideoTrack):n.ssrc===s.small?a=h.SMALL:n.ssrc===s.auxiliary&&(c=i.localAuxVideoTrack,a=h.AUXILIARY),!a)return;if(e[a].bytesSent=n.bytesSent,e[a].packetsSent=n.packetsSent,e[a].framesEncoded=n.framesEncoded,T(n.keyFramesEncoded)||(e[a].keyFramesEncoded=n.keyFramesEncoded),T(n.nackCount)||(e[a].nackCount=n.nackCount),T(n.pliCount)||(e[a].pliCount=n.pliCount),T(n.retransmittedPacketsSent)||(e[a].retransmittedPacketsSent=n.retransmittedPacketsSent),T(n.totalEncodeTime)||(e[a].totalEncodeTime=n.totalEncodeTime),T(n.totalPacketSendDelay)||(e[a].totalPacketSendDelay=n.totalPacketSendDelay),!T(n.encoderImplementation)&&(a===h.VIDEO&&this._prevEncoderImplementation!==n.encoderImplementation||a===h.AUXILIARY&&this._prevAuxEncoderImpl!==n.encoderImplementation)){let f=2,R=this._prevEncoderImplementation;a===h.AUXILIARY&&(f=7,R=this._prevAuxEncoderImpl),g.emit("262",{userId:i.userId,streamType:f,prevImplementation:R,implementation:n.encoderImplementation,codec:i.videoCodec,isHWCodec:n.powerEfficientEncoder}),this[a===h.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=n.encoderImplementation,this._log.info(`${a===h.AUXILIARY?"aux ":""}encoderImplementation change to ${n.encoderImplementation}(${i.videoCodec}) HWEncoder: ${n.powerEfficientEncoder}`)}n.ssrc===s.video?!T(n.qualityLimitationReason)&&n.bytesSent!==0&&this._prevQualityLimitationReason!==n.qualityLimitationReason&&(this._log.info(`qualityLimitationReason change to ${n.qualityLimitationReason}`),g.emit("263",{userId:i.userId,reason:n.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:(d=i.localMainVideoTrack)==null?void 0:d.isQosClearFirst}),this._prevQualityLimitationReason=n.qualityLimitationReason):n.ssrc===s.auxiliary&&!T(n.qualityLimitationReason)&&n.bytesSent!==0&&this._prevAuxQualityLimitationReason!==n.qualityLimitationReason&&(this._log.info(`aux qualityLimitationReason change to ${n.qualityLimitationReason}`),g.emit("263",{userId:i.userId,reason:n.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:(l=i.localAuxVideoTrack)==null?void 0:l.isQosClearFirst}),this._prevAuxQualityLimitationReason=n.qualityLimitationReason)}else e.audio.bytesSent=n.bytesSent,e.audio.packetsSent=n.packetsSent;else n.type==="candidate-pair"?Ci(n)&&ee(n.currentRoundTripTime)&&(e.rtt=Math.floor(n.currentRoundTripTime*1e3),this.totalBytesSent=n.bytesSent):n.type==="media-source"&&(n.kind===h.AUDIO?(e.audio.audioLevel=n.audioLevel||0,e.audio.totalAudioEnergy=n.totalAudioEnergy||0,n.echoReturnLoss,n.totalSamplesDuration&&(e.audio.totalSamplesDuration=n.totalSamplesDuration)):n.kind===h.VIDEO&&(n.trackIdentifier===i.getVideoTrackId(h.VIDEO)?e.video.fpsCapture=n.framesPerSecond:n.trackIdentifier===i.getVideoTrackId(h.AUXILIARY)?e.auxiliary.fpsCapture=n.framesPerSecond:e.small.fpsCapture=n.framesPerSecond));if(!T(n.audioLevel)&&((p=i.localMainAudioTrack)==null?void 0:p.mediaTrack)&&n.trackIdentifier===i.localMainAudioTrack.mediaTrack.id&&(e.audio.audioLevel=n.audioLevel||0),!T(n.frameWidth)){let m=h.SMALL;n.trackIdentifier===i.getVideoTrackId(h.VIDEO)||n.ssrc===s.video?m=h.VIDEO:(n.trackIdentifier===i.getVideoTrackId(h.AUXILIARY)||n.ssrc===s.auxiliary)&&(m=h.AUXILIARY),e[m].frameWidth=n.frameWidth,e[m].frameHeight=n.frameHeight,e[m].framesSent=n.framesSent}}),i.localMainAudioTrack){let n=i.localMainAudioTrack.getInternalAudioLevel();e.audio.micAudioLevel=n,e.audio.audioLevel===0&&(e.audio.audioLevel=n)}this.totalBytesSent||(this.totalBytesSent+=e.audio.bytesSent+e.video.bytesSent+e.auxiliary.bytesSent),Object.keys(e).forEach(n=>{n===h.AUDIO?i.localMainAudioTrack&&(i.localMainAudioTrack.stat=e[n]):n===h.VIDEO?i.localMainVideoTrack&&(i.localMainVideoTrack.stat=e[n]):n===h.AUXILIARY&&i.localAuxVideoTrack&&(i.localAuxVideoTrack.stat=e[n])})}catch(o){this._log.warn(`failed to getStats on sender connection ${o}`)}return e})}getReceiverStats(i){return _(this,null,function*(){let e={tinyId:i.tinyId,userId:i.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0}},t=i.getPeerConnection();if(t)try{let{ssrc:s}=i,{muteState:o,subscribeState:n}=i;(this._spcStats||(yield t.getStats())).forEach(c=>{if(c.type==="inbound-rtp"){let d=(c.mediaType||c.kind)===h.AUDIO;if(d){if(c.ssrc!==s.audio||!o.hasAudio)return;e.audio.packetsReceived=c.packetsReceived,e.audio.bytesReceived=c.bytesReceived,e.audio.packetsLost=c.packetsLost,c.insertedSamplesForDeceleration&&(e.audio.insertedSamplesForDeceleration=c.insertedSamplesForDeceleration),c.removedSamplesForAcceleration&&(e.audio.removedSamplesForAcceleration=c.removedSamplesForAcceleration),c.totalSamplesDuration&&(e.audio.totalSamplesDuration=c.totalSamplesDuration),c.totalSamplesReceived&&(e.audio.totalSamplesReceived=c.totalSamplesReceived),c.concealedSamples&&(e.audio.concealedSamples=c.concealedSamples);let{remoteAudioTrack:l}=i;l.stat.packetsReceived=c.packetsReceived,l.stat.bytesReceived=c.bytesReceived,l.stat.packetsLost=c.packetsLost,e.audio.p2pDelay=l.stat.end2EndDelay,e.hasAudio=!0}else{if(ie&&c.bytesReceived===0)return;let l;c.ssrc===s.video&&o.hasVideo&&(e.video.packetsReceived=c.packetsReceived,e.video.bytesReceived=c.bytesReceived,e.video.packetsLost=c.packetsLost,e.video.framesReceived=c.framesReceived,e.video.framesDecoded=c.framesDecoded,e.video.fpsDecoded=c.framesPerSecond,e.hasVideo=!0,l=i.remoteVideoTrack,o.hasSmall&&n.smallVideo&&(e.isSmallSubscribed=!0),c.decoderImplementation&&(!this._prevDecoderImplementationMap.has(e.userId)||this._prevDecoderImplementationMap.get(e.userId)!==c.decoderImplementation)&&(this._log.info(`${e.userId} decoderImplementation change to ${c.decoderImplementation} HWDecoder: ${c.powerEfficientDecoder}`),g.emit("262",{userId:this.room.userId,remoteUserId:e.userId,prevImplementation:this._prevDecoderImplementationMap.get(e.userId),implementation:c.decoderImplementation,codec:i.videoCodec,isHWCodec:c.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(e.userId,c.decoderImplementation))),c.ssrc===s.auxiliary&&o.hasAuxiliary&&(e.auxiliary.packetsReceived=c.packetsReceived,e.auxiliary.bytesReceived=c.bytesReceived,e.auxiliary.packetsLost=c.packetsLost,e.auxiliary.framesReceived=c.framesReceived,e.auxiliary.framesDecoded=c.framesDecoded,e.auxiliary.fpsDecoded=c.framesPerSecond,l=i.remoteAuxiliaryTrack,e.hasAuxiliary=!0),l&&(l.stat.packetsReceived=c.packetsReceived,l.stat.bytesReceived=c.bytesReceived,l.stat.packetsLost=c.packetsLost,l.stat.framesReceived=c.framesReceived,l.stat.framesDecoded=c.framesDecoded,c.jitterBufferDelay&&(l.stat.jitterBufferDelay=Math.floor(c.jitterBufferDelay/c.jitterBufferEmittedCount*1e3)))}c.jitterBufferDelay&&(d?(e.audio.totalJitter=c.jitterBufferDelay,e.audio.totalJitterCount=c.jitterBufferEmittedCount):c.ssrc===s.video&&o.hasVideo?(e.video.totalJitter=c.jitterBufferDelay,e.video.totalJitterCount=c.jitterBufferEmittedCount):c.ssrc===s.auxiliary&&o.hasAuxiliary&&(e.auxiliary.totalJitter=c.jitterBufferDelay,e.auxiliary.totalJitterCount=c.jitterBufferEmittedCount))}else c.type==="candidate-pair"&&Ci(c)&&ee(c.currentRoundTripTime)&&(e.rtt=Math.floor(c.currentRoundTripTime*1e3),this.totalBytesReceived=c.bytesReceived);T(c.frameWidth)||((c.trackIdentifier===i.getMainStreamVideoTrackId()||c.ssrc===s.video)&&(e.video.frameWidth=c.frameWidth,e.video.frameHeight=c.frameHeight,i.remoteVideoTrack.stat.frameWidth=c.frameWidth,i.remoteVideoTrack.stat.frameHeight=c.frameHeight),(c.trackIdentifier===i.getAuxStreamVideoTrackId()||c.ssrc===s.auxiliary)&&(e.auxiliary.frameWidth=c.frameWidth,e.auxiliary.frameHeight=c.frameHeight,i.remoteAuxiliaryTrack.stat.frameWidth=c.frameWidth,i.remoteAuxiliaryTrack.stat.frameHeight=c.frameHeight)),!T(c.audioLevel)&&i.muteState.audioAvailable&&i.remoteAudioTrack.mediaTrack&&c.trackIdentifier===i.remoteAudioTrack.mediaTrack.id&&(e.audio.audioLevel=c.audioLevel||0,e.audio.totalAudioEnergy=c.totalAudioEnergy||0)}),e.audio.audioLevel===0&&i.muteState.audioAvailable&&(e.audio.audioLevel=i.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=e.audio.bytesReceived+e.video.bytesReceived+e.auxiliary.bytesReceived)}catch(s){this._log.warn(`failed to getStats on receiver connection ${s}`)}return e})}getStats(i,e){return _(this,null,function*(){let t={},s=[];if(this.room.singlePC){let o=this.room.singlePC.getPeerConnection();if(!o)return{senderStats:t,receiverStats:s};let n=x(),a=yield o.getStats(),c=x();c-n>2e3&&this._log.warn(`getStats cost ${c-n}ms`);let d=[],l=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);a.forEach(p=>l.has(p.type)&&d.push(p)),this._spcStats=d}i&&(t=yield this.getSenderStats(i));for(let[o,n]of e){let a=yield this.getReceiverStats(n);s.push(a)}return{senderStats:t,receiverStats:s}})}getDifferenceValue(i,e){if(Bt(i))return e;let t=e-i;return t<0?0:t}prepareReport({stats:i,report:e,freezeMap:t}){var p;if(!Bt(i.senderStats)){let m={uint32_audio_level:i.senderStats.audio.audioLevel*ct,uint32_audio_energy:(i.senderStats.audio.totalAudioEnergy||0)*1e6,uint32_audio_codec_bitrate:i.senderStats.audio.bytesSent};i.senderStats.audio.micAudioLevel&&(m.uint32_mic_audio_level=i.senderStats.audio.micAudioLevel*ct),i.senderStats.audio.totalSamplesDuration&&(e.msg_device_info.uint32_audio_capture_cost=i.senderStats.audio.totalSamplesDuration);let f=[];if(i.senderStats.video.bytesSent){let C={uint32_video_stream_type:2,uint32_video_codec_fps:i.senderStats.video.framesSent,uint32_video_capture_fps:i.senderStats.video.fpsCapture,uint32_video_width:i.senderStats.video.frameWidth,uint32_video_height:i.senderStats.video.frameHeight,uint32_video_codec_bitrate:i.senderStats.video.bytesSent,uint32_video_enc_fps:i.senderStats.video.framesEncoded,uint32_key_frame_count:i.senderStats.video.keyFramesEncoded,uint32_nack_count:i.senderStats.video.nackCount,uint32_pli_count:i.senderStats.video.pliCount,uint32_encode_cost:(i.senderStats.video.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.video.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.video.retransmittedPacketsSent};f.push(C)}if(i.senderStats.small.bytesSent){let C={uint32_video_stream_type:3,uint32_video_codec_fps:i.senderStats.small.framesSent||0,uint32_video_capture_fps:i.senderStats.small.fpsCapture||0,uint32_video_width:i.senderStats.small.frameWidth||0,uint32_video_height:i.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:i.senderStats.small.bytesSent,uint32_video_enc_fps:i.senderStats.small.framesEncoded||0,uint32_key_frame_count:i.senderStats.small.keyFramesEncoded,uint32_nack_count:i.senderStats.small.nackCount,uint32_pli_count:i.senderStats.small.pliCount,uint32_encode_cost:(i.senderStats.small.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.small.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.small.retransmittedPacketsSent};f.push(C)}if(i.senderStats.auxiliary.bytesSent){let C={uint32_video_stream_type:7,uint32_video_codec_fps:i.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:i.senderStats.auxiliary.fpsCapture||0,uint32_video_width:i.senderStats.auxiliary.frameWidth||0,uint32_video_height:i.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:i.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:i.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:i.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:i.senderStats.auxiliary.nackCount,uint32_pli_count:i.senderStats.auxiliary.pliCount,uint32_encode_cost:(i.senderStats.auxiliary.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.auxiliary.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.auxiliary.retransmittedPacketsSent};f.push(C)}let R={uint32_bitrate:0,uint32_lost:0,uint32_rtt:i.senderStats.rtt};e.msg_up_stream_info={msg_audio_status:m,msg_video_status:f,msg_network_status:R}}let{statInterval:s}=this;e.msg_down_stream_info=[],i.receiverStats.forEach(m=>{let f={msg_user_info:{str_identifier:m.userId,uint64_tinyid:m.tinyId},msg_network_status:{uint32_rtt:m.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(m.hasAudio){let R={uint32_audio_p2p_delay:m.audio.p2pDelay,uint32_audio_cache_ms:m.audio.totalJitter,uint32_audio_cache_ms_count:m.audio.totalJitterCount,uint32_audio_codec_bitrate:m.audio.bytesReceived,uint32_audio_total_bitrate:m.audio.bytesReceived,uint32_audio_level:m.audio.audioLevel*1e8,uint32_audio_energy:m.audio.totalAudioEnergy*1e6,uint32_audio_receive:m.audio.packetsReceived,uint32_audio_origin_lost:m.audio.packetsLost};f.msg_audio_status=R}if(m.hasVideo){let R=t.get(`${m.userId}_${Ea}`),C=R?R.duration:0,v={uint32_video_stream_type:m.isSmallSubscribed?3:2,uint32_video_receive_fps:m.video.framesReceived,uint32_video_width:m.video.frameWidth,uint32_video_height:m.video.frameHeight,uint32_video_codec_bitrate:m.video.bytesReceived,uint32_video_receive:m.video.packetsReceived,uint32_video_origin_lost:m.video.packetsLost,uint32_video_block_time:C,uint32_video_dec_fps:m.video.framesDecoded,uint32_video_cache_ms:m.video.totalJitter,uint32_video_cache_ms_count:m.video.totalJitterCount};f.msg_video_status.push(v)}if(m.hasAuxiliary){let R=t.get(`${m.userId}_${ga}`),C=R?R.duration:0,v={uint32_video_stream_type:7,uint32_video_receive_fps:m.auxiliary.framesReceived,uint32_video_width:m.auxiliary.frameWidth,uint32_video_height:m.auxiliary.frameHeight,uint32_video_codec_bitrate:m.auxiliary.bytesReceived,uint32_video_receive:m.auxiliary.packetsReceived+m.auxiliary.packetsLost,uint32_video_origin_lost:m.auxiliary.packetsLost,uint32_video_block_time:C,uint32_video_dec_fps:m.auxiliary.framesDecoded,uint32_video_cache_ms:m.auxiliary.totalJitter,uint32_video_cache_ms_count:m.auxiliary.totalJitterCount};f.msg_video_status.push(v)}e.msg_down_stream_info.push(f)});let o=this._prevReport,n=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(e)),this._prevStats=JSON.parse(JSON.stringify(i)),e.msg_up_stream_info.msg_audio_status&&o.msg_up_stream_info.msg_audio_status){let m=o.msg_up_stream_info.msg_audio_status,f=e.msg_up_stream_info.msg_audio_status;if(m.uint32_audio_codec_bitrate===0)f.uint32_audio_codec_bitrate=0;else{let R=this.getDifferenceValue(m.uint32_audio_codec_bitrate,f.uint32_audio_codec_bitrate);f.uint32_audio_codec_bitrate=Math.round(R*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=f.uint32_audio_codec_bitrate}(p=o.msg_device_info)!=null&&p.uint32_audio_capture_cost?e.msg_device_info.uint32_audio_capture_cost=2*Math.floor(this.getDifferenceValue(o.msg_device_info.uint32_audio_capture_cost,e.msg_device_info.uint32_audio_capture_cost)*1e3/s):delete e.msg_device_info.uint32_audio_capture_cost}let a=o.msg_up_stream_info.msg_video_status;e.msg_up_stream_info.msg_video_status.forEach(m=>{let f=a.find(Ge=>Ge.uint32_video_stream_type===m.uint32_video_stream_type);if(!f||f.uint32_video_codec_bitrate===0){m.uint32_video_codec_bitrate=0,m.uint32_video_enc_fps=0,m.uint32_video_codec_fps=0;return}let R=0,C=0,v=0;f&&m.uint32_video_codec_bitrate>=f.uint32_video_codec_bitrate&&(R=f.uint32_video_codec_bitrate,C=f.uint32_video_enc_fps,v=f.uint32_video_codec_fps);let U=this.getDifferenceValue(R,m.uint32_video_codec_bitrate);m.uint32_video_codec_bitrate=Math.round(U*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=m.uint32_video_codec_bitrate,m.uint32_video_enc_fps=Math.round(this.getDifferenceValue(C,m.uint32_video_enc_fps)/s),m.uint32_video_codec_fps=Math.round(this.getDifferenceValue(v,m.uint32_video_codec_fps)/s),Ei&&Qt()===115&&f.uint32_video_width===0&&f.uint32_video_height===0&&f.uint32_video_codec_fps===0&&(m.uint32_video_codec_fps=m.uint32_video_enc_fps),T(f.uint32_key_frame_count)||(m.uint32_key_frame_count=Math.round(this.getDifferenceValue(f.uint32_key_frame_count,m.uint32_key_frame_count))),T(f.uint32_nack_count)||(m.uint32_nack_count=Math.round(this.getDifferenceValue(f.uint32_nack_count,m.uint32_nack_count))),T(f.uint32_pli_count)||(m.uint32_pli_count=Math.round(this.getDifferenceValue(f.uint32_pli_count,m.uint32_pli_count))),T(f.uint32_video_arq_packets)||(m.uint32_video_arq_packets=Math.round(this.getDifferenceValue(f.uint32_video_arq_packets,m.uint32_video_arq_packets))),T(f.uint32_encode_cost)||(m.uint32_encode_cost=Math.round(this.getDifferenceValue(f.uint32_encode_cost,m.uint32_encode_cost)/s)),T(f.uint32_send_packet_cost)||(m.uint32_send_packet_cost=Math.round(this.getDifferenceValue(f.uint32_send_packet_cost,m.uint32_send_packet_cost)/s))});let d=o.msg_down_stream_info;e.msg_down_stream_info=e.msg_down_stream_info.filter(m=>d.find(f=>f.msg_user_info.uint64_tinyid===m.msg_user_info.uint64_tinyid));let l=e.msg_down_stream_info;return l.forEach(m=>{let f=d.find(R=>R.msg_user_info.uint64_tinyid===m.msg_user_info.uint64_tinyid);if(!Bt(m.msg_audio_status)&&!Bt(f.msg_audio_status)){let R=m.msg_audio_status,C=f.msg_audio_status,v=this.getDifferenceValue(C.uint32_audio_cache_ms_count,R.uint32_audio_cache_ms_count);delete R.uint32_audio_cache_ms_count,R.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(C.uint32_audio_cache_ms,R.uint32_audio_cache_ms)/v)||0;let U=this.room.remotePublishedUserMap.get(m.msg_user_info.str_identifier);U&&(U.remoteAudioTrack.stat.jitterBufferDelay=R.uint32_audio_cache_ms),R.uint32_audio_origin_lost=this.getDifferenceValue(C.uint32_audio_origin_lost,R.uint32_audio_origin_lost),R.uint32_audio_receive=this.getDifferenceValue(C.uint32_audio_receive,R.uint32_audio_receive),R.uint32_audio_receive+=R.uint32_audio_origin_lost;let Ge=this.getDifferenceValue(C.uint32_audio_codec_bitrate,R.uint32_audio_codec_bitrate);R.uint32_audio_codec_bitrate=Math.round(Ge*8/s),R.uint32_audio_total_bitrate=Math.round(Ge*8/s)}else m.msg_audio_status={};if(m.msg_video_status&&f.msg_video_status){let R=f.msg_video_status;m.msg_video_status=m.msg_video_status.filter(v=>R.find(U=>U.uint32_video_stream_type===v.uint32_video_stream_type)),m.msg_video_status.forEach(v=>{let U=R.find(Uh=>Uh.uint32_video_stream_type===v.uint32_video_stream_type),Ge=U.uint32_video_receive,go=U.uint32_video_origin_lost,Lh=U.uint32_video_codec_bitrate,G=U.uint32_video_receive_fps,xh=U.uint32_video_dec_fps;v.uint32_video_origin_lost=this.getDifferenceValue(go,v.uint32_video_origin_lost),v.uint32_video_receive=this.getDifferenceValue(Ge,v.uint32_video_receive)+v.uint32_video_origin_lost;let Ph=this.getDifferenceValue(Lh,v.uint32_video_codec_bitrate);v.uint32_video_codec_bitrate=Math.round(Ph*8/s);let wh=this.getDifferenceValue(G,v.uint32_video_receive_fps);v.uint32_video_receive_fps=Math.round(wh/s),v.uint32_video_dec_fps=Math.round(this.getDifferenceValue(xh,v.uint32_video_dec_fps)/s);let Vh=this.getDifferenceValue(U.uint32_video_cache_ms_count,v.uint32_video_cache_ms_count);delete v.uint32_video_cache_ms_count,v.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(U.uint32_video_cache_ms,v.uint32_video_cache_ms)/Vh)||0})}}),n&&i.receiverStats.forEach(m=>{if(m.audio.concealedSamples&&m.audio.totalSamplesReceived){let f=n.receiverStats.find(R=>R.userId===m.userId);if(f&&f.audio.concealedSamples&&f.audio.totalSamplesReceived){let R=m.audio.concealedSamples-f.audio.concealedSamples,C=m.audio.totalSamplesReceived-f.audio.totalSamplesReceived,v=Math.floor(R/C*1e3*s);if(v>s/5){let U=l.find(Ge=>Ge.msg_user_info.str_identifier===m.userId);U&&(U.msg_audio_status.uint32_audio_block_time=v)}}}}),e}getStatsReport(s){return _(this,arguments,function*({uplinkConnection:i,downlinkConnections:e,freezeMap:t}){let o={msg_device_info:{},msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_cache_ms:0,uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},n=yield this.getStats(i,e);return JSON.stringify(this._prevReport)==="{}"&&(this._prevReport=JSON.parse(JSON.stringify(o))),this.prepareReport({stats:n,report:o,freezeMap:t}),this._prevReportTime=Date.now(),o})}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}};var ch=Se(Ne());var Dd=class extends ch.default{constructor({signalChannel:e,room:t}){super();u(this,"_room");u(this,"_signalChannel");u(this,"_log");u(this,"_uplinkRTT",0);u(this,"_uplinkLoss",0);u(this,"_downlinkRTT",0);u(this,"_downlinkLoss",0);u(this,"_downlinkPrevStatMap",new Map);u(this,"_downlinkLossAndRTTMap",new Map);u(this,"_interval",-1);u(this,"_uplinkNetworkQuality",0);u(this,"_downlinkNetworkQuality",0);this._room=t,this._signalChannel=e,this._log=I.createLogger({id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info(`uplink ${this.uplinkNetworkQuality} -> ${e}, rtt: ${this._uplinkRTT}, loss: ${this._uplinkLoss}`),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:s}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info(`downlink ${this.downlinkNetworkQuality} -> ${e}, rtt: ${t}, loss: ${s}`)}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(V.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(_e.CONNECTION_STATE_CHANGED,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var c,d;if(e.data.code!==0)return;let t=e.data.data;if(t.delay&&this.updateDelay(t.delay),!this._room.uplinkConnection){this.uplinkNetworkQuality=0,this._uplinkLoss=0,this._uplinkRTT=0;return}let s=(d=(c=this._room)==null?void 0:c.uplinkConnection)==null?void 0:d.getPeerConnection();if(s&&this.isPeerConnectionDisconnected(s)){this.uplinkNetworkQuality=6,this._uplinkLoss=0,this._uplinkRTT=0;return}let o=t.expectAudPkg+t.expectVidPkg,n=t.recvAudPkg+t.recvVidPkg,a=o-n;o===0&&n===0||(a<=0?this._uplinkLoss=0:this._uplinkLoss=Math.round(a/o*100),this._uplinkRTT=t.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this._uplinkLoss,this._uplinkRTT))}handleDownlinkNetworkQuality(){return _(this,null,function*(){if(this._room.remotePublishedUserMap.size===0){this.downlinkNetworkQuality=0;return}let e=[...this._room.remotePublishedUserMap.values()],t=e.filter(a=>{var c;return((c=a.getPeerConnection())==null?void 0:c.connectionState)===se.CONNECTED});if(e.filter(a=>this.isPeerConnectionDisconnected(a.getPeerConnection())).length===e.length){this.downlinkNetworkQuality=6;return}for(let a=0;a<t.length;a++){let c=t[a].getPeerConnection();if(!c)return;let{rtt:d,totalPacketsLost:l,totalPacketsReceived:p}=yield this.getStat(c);if(!this._downlinkPrevStatMap.has(c)){this._downlinkPrevStatMap.set(c,{totalPacketsLost:l,totalPacketsReceived:p});continue}let m=0,f=this._downlinkPrevStatMap.get(c),R=l-f.totalPacketsLost,C=p-f.totalPacketsReceived;R<=0||C<0?m=0:m=Math.round(R/(R+C)*100),this._downlinkPrevStatMap.set(c,{totalPacketsLost:l,totalPacketsReceived:p}),this._downlinkLossAndRTTMap.set(c,{rtt:d,loss:m,userId:t[a].getUserId(),audioDelay:t[a].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[a].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach(a=>{this.isPeerConnectionDisconnected(a)&&(this._downlinkPrevStatMap.delete(a),this._downlinkLossAndRTTMap.delete(a))}),this._downlinkLossAndRTTMap.size===0)return;let{rtt:o,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._downlinkRTT=o,this._downlinkLoss=n,this.downlinkNetworkQuality=this.getNetworkQuality(n,o)})}getStat(e){return _(this,null,function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!$i())return t;let s=e.getReceivers();try{for(let o=0;o<s.length;o++)(yield s[o].getStats()).forEach(c=>{c.type==="candidate-pair"&&ee(c.currentRoundTripTime)&&(t.rtt=Math.round(c.currentRoundTripTime*1e3)),c.type==="inbound-rtp"&&(c.mediaType===h.AUDIO||c.mediaType===h.VIDEO)&&(t.totalPacketsLost+=c.packetsLost,t.totalPacketsReceived+=c.packetsReceived)});return t}catch(o){return t}})}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach(s=>{t.rtt+=s.rtt,t.loss+=s.loss}),Object.keys(t).forEach(s=>{t[s]=Math.round(t[s]/e.length)})),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){e.state==="DISCONNECTED"?(this._uplinkRTT=0,this._uplinkLoss=0,this.uplinkNetworkQuality=6):e.state==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange({state:e}){e==="DISCONNECTED"?(this._uplinkLoss=0,this._uplinkRTT=0,this.uplinkNetworkQuality=6):e==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!!(e&&(e.connectionState===se.DISCONNECTED||e.connectionState===se.FAILED||e.connectionState===se.CLOSED))}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this._uplinkRTT=0,this._uplinkLoss=0)}start(){if(this._interval!==-1){this._log.info("network quality calculating is already started");return}this._log.debug("start network quality calculating"),this._interval=re.run(_i,()=>{this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];g.emit(E.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this._uplinkRTT,loss:this._uplinkLoss},downlinks:e}),this.emit(Dd.EVENT_NETWORK_QUALITY,{uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this._uplinkRTT,uplinkLoss:this._uplinkLoss,downlinkRTT:this._downlinkRTT,downlinkLoss:this._downlinkLoss})},{delay:2e3})}stop(){this._log.debug("stopped"),this._interval!==-1&&(re.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach(({srcTinyId:s,videoDelay:o,audioDelay:n})=>{let a=t.get(s);if(a){let c=this._room.remotePublishedUserMap.get(a);c==null||c.setDelay({videoDelay:o,audioDelay:n})}})}},rr=Dd;u(rr,"EVENT_NETWORK_QUALITY","0");function $_({fn:r,context:i}){return function(...e){try{let t=r.apply(i,e);return bs(t)?t.catch(s=>I.error(`${r.name}() error observed ${s}`)):t}catch(t){I.error(`${r.name}() error observed ${t}`)}}}var ea=class{constructor(i){this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0};this._eventMap=new Map;this._captureCostSum=0;this._captureCostCount=0;this._frameWorkType=i.frameWorkType||30,this._component=i.component||0,this.connectionType=i.connectionType||1,this._language=i.language||0,this._room=i.room,this._keyPrefix="key_point",this._log=I.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&W(this[e])&&(this[e]=$_({fn:this[e],context:this}))}),this.initData(),this.installEvents()}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:Re,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,Is().then(i=>{this._basicInfo.string_os_version=As(),i?this._basicInfo.string_device_name=i.mobile?i.model:this._basicInfo.string_os_version:this._basicInfo.string_device_name=this._basicInfo.string_os_version})}addEvent(i,e){return this._eventMap.set(i,e),g.on(i,e),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("pagehide",this.handleUnload),this._room.once("banned",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(E.JOIN_START,this.handleJoinStart).addEvent(E.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(E.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(E.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(E.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(E.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(E.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(E.JOIN_FAILED,this.handleJoinFailed).addEvent(E.LEAVE_START,this.handleLeaveStart).addEvent(E.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(E.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(E.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(E.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(E.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(E.PUBLISH_START,this.handlePublishStart).addEvent(E.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(E.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(E.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(E.PLAY_TRACK_START,this.handlePlayStart).addEvent(E.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(E.PLAYER_STATE_CHANGED,({track:i,state:e,type:t})=>{!_t(i)||!this.hitTest(i.room)||e==="PLAYING"&&(t===h.AUDIO?this.handleAudioPlaying(i):this.handleVideoPlaying(i))}).addEvent(E.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(E.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(E.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(E.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let s=e.hasAudio||e.hasVideo||e.hasSmall,o=e.hasAuxiliary,n=t.hasAudio||t.hasVideo||t.hasSmall,a=t.hasAuxiliary;!s&&n&&this.handleRemoteStreamAdded(t.userId,"main"),!o&&a&&this.handleRemoteStreamAdded(t.userId,"auxiliary")}).addEvent(E.SINGLE_CONNECTION_STAT,({room:i,stat:e})=>{this.hitTest(i)&&(this._pathJoinRoom.int32_ice_cost=e.ice,this._pathJoinRoom.int32_dtls_cost=e.dtls,this._pathJoinRoom.int32_peer_connection_cost=e.peerConnection)})}uninstallEvents(){window.removeEventListener("unload",this.handleUnload),this._eventMap.forEach((i,e)=>g.off(e,i)),this._eventMap.clear()}destroy(){this.uninstallEvents(),re.clearTask(this._intervalId)}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(i){this.hitTest(i.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now()),i.params&&(T(i.params.frameWorkType)||(this._frameWorkType=i.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),T(i.params.component)||(this._component=i.params.component,this._basicInfo.uint32_component=this._component),T(i.params.language)||(this._language=i.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess({room:i,detailCost:e}){if(this.hitTest(i)&&e){let{totalCost:t,local:s,dns:o,tcp:n,tls:a,request:c,response:d}=e;this._pathJoinRoom.int32_schedule_cost=t,this._pathJoinRoom.int32_schedule_local=s,this._pathJoinRoom.int32_schedule_dns=o,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=a,this._pathJoinRoom.int32_schedule_request=c,this._pathJoinRoom.int32_schedule_response=d}}handleSignalConnectionStart({room:i}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd({room:i,error:e}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),e&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=e instanceof b?Number(e.getExtraCode()||e.getCode()):A.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=i.code,i.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=i.room.getSignalInfo())}handleJoinFailed({room:i,error:e}){this.hitTest(i)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=e.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=i.publishedUserList||[])}handleSendFirstVideoFrame({room:i}){!this.hitTest(i)||this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(i){this.hitTest(i.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(i){this.hitTest(i.room)&&this._pathLeaveRoom.uint64_end_time===0&&(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(i){this.hitTest(i.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(i,e){var s;let t=`${i}_${e}`;if(!this._remoteStreamStatMap.has(t)){let o={userId:i,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:P(N({},F_),{msg_user_info:new uo({userId:i,tinyId:(s=this._room.remotePublishedUserMap.get(i))==null?void 0:s.tinyId,role:20})})};o.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(t,o)}}handleSubscribeStart({room:i,remotePublishedUser:e,streamType:t,subscribeState:s}){if(!this.hitTest(i))return;let{userId:o,tinyId:n,role:a}=e,c=new uo({userId:o,tinyId:n,role:a==="anchor"?20:21}),d=Date.now(),l=`${o}_${t}`,p=this._remoteStreamStatMap.get(l);p&&p.subscribeStartTime===0&&(p.subscribeStartTime=d),t==="main"?(e.muteState.hasVideo&&(s.video||s.smallVideo)&&!this._pathMainVideoMap.has(l)&&this._pathMainVideoMap.set(l,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:o,sendSubscribeCMDTime:d}),e.muteState.hasAudio&&s.audio&&!this._pathMainAudioMap.has(l)&&this._pathMainAudioMap.set(l,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:o,sendSubscribeCMDTime:d})):e.muteState.hasAuxiliary&&s.auxiliary&&!this._pathAuxiliaryMap.has(l)&&this._pathAuxiliaryMap.set(l,{sendSubscribeCMDTime:d})}handleSubscribed({room:i,remotePublishedUser:e,streamType:t}){if(this.hitTest(i)){let s=`${e.userId}_${t}`,o=this._remoteStreamStatMap.get(s);o&&o.subscribedTime===0&&(o.subscribedTime=Date.now())}}handlePlayStart({track:i}){if(!_t(i)||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._remoteStreamStatMap.get(e);(t==null?void 0:t.playStreamTime)===0&&(t.playStreamTime=Date.now())}handleVideoLoadedData({track:i}){if(!_t(i)||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._pathMainVideoMap.get(e);t&&t.statsToReport.uint64_combine_first_frame_time===0&&(t.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(i){let e=`${i.userId}_${i.streamType}`,t=Date.now(),s=this._pathMainVideoMap.get(e),o=this._remoteStreamStatMap.get(e);if(s&&(s.statsToReport.uint64_render_first_frame_time===0&&(s.statsToReport.uint64_render_first_frame_time=t),o)){let{statsToReport:a,playStreamTime:c,subscribedTime:d}=o;a.uint32_video_render_first===0&&c-d<=100&&(a.uint32_video_render_first=t-s.sendSubscribeCMDTime)}let n=this._pathAuxiliaryMap.get(e);if(n&&o){let{statsToReport:a,playStreamTime:c,subscribedTime:d}=o;a.uint32_video_render_first===0&&c-d<=100&&(a.uint32_video_render_first=t-n.sendSubscribeCMDTime)}}handleAudioPlaying(i){let e=`${i.userId}_${i.streamType}`,t=this._pathMainAudioMap.get(e);t&&t.statsToReport.uint64_play_first_frame_time===0&&(t.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(i){this.hitTest(i.room)&&(this._networkQuality.totalUplinkLoss+=i.uplink.loss,this._networkQuality.totalUplinkRTT+=i.uplink.rtt,this._networkQuality.count++,i.downlinks.forEach(({rtt:e,loss:t,userId:s,videoDelay:o,audioDelay:n})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(s);if(a)a.totalRTT+=e,a.totalLoss+=t,o&&(a.totalVideoDelay=(a.totalVideoDelay||0)+o,a.videoDelayCount=(a.videoDelayCount||0)+1),n&&(a.totalAudioDelay=(a.totalAudioDelay||0)+n,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let c,d,l,p;o&&(d=o,l=1),n&&(c=n,p=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(s,{totalRTT:e,totalLoss:t,count:1,totalAudioDelay:c,totalVideoDelay:d,audioDelayCount:p,videoDelayCount:l})}}))}handleHeartbeatStats(i){if(this.hitTest(i.room)){let{msg_device_info:e,msg_up_stream_info:t,msg_down_stream_info:s}=i.report;if(t.msg_video_status[0]){let{uint32_video_codec_bitrate:o,uint32_video_enc_fps:n,uint32_video_width:a,uint32_video_height:c}=t.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=o,this._localStreamStat.totalVideoFPS+=n,this._localStreamStat.totalVideoWidth+=a,this._localStreamStat.totalVideoHeight+=c,this._localStreamStat.videoCount++}if(t.msg_audio_status){let{uint32_audio_level:o}=t.msg_audio_status;Math.floor(o/ct*100)>0&&(this._localStreamStat.totalAudioLevel+=o/ct,this._localStreamStat.audioLevelCount++)}s.forEach(o=>{let{msg_user_info:n,msg_audio_status:a,msg_video_status:c}=o,d=n.str_identifier,l=this._room.remotePublishedUserMap.get(d);if(c.forEach(p=>{let m=p.uint32_video_stream_type===2,f=p.uint32_video_stream_type===7,R=`${d}_${m?"main":"auxiliary"}`,C=this._remoteStreamStatMap.get(R);if(!!C&&(m&&(l==null?void 0:l.remoteVideoTrack.isSubscribed)||f&&(l==null?void 0:l.remoteAuxiliaryTrack))){C.totalVideoFPS+=p.uint32_video_receive_fps,C.totalVideoBitrate+=p.uint32_video_codec_bitrate,C.videoCount++,C.statsToReport.uint32_video_width===0&&(C.statsToReport.uint32_video_width=p.uint32_video_width),C.statsToReport.uint32_video_height===0&&(C.statsToReport.uint32_video_height=p.uint32_video_height);let v=m?l.remoteVideoTrack:l.remoteAuxiliaryTrack;v.stat.jitterBufferDelay&&(C.videoJitterBufferDelay=v.stat.jitterBufferDelay),v.stat.framesReceived&&(C.statsToReport.uint32_video_consume_render_rate=Math.floor(v.stat.framesDecoded/v.stat.framesReceived*Kr(10,6)))}}),a){let p=`${d}_${"main"}`,m=this._remoteStreamStatMap.get(p);this._remoteStreamStatMap.has(p)&&m&&(l==null?void 0:l.remoteAudioTrack.isSubscribed)&&(m.totalAudioBitrate+=a.uint32_audio_codec_bitrate,m.audioCount++,l.remoteAudioTrack.stat.jitterBufferDelay&&(m.audioJitterBufferDelay=l.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(a.uint32_audio_level/ct*100)>0&&(m.totalAudioLevel+=a.uint32_audio_level/ct,m.audioLevelCount++))}}),e.uint32_audio_capture_cost&&(this._captureCostSum+=e.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0))}}handlePublishStart({room:i}){this.hitTest(i)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed({track:i,error:e}){let s={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof b?e.getExtraCode()||e.getCode():A.UNKNOWN);i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=s,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=s,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&hi)>=0}hasAudioFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&mi)>=0}hasAuxFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&xi)>=0}hitTest(i){return i===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let i=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=i<<16|e}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((i,e)=>{let{userId:t}=i,s=this._networkQuality.totalDownlinkRTTAndLossMap.get(t);if(s){let{totalLoss:l,count:p,audioDelayCount:m,videoDelayCount:f,totalAudioDelay:R,totalVideoDelay:C}=s;i.statsToReport.uint32_avg_down_loss=Math.floor(l/p),m&&R&&(i.statsToReport.uint32_audio_network_p2p_delay=Math.floor(R/m),i.audioJitterBufferDelay&&(i.statsToReport.uint32_p2p_delay=Math.floor(i.statsToReport.uint32_audio_network_p2p_delay+i.audioJitterBufferDelay))),f&&C&&(i.statsToReport.uint32_video_network_p2p_delay=Math.floor(C/f))}i.videoCount>0&&(i.statsToReport.uint32_video_avg_fps=Math.floor(i.totalVideoFPS/i.videoCount),i.statsToReport.uint32_video_avg_bitrate=Math.floor(i.totalVideoBitrate/i.videoCount)),i.audioCount>0&&(i.statsToReport.uint32_audio_recv_bitrate=i.statsToReport.uint32_audio_bitrate=Math.floor(i.totalAudioBitrate/i.audioCount)),i.audioLevelCount>0&&(i.statsToReport.uint32_audio_play_db=Math.floor(i.totalAudioLevel/i.audioLevelCount*100));let{callDurationCalculator:o}=this._room;o&&(i.statsToReport.uint32_audio_play_time=o.getDuration(e,h.AUDIO),i.statsToReport.uint32_video_play_time=o.getDuration(e,h.VIDEO)),i.statsToReport.uint32_video_render_first=Math.min(i.statsToReport.uint32_video_render_first,sr);let{badCaseDetector:n}=this._room,{dataFreeze:a,count:c}=n.getDataFreezeDuration(e),{renderFreeze:d}=n.getRenderFreezeDuration(e);i.statsToReport.uint32_video_block_count=c,i.statsToReport.uint32_video_block_time=Math.min(a,i.statsToReport.uint32_video_play_time),i.statsToReport.uint32_video_external_block_time=Math.min(d,i.statsToReport.uint32_video_play_time),n.isBlackStream(e)&&i.statsToReport.uint32_video_avg_fps===0?i.statsToReport.uint32_video_black_screen_subjective=1:i.statsToReport.uint32_video_black_screen_subjective=0,(i.subscribeStartTime===0||i.subscribeStartTime-i.streamAddedTime>100||i.playStreamTime===0)&&(this._pathMainAudioMap.delete(e),this._pathMainVideoMap.delete(e),i.statsToReport.uint32_video_render_first=0)}),this._pathMainAudioMap.forEach((i,e)=>{if(!this.hasAudioFlag(i.userId)){this._pathMainAudioMap.delete(e);return}i.statsToReport.uint64_play_first_frame_time-i.statsToReport.uint64_start_enter_time>sr&&(i.statsToReport.uint64_play_first_frame_time=i.statsToReport.uint64_start_enter_time+sr)}),this._pathMainVideoMap.forEach((i,e)=>{if(!this.hasVideoFlag(i.userId)){this._pathMainVideoMap.delete(e);return}i.statsToReport.uint64_render_first_frame_time-i.statsToReport.uint64_start_enter_time>sr&&(i.statsToReport.uint64_render_first_frame_time=i.statsToReport.uint64_start_enter_time+sr)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>sr&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+sr)}getReportData(){this._basicInfo.uint32_networkType=br();let i={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new uo({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:vs(this._signalInfo.relayIp),uint32_client_ip:vs(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*Kr(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map(e=>e.statsToReport),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map(e=>e.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(e=>e.statsToReport),uint32_info_client_ip:vs(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport};return Ko(i),i}report(){return _(this,null,function*(){try{this.prepareReport();let i=this.getReportData();yield this.upload(i),this.initData()}catch(i){this._log.warn(i)}})}upload(i){return _(this,null,function*(){if(i.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),t=yield ya(i),s=t instanceof ArrayBuffer,o=`${Si(e,li.KEY_POINT)}&gzip=${+s}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(o,t)),n||Xt({url:o,body:t}),this.uploadKVStat(D),this.uploadKVStat(Hi)})}setConnectionType(i){this.connectionType=i,this._basicInfo.uint32_connection_type=i}uploadKVStat(i){return _(this,null,function*(){let e=i.getReportData();if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=P(N({},e.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(e);let t=yield ya(e),s=`${Si(+this._room.sdkAppId,li.KV_STAT)}&gzip=${+(t instanceof ArrayBuffer)}`,o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(s,t)),o||Xt({url:s,body:t})})}};y([it({settings:{timeout:500,retries:3}})],ea.prototype,"upload",1);var sr=5e3,F_={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_render_first:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},uo=class{constructor(i){this.str_identifier=String(i.userId),this.str_tinyid=String(i.tinyId||0),this.uint32_role=i.role}},dh=ea;var Od=class{constructor(){u(this,"_startTime");u(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=x())}stop(){this._endTime===0&&(this._endTime=x())}getDuration(){return this._endTime===0?x()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},Xr=Od;var Md=class{constructor(i){u(this,"_room",null);u(this,"_durationMap");u(this,"_eventMap",new Map);this._room=i.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(E.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(E.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(E.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{var n;let{userId:s}=t;if(!this.hitTest(i))return;e.hasAudio&&!t.hasAudio&&this.stopDurationItem(`${s}_${"main"}`,h.AUDIO),e.hasVideo&&!t.hasVideo&&this.stopDurationItem(`${s}_${"main"}`,h.VIDEO),e.hasAuxiliary&&!t.hasAuxiliary&&this.stopDurationItem(`${s}_${"auxiliary"}`,h.VIDEO);let o=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(s);!o||(!e.hasAudio&&t.hasAudio&&o.remoteAudioTrack.isSubscribed&&this.addDuractionItem(s,h.AUDIO,"main"),!e.hasVideo&&t.hasVideo&&o.remoteVideoTrack.isSubscribed&&this.addDuractionItem(s,h.VIDEO,"main"),!e.hasAuxiliary&&t.hasAuxiliary&&o.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(s,h.VIDEO,"auxiliary"))}),this._eventMap.forEach((i,e)=>g.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>g.off(e,i,this)),this._eventMap.clear()}handleSubscribed({room:i,streamType:e,remotePublishedUser:t}){if(!this.hitTest(i))return;let{userId:s}=t,o=`${s}_${e}`;if(t.muteState.hasAudio&&e==="main")if(t.remoteAudioTrack.isSubscribed){let n=new Xr,a=this._durationMap.get(o);a?this.isRecording(a.audio)||a.audio.push(n):this._durationMap.set(o,{userId:s,type:e,audio:[n],video:[]})}else this.stopDurationItem(o,h.AUDIO);if(t.muteState.hasVideo||t.muteState.hasAuxiliary)if(t.remoteVideoTrack.isSubscribed||t.remoteAuxiliaryTrack.isSubscribed){let n=new Xr,a=this._durationMap.get(o);a?this.isRecording(a.video)||a.video.push(n):this._durationMap.set(o,{userId:s,type:e,audio:[],video:[n]})}else this.stopDurationItem(o,h.VIDEO)}handleStreamStopped({room:i,streamType:e,remotePublishedUser:t}){if(!this.hitTest(i))return;let{userId:s}=t,o=`${s}_${e}`;this.stopDurationItem(o,h.AUDIO),this.stopDurationItem(o,h.VIDEO)}isRecording(i){return i.findIndex(e=>e.endTime===0)>=0}addDuractionItem(i,e,t){let s=`${i}_${t}`,o=new Xr,n=this._durationMap.get(s);n?this.isRecording(n[e])||n[e].push(o):this._durationMap.set(s,{userId:i,type:t,audio:e===h.AUDIO?[o]:[],video:e===h.AUDIO?[]:[o]})}stopDurationItem(i,e){if(this._durationMap.has(i)){let s=this._durationMap.get(i)[e].find(o=>o.endTime===0);s&&s.stop()}}hitTest(i){return this._room===i}getDuration(i,e){return this._durationMap.has(i)?this._durationMap.get(i)[e].reduce((s,o)=>s+o.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},uh=Md;var kd=class{constructor(i){u(this,"_room");u(this,"_renderFreezeMap",new Map);u(this,"_isVideoPlayingEventFiredMap",new Map);u(this,"_dataFreezeMap",new Map);u(this,"_monitorFreezeData",new Map);u(this,"_eventMap",new Map);this._room=i.room,this.installEvents()}installEvents(){this._eventMap.set(E.LEAVE_SUCCESS,({room:i})=>{this.hitTest(i)&&this.stop()}).set(E.PLAY_TRACK_START,this.onPlayTrackStart).set(E.UNSUBSCRIBE_SUCCESS,({room:i,streamType:e,remotePublishedUser:t})=>{if(!this.hitTest(i))return;let{userId:s}=t,o=`${s}_${e}`;this.stopDataFreeze({key:o,userId:s,type:e})}).set(E.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let{userId:s}=t;if(e.hasVideo&&!t.hasVideo){let o="main",n=`${t.userId}_${o}`;this.stopDataFreeze({key:n,userId:s,type:o})}if(e.hasAuxiliary&&!t.hasAuxiliary){let o="auxiliary",n=`${t.userId}_${o}`;this.stopDataFreeze({key:n,userId:s,type:o})}}).set(E.PLAYER_STATE_CHANGED,({track:i,state:e,reason:t,type:s})=>{if(!(!_t(i)||!this.hitTest(i.room)||s!==h.VIDEO)){if(e==="PLAYING"){let o=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.set(o,!0)}t===h.MUTE?this.onVideoTrackMuted(i):t===h.UNMUTE&&this.onVideoTrackUnmuted(i)}}).set(E.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((i,e)=>g.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>g.off(e,i,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,s=`${e}_${t}`,o=this._dataFreezeMap.get(s),n=new Xr;o?o.durationItemList.push(n):this._dataFreezeMap.set(s,{userId:e,type:t,durationItemList:[n],isFreezing(){let a=this.durationItemList[this.durationItemList.length-1];return a&&a.endTime===0}})}onVideoTrackUnmuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,s=`${e}_${t}`;this.stopDataFreeze({key:s,userId:e,type:t})}onHearBeatReport({room:i,report:e}){!this.hitTest(i)||e.msg_down_stream_info.forEach(t=>{let s=this._room.remotePublishedUserMap.get(t.msg_user_info.str_identifier);if(!s)return;let{userId:o,muteState:n}=s;t.msg_video_status.forEach(a=>{a.uint32_video_stream_type===2&&n.hasVideo&&!n.videoMuted&&s.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:o,fps:a.uint32_video_dec_fps,type:"main"}),a.uint32_video_stream_type===7&&n.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:o,fps:a.uint32_video_dec_fps,type:"auxiliary"})})})}stopDataFreeze({key:i,userId:e,type:t}){let s=this._dataFreezeMap.get(i);if(!s||!s.isFreezing())return;let o=s.durationItemList[s.durationItemList.length-1];o.stop();let n=o.getDuration();n>Do?this._monitorFreezeData.set(i,{userId:e,type:t,duration:n}):s.durationItemList.pop()}getTotalDuration(i){return i.reduce((e,t)=>{let s=t.getDuration();return e+Math.min(s,5e3)},0)}handleRenderFreeze(s){return _(this,arguments,function*({userId:i,fps:e,type:t}){let o=`${i}_${t}`,n=this._renderFreezeMap.get(o);if(e<=2){let a=x();n&&!n.isFreeze&&(n.freezeTimeline.push({startTime:a,endTime:0}),n.isFreeze=!0),n||this._renderFreezeMap.set(o,{userId:i,type:t,isFreeze:!0,freezeTimeline:[{startTime:a,endTime:0}],renderFreezeTotal:0})}else if(n&&n.isFreeze){n.isFreeze=!1;let a=n.freezeTimeline.pop();if(a){a.endTime=x();let c=a.endTime-a.startTime;n.freezeTimeline.push(a),n.renderFreezeTotal+=Math.min(5e3,c)}}})}onPlayTrackStart({track:i}){if(!_t(i)||!this.hitTest(i.room)||i.kind!==h.VIDEO||i.hasFlag)return;let e=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.has(e)||this._isVideoPlayingEventFiredMap.set(e,!1)}getDataFreezeDuration(i){let e={dataFreeze:0,count:0},t=this._dataFreezeMap.get(i);if(t){if(t.isFreezing()){let s=t.durationItemList[t.durationItemList.length-1];s.stop(),s.getDuration()<Do&&t.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(t.durationItemList),e.count=t.durationItemList.length}return e}getRenderFreezeDuration(i){let e=this._renderFreezeMap.get(i),t=0,s=0;if(e)if(!e.isFreeze)t=e.renderFreezeTotal;else{let o=x(),n=e.freezeTimeline[e.freezeTimeline.length-1],a=o-n.startTime;t=e.renderFreezeTotal+Math.min(a,5e3),s=e.freezeTimeline.length}return{renderFreeze:t,count:s}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(i){return this._isVideoPlayingEventFiredMap.has(i)?!this._isVideoPlayingEventFiredMap.get(i):!1}resetMonitor(){this._monitorFreezeData.clear()}hitTest(i){return i===this._room}destroy(){this.uninstallEvents()}},lh=kd;var hh=Se(Ne(),1);var H_=[1,0,0,0,1,1,0,1],ta=class extends Ye{constructor(i){if(super(i,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror"}),i instanceof ye)try{this.setTexBuffer(H_)}catch(e){i.destroy(e)}}draw2d(i,e,t,s,o){if(this.ctx2d){this.ctx2d.save(),this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0);let n=super.draw2d(i,e,t,s,o);return this.ctx2d.restore(),n}return!1}render(i){var e;return(e=this.input)!=null&&e.requestFrame(i)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}};var Ld=class{constructor(i,e){this.node=i;this.layout=e;u(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}},ia=class extends Ye{constructor(e){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0});u(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let s=new Ld(e,t);this.inputs[t.zIndex]=s}resize(e,t){let s=this.inputs.reduce((o,n)=>n?Object.assign(o,{width:Math.max(o.width,n.right),height:Math.max(o.height,n.bottom)}):o,{width:0,height:0});super.resize(s.width,s.height),this.context instanceof ye&&this.inputs.forEach(o=>{if(o){let n=this.layout2texCoords(o);o.positionBuffer?this.changeBufferData(o.positionBuffer,n):o.positionBuffer=this.createBuffer(n)}})}connect(e,...t){return super.connect(e,...t),this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex(t=>(t==null?void 0:t.node)===e)]=void 0}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),!this.inputs.reduce((o,n)=>(!n||!n.node.requestFrame(e))&&o,!0)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let o=0;o<this.inputs.length;o++){let n=this.inputs[o];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){if(!this.inputs.reduce((s,o)=>(!o||!o.node.requestFrame(e))&&s,!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let s=0;s<this.inputs.length;s++){let o=this.inputs[s];o&&this.draw2d(o.node.image,o.x,o.y,o.width,o.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:t,y:s,width:o,height:n,name:a}=this,c=Date.now(),d=(e-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:s,width:o,height:n,timestamp:c,fps:d,name:a},N({parent:this.inputs.filter(l=>l).map(l=>l.node.getInfo())},this.lastInfo)}close(){super.close(),this.inputs.forEach(e=>{var t,s;if(e&&((t=e.node)==null||t.disconnect(),e.positionBuffer&&this.context instanceof ye))try{(s=this.context.ctx)==null||s.deleteBuffer(e.positionBuffer)}catch(o){}})}};var G_=`#version 300 es
|
|
76
|
+
`),e}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return _(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(e){throw this.closePeerConnection(!0),this.uninstallEvents(),e}})}exchangeSDP(){return _(this,null,function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(e){throw e}})}createOffer(){return _(this,null,function*(){try{let e=yield this._peerConnection.createOffer(ah);yield this._peerConnection.setLocalDescription(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:j.PUBLISH,responseCommand:V.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof ze||this.localAuxVideoTrack instanceof ze,state:this.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug(`sending sdp offer: ${e.data.sdp}`),this._signalChannel.sendWaitForResponse(e).then(t=>{let{code:s,message:o,data:n}=t.data;return s===0?this.acceptAnswer(n):this.checkPublishResultCode(s,o)})}setSDPDirection(e,t,s="all"){let o=ce(e);return o.media.forEach(n=>{(s==="all"||n.type===s)&&(n.direction=t)}),He(o)}acceptAnswer(e){return _(this,null,function*(){var t,s,o,n,a;try{let c;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let p=((t=this._publishingLocalVideoTrack)==null?void 0:t.profile.bitrate)||((s=this.localMainVideoTrack)==null?void 0:s.profile.bitrate),m=((o=this._publishingLocalAudioTrack)==null?void 0:o.profile.bitrate)||((n=this.localMainAudioTrack)==null?void 0:n.profile.bitrate);if(p){let f=this._isPublishingAux?h.AUXILIARY:h.BIG;c=yield this.setBandwidth({bandwidth:p,type:h.VIDEO,sdp:c,videoType:f})}m&&(c=yield this.setBandwidth({bandwidth:m,type:h.AUDIO,sdp:c}))}if(c=this.removeVideoOrientation(e.sdp),(a=this._publishingLocalVideoTrack)!=null&&a.small){let{smallStreamConfig:p}=this._room;c=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||p.bitrate,type:h.VIDEO,videoType:h.SMALL,sdp:c})}let u={type:e.type,sdp:c};yield this._peerConnection.setRemoteDescription(u),this._log.debug(`accepted answer: ${c}`)}catch(c){throw this._log.error(`failed to accept remote answer ${c}`),c}})}sendMutedFlag(e){var o,n,a;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let s={audio:!!((o=this.localMainAudioTrack)!=null&&o.muted),bigVideo:!!((n=this.localMainVideoTrack)!=null&&n.muted),auxVideo:!!((a=this.localAuxVideoTrack)!=null&&a.muted)};this._log.info(`send muted state: ${JSON.stringify(s)}`),this._signalChannel.send(j.UPDATE_MUTE_STAT,s)}getIsReconnecting(){return this._isReconnecting}reconnect(){return _(this,null,function*(){if(!(Ie(Od.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:j.UNPUBLISH,responseCommand:V.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch(t){let s=Lt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${s/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},s)}})}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&g.emit(E.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{ce(e).media.forEach((s,o)=>{if(s.type===h.AUDIO){let n=s.ssrcs&&s.ssrcs[0];n&&(this.ssrc.audio=Number(n.id))}else{if(this._sdpSemantics===ur&&s.ssrcGroups){s.ssrcGroups.forEach((a,c)=>{let d=Number(a.ssrcs.split(" ")[0]);c===0?this.ssrc.video=d:c===1&&(this.ssrc.small=d)});return}let n=s.ssrcs&&s.ssrcs[0];if(!n)return;switch(o){case 1:this.ssrc.video=Number(n.id);break;case 2:this.ssrc.small=Number(n.id);break;case 3:this.ssrc.auxiliary=Number(n.id);break;default:break}}})}catch(t){}}getVideoTrackId(e=h.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===h.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===h.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===h.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===h.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Vi?(this._log.error(Ae.NOT_SUPPORTED_H264ENCODE),new b({code:A.NOT_SUPPORTED_H264,message:L({key:M.NOT_SUPPORTED_H264ENCODE})})):new b({code:A.UNKNOWN,message:L({key:M.SIGNAL_RESPONSE_FAILED,data:{signalResponse:V.PUBLISH_RESULT,code:e,message:t}})})}},ao=Od;y([W(r=>function(...i){return new Promise((e,t)=>{let s=o=>{this._emitter.off("closed",s),t(new b({code:A.API_CALL_ABORTED,message:L({key:M.CONNECTION_ABORTED,data:o})}))};this._emitter.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this._emitter.off("closed",s)})})})],ao.prototype,"publish",1),y([Tt(Ke.prototype.afterConnect),An(Ke.prototype.beforeConnect)],ao.prototype,"connect",1);var co=ao;var lo=class{constructor(i,e){this.room=i;l(this,"_log");l(this,"_prevReportTime",0);l(this,"_prevReport",{});l(this,"_prevStats",null);l(this,"_prevEncoderImplementation","");l(this,"_prevAuxEncoderImpl","");l(this,"_prevQualityLimitationReason","");l(this,"_prevAuxQualityLimitationReason","");l(this,"_prevDecoderImplementationMap",new Map);l(this,"totalBytesSent",0);l(this,"totalBytesReceived",0);l(this,"_spcStats",null);this._log=e}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(i){return _(this,null,function*(){let e={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},t=i.getPeerConnection(),s=i.getSSRC();if(t)try{if((this._spcStats||(yield t.getStats())).forEach(n=>{var d,u,p;let a,c;if(n.type==="outbound-rtp")if((n.mediaType||n.kind)===h.VIDEO){if(n.ssrc===s.video?(a=h.VIDEO,c=i.localMainVideoTrack):n.ssrc===s.small?a=h.SMALL:n.ssrc===s.auxiliary&&(c=i.localAuxVideoTrack,a=h.AUXILIARY),!a)return;if(e[a].bytesSent=n.bytesSent,e[a].packetsSent=n.packetsSent,e[a].framesEncoded=n.framesEncoded,T(n.keyFramesEncoded)||(e[a].keyFramesEncoded=n.keyFramesEncoded),T(n.nackCount)||(e[a].nackCount=n.nackCount),T(n.pliCount)||(e[a].pliCount=n.pliCount),T(n.retransmittedPacketsSent)||(e[a].retransmittedPacketsSent=n.retransmittedPacketsSent),T(n.totalEncodeTime)||(e[a].totalEncodeTime=n.totalEncodeTime),T(n.totalPacketSendDelay)||(e[a].totalPacketSendDelay=n.totalPacketSendDelay),!T(n.encoderImplementation)&&(a===h.VIDEO&&this._prevEncoderImplementation!==n.encoderImplementation||a===h.AUXILIARY&&this._prevAuxEncoderImpl!==n.encoderImplementation)){let f=2,R=this._prevEncoderImplementation;a===h.AUXILIARY&&(f=7,R=this._prevAuxEncoderImpl),g.emit("262",{userId:i.userId,streamType:f,prevImplementation:R,implementation:n.encoderImplementation,codec:i.videoCodec,isHWCodec:n.powerEfficientEncoder}),this[a===h.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=n.encoderImplementation,this._log.info(`${a===h.AUXILIARY?"aux ":""}encoderImplementation change to ${n.encoderImplementation}(${i.videoCodec}) HWEncoder: ${n.powerEfficientEncoder}`)}n.ssrc===s.video?!T(n.qualityLimitationReason)&&n.bytesSent!==0&&this._prevQualityLimitationReason!==n.qualityLimitationReason&&(this._log.info(`qualityLimitationReason change to ${n.qualityLimitationReason}`),g.emit("263",{userId:i.userId,reason:n.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:(d=i.localMainVideoTrack)==null?void 0:d.isQosClearFirst}),this._prevQualityLimitationReason=n.qualityLimitationReason):n.ssrc===s.auxiliary&&!T(n.qualityLimitationReason)&&n.bytesSent!==0&&this._prevAuxQualityLimitationReason!==n.qualityLimitationReason&&(this._log.info(`aux qualityLimitationReason change to ${n.qualityLimitationReason}`),g.emit("263",{userId:i.userId,reason:n.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:(u=i.localAuxVideoTrack)==null?void 0:u.isQosClearFirst}),this._prevAuxQualityLimitationReason=n.qualityLimitationReason)}else e.audio.bytesSent=n.bytesSent,e.audio.packetsSent=n.packetsSent;else n.type==="candidate-pair"?yi(n)&&ee(n.currentRoundTripTime)&&(e.rtt=Math.floor(n.currentRoundTripTime*1e3),this.totalBytesSent=n.bytesSent):n.type==="media-source"&&(n.kind===h.AUDIO?(e.audio.audioLevel=n.audioLevel||0,e.audio.totalAudioEnergy=n.totalAudioEnergy||0,n.echoReturnLoss,n.totalSamplesDuration&&(e.audio.totalSamplesDuration=n.totalSamplesDuration)):n.kind===h.VIDEO&&(n.trackIdentifier===i.getVideoTrackId(h.VIDEO)?e.video.fpsCapture=n.framesPerSecond:n.trackIdentifier===i.getVideoTrackId(h.AUXILIARY)?e.auxiliary.fpsCapture=n.framesPerSecond:e.small.fpsCapture=n.framesPerSecond));if(!T(n.audioLevel)&&((p=i.localMainAudioTrack)==null?void 0:p.mediaTrack)&&n.trackIdentifier===i.localMainAudioTrack.mediaTrack.id&&(e.audio.audioLevel=n.audioLevel||0),!T(n.frameWidth)){let m=h.SMALL;n.trackIdentifier===i.getVideoTrackId(h.VIDEO)||n.ssrc===s.video?m=h.VIDEO:(n.trackIdentifier===i.getVideoTrackId(h.AUXILIARY)||n.ssrc===s.auxiliary)&&(m=h.AUXILIARY),e[m].frameWidth=n.frameWidth,e[m].frameHeight=n.frameHeight,e[m].framesSent=n.framesSent}}),i.localMainAudioTrack){let n=i.localMainAudioTrack.getInternalAudioLevel();e.audio.micAudioLevel=n,e.audio.audioLevel===0&&(e.audio.audioLevel=n)}this.totalBytesSent||(this.totalBytesSent+=e.audio.bytesSent+e.video.bytesSent+e.auxiliary.bytesSent),Object.keys(e).forEach(n=>{n===h.AUDIO?i.localMainAudioTrack&&(i.localMainAudioTrack.stat=e[n]):n===h.VIDEO?i.localMainVideoTrack&&(i.localMainVideoTrack.stat=e[n]):n===h.AUXILIARY&&i.localAuxVideoTrack&&(i.localAuxVideoTrack.stat=e[n])})}catch(o){this._log.warn(`failed to getStats on sender connection ${o}`)}return e})}getReceiverStats(i){return _(this,null,function*(){let e={tinyId:i.tinyId,userId:i.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0}},t=i.getPeerConnection();if(t)try{let{ssrc:s}=i,{muteState:o,subscribeState:n}=i;(this._spcStats||(yield t.getStats())).forEach(c=>{if(c.type==="inbound-rtp"){let d=(c.mediaType||c.kind)===h.AUDIO;if(d){if(c.ssrc!==s.audio||!o.hasAudio)return;e.audio.packetsReceived=c.packetsReceived,e.audio.bytesReceived=c.bytesReceived,e.audio.packetsLost=c.packetsLost,c.insertedSamplesForDeceleration&&(e.audio.insertedSamplesForDeceleration=c.insertedSamplesForDeceleration),c.removedSamplesForAcceleration&&(e.audio.removedSamplesForAcceleration=c.removedSamplesForAcceleration),c.totalSamplesDuration&&(e.audio.totalSamplesDuration=c.totalSamplesDuration),c.totalSamplesReceived&&(e.audio.totalSamplesReceived=c.totalSamplesReceived),c.concealedSamples&&(e.audio.concealedSamples=c.concealedSamples);let{remoteAudioTrack:u}=i;u.stat.packetsReceived=c.packetsReceived,u.stat.bytesReceived=c.bytesReceived,u.stat.packetsLost=c.packetsLost,e.audio.p2pDelay=u.stat.end2EndDelay,e.hasAudio=!0}else{if(ie&&c.bytesReceived===0)return;let u;c.ssrc===s.video&&o.hasVideo&&(e.video.packetsReceived=c.packetsReceived,e.video.bytesReceived=c.bytesReceived,e.video.packetsLost=c.packetsLost,e.video.framesReceived=c.framesReceived,e.video.framesDecoded=c.framesDecoded,e.video.fpsDecoded=c.framesPerSecond,e.hasVideo=!0,u=i.remoteVideoTrack,o.hasSmall&&n.smallVideo&&(e.isSmallSubscribed=!0),c.decoderImplementation&&(!this._prevDecoderImplementationMap.has(e.userId)||this._prevDecoderImplementationMap.get(e.userId)!==c.decoderImplementation)&&(this._log.info(`${e.userId} decoderImplementation change to ${c.decoderImplementation} HWDecoder: ${c.powerEfficientDecoder}`),g.emit("262",{userId:this.room.userId,remoteUserId:e.userId,prevImplementation:this._prevDecoderImplementationMap.get(e.userId),implementation:c.decoderImplementation,codec:i.videoCodec,isHWCodec:c.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(e.userId,c.decoderImplementation))),c.ssrc===s.auxiliary&&o.hasAuxiliary&&(e.auxiliary.packetsReceived=c.packetsReceived,e.auxiliary.bytesReceived=c.bytesReceived,e.auxiliary.packetsLost=c.packetsLost,e.auxiliary.framesReceived=c.framesReceived,e.auxiliary.framesDecoded=c.framesDecoded,e.auxiliary.fpsDecoded=c.framesPerSecond,u=i.remoteAuxiliaryTrack,e.hasAuxiliary=!0),u&&(u.stat.packetsReceived=c.packetsReceived,u.stat.bytesReceived=c.bytesReceived,u.stat.packetsLost=c.packetsLost,u.stat.framesReceived=c.framesReceived,u.stat.framesDecoded=c.framesDecoded,c.jitterBufferDelay&&(u.stat.jitterBufferDelay=Math.floor(c.jitterBufferDelay/c.jitterBufferEmittedCount*1e3)))}c.jitterBufferDelay&&(d?(e.audio.totalJitter=c.jitterBufferDelay,e.audio.totalJitterCount=c.jitterBufferEmittedCount):c.ssrc===s.video&&o.hasVideo?(e.video.totalJitter=c.jitterBufferDelay,e.video.totalJitterCount=c.jitterBufferEmittedCount):c.ssrc===s.auxiliary&&o.hasAuxiliary&&(e.auxiliary.totalJitter=c.jitterBufferDelay,e.auxiliary.totalJitterCount=c.jitterBufferEmittedCount))}else c.type==="candidate-pair"&&yi(c)&&ee(c.currentRoundTripTime)&&(e.rtt=Math.floor(c.currentRoundTripTime*1e3),this.totalBytesReceived=c.bytesReceived);T(c.frameWidth)||((c.trackIdentifier===i.getMainStreamVideoTrackId()||c.ssrc===s.video)&&(e.video.frameWidth=c.frameWidth,e.video.frameHeight=c.frameHeight,i.remoteVideoTrack.stat.frameWidth=c.frameWidth,i.remoteVideoTrack.stat.frameHeight=c.frameHeight),(c.trackIdentifier===i.getAuxStreamVideoTrackId()||c.ssrc===s.auxiliary)&&(e.auxiliary.frameWidth=c.frameWidth,e.auxiliary.frameHeight=c.frameHeight,i.remoteAuxiliaryTrack.stat.frameWidth=c.frameWidth,i.remoteAuxiliaryTrack.stat.frameHeight=c.frameHeight)),!T(c.audioLevel)&&i.muteState.audioAvailable&&i.remoteAudioTrack.mediaTrack&&c.trackIdentifier===i.remoteAudioTrack.mediaTrack.id&&(e.audio.audioLevel=c.audioLevel||0,e.audio.totalAudioEnergy=c.totalAudioEnergy||0)}),e.audio.audioLevel===0&&i.muteState.audioAvailable&&(e.audio.audioLevel=i.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=e.audio.bytesReceived+e.video.bytesReceived+e.auxiliary.bytesReceived)}catch(s){this._log.warn(`failed to getStats on receiver connection ${s}`)}return e})}getStats(i,e){return _(this,null,function*(){let t={},s=[];if(this.room.singlePC){let o=this.room.singlePC.getPeerConnection();if(!o)return{senderStats:t,receiverStats:s};let n=x(),a=yield o.getStats(),c=x();c-n>2e3&&this._log.warn(`getStats cost ${c-n}ms`);let d=[],u=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);a.forEach(p=>u.has(p.type)&&d.push(p)),this._spcStats=d}i&&(t=yield this.getSenderStats(i));for(let[o,n]of e){let a=yield this.getReceiverStats(n);s.push(a)}return{senderStats:t,receiverStats:s}})}getDifferenceValue(i,e){if($t(i))return e;let t=e-i;return t<0?0:t}prepareReport({stats:i,report:e,freezeMap:t}){var p;if(!$t(i.senderStats)){let m={uint32_audio_level:i.senderStats.audio.audioLevel*dt,uint32_audio_energy:(i.senderStats.audio.totalAudioEnergy||0)*1e6,uint32_audio_codec_bitrate:i.senderStats.audio.bytesSent};i.senderStats.audio.micAudioLevel&&(m.uint32_mic_audio_level=i.senderStats.audio.micAudioLevel*dt),i.senderStats.audio.totalSamplesDuration&&(e.msg_device_info.uint32_audio_capture_cost=i.senderStats.audio.totalSamplesDuration);let f=[];if(i.senderStats.video.bytesSent){let C={uint32_video_stream_type:2,uint32_video_codec_fps:i.senderStats.video.framesSent,uint32_video_capture_fps:i.senderStats.video.fpsCapture,uint32_video_width:i.senderStats.video.frameWidth,uint32_video_height:i.senderStats.video.frameHeight,uint32_video_codec_bitrate:i.senderStats.video.bytesSent,uint32_video_enc_fps:i.senderStats.video.framesEncoded,uint32_key_frame_count:i.senderStats.video.keyFramesEncoded,uint32_nack_count:i.senderStats.video.nackCount,uint32_pli_count:i.senderStats.video.pliCount,uint32_encode_cost:(i.senderStats.video.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.video.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.video.retransmittedPacketsSent};f.push(C)}if(i.senderStats.small.bytesSent){let C={uint32_video_stream_type:3,uint32_video_codec_fps:i.senderStats.small.framesSent||0,uint32_video_capture_fps:i.senderStats.small.fpsCapture||0,uint32_video_width:i.senderStats.small.frameWidth||0,uint32_video_height:i.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:i.senderStats.small.bytesSent,uint32_video_enc_fps:i.senderStats.small.framesEncoded||0,uint32_key_frame_count:i.senderStats.small.keyFramesEncoded,uint32_nack_count:i.senderStats.small.nackCount,uint32_pli_count:i.senderStats.small.pliCount,uint32_encode_cost:(i.senderStats.small.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.small.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.small.retransmittedPacketsSent};f.push(C)}if(i.senderStats.auxiliary.bytesSent){let C={uint32_video_stream_type:7,uint32_video_codec_fps:i.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:i.senderStats.auxiliary.fpsCapture||0,uint32_video_width:i.senderStats.auxiliary.frameWidth||0,uint32_video_height:i.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:i.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:i.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:i.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:i.senderStats.auxiliary.nackCount,uint32_pli_count:i.senderStats.auxiliary.pliCount,uint32_encode_cost:(i.senderStats.auxiliary.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.auxiliary.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.auxiliary.retransmittedPacketsSent};f.push(C)}let R={uint32_bitrate:0,uint32_lost:0,uint32_rtt:i.senderStats.rtt};e.msg_up_stream_info={msg_audio_status:m,msg_video_status:f,msg_network_status:R}}let{statInterval:s}=this;e.msg_down_stream_info=[],i.receiverStats.forEach(m=>{let f={msg_user_info:{str_identifier:m.userId,uint64_tinyid:m.tinyId},msg_network_status:{uint32_rtt:m.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(m.hasAudio){let R={uint32_audio_p2p_delay:m.audio.p2pDelay,uint32_audio_cache_ms:m.audio.totalJitter,uint32_audio_cache_ms_count:m.audio.totalJitterCount,uint32_audio_codec_bitrate:m.audio.bytesReceived,uint32_audio_total_bitrate:m.audio.bytesReceived,uint32_audio_level:m.audio.audioLevel*1e8,uint32_audio_energy:m.audio.totalAudioEnergy*1e6,uint32_audio_receive:m.audio.packetsReceived,uint32_audio_origin_lost:m.audio.packetsLost};f.msg_audio_status=R}if(m.hasVideo){let R=t.get(`${m.userId}_${ga}`),C=R?R.duration:0,v={uint32_video_stream_type:m.isSmallSubscribed?3:2,uint32_video_receive_fps:m.video.framesReceived,uint32_video_width:m.video.frameWidth,uint32_video_height:m.video.frameHeight,uint32_video_codec_bitrate:m.video.bytesReceived,uint32_video_receive:m.video.packetsReceived,uint32_video_origin_lost:m.video.packetsLost,uint32_video_block_time:C,uint32_video_dec_fps:m.video.framesDecoded,uint32_video_cache_ms:m.video.totalJitter,uint32_video_cache_ms_count:m.video.totalJitterCount};f.msg_video_status.push(v)}if(m.hasAuxiliary){let R=t.get(`${m.userId}_${Ta}`),C=R?R.duration:0,v={uint32_video_stream_type:7,uint32_video_receive_fps:m.auxiliary.framesReceived,uint32_video_width:m.auxiliary.frameWidth,uint32_video_height:m.auxiliary.frameHeight,uint32_video_codec_bitrate:m.auxiliary.bytesReceived,uint32_video_receive:m.auxiliary.packetsReceived+m.auxiliary.packetsLost,uint32_video_origin_lost:m.auxiliary.packetsLost,uint32_video_block_time:C,uint32_video_dec_fps:m.auxiliary.framesDecoded,uint32_video_cache_ms:m.auxiliary.totalJitter,uint32_video_cache_ms_count:m.auxiliary.totalJitterCount};f.msg_video_status.push(v)}e.msg_down_stream_info.push(f)});let o=this._prevReport,n=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(e)),this._prevStats=JSON.parse(JSON.stringify(i)),e.msg_up_stream_info.msg_audio_status&&o.msg_up_stream_info.msg_audio_status){let m=o.msg_up_stream_info.msg_audio_status,f=e.msg_up_stream_info.msg_audio_status;if(m.uint32_audio_codec_bitrate===0)f.uint32_audio_codec_bitrate=0;else{let R=this.getDifferenceValue(m.uint32_audio_codec_bitrate,f.uint32_audio_codec_bitrate);f.uint32_audio_codec_bitrate=Math.round(R*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=f.uint32_audio_codec_bitrate}(p=o.msg_device_info)!=null&&p.uint32_audio_capture_cost?e.msg_device_info.uint32_audio_capture_cost=2*Math.floor(this.getDifferenceValue(o.msg_device_info.uint32_audio_capture_cost,e.msg_device_info.uint32_audio_capture_cost)*1e3/s):delete e.msg_device_info.uint32_audio_capture_cost}let a=o.msg_up_stream_info.msg_video_status;e.msg_up_stream_info.msg_video_status.forEach(m=>{let f=a.find(Ge=>Ge.uint32_video_stream_type===m.uint32_video_stream_type);if(!f||f.uint32_video_codec_bitrate===0){m.uint32_video_codec_bitrate=0,m.uint32_video_enc_fps=0,m.uint32_video_codec_fps=0;return}let R=0,C=0,v=0;f&&m.uint32_video_codec_bitrate>=f.uint32_video_codec_bitrate&&(R=f.uint32_video_codec_bitrate,C=f.uint32_video_enc_fps,v=f.uint32_video_codec_fps);let U=this.getDifferenceValue(R,m.uint32_video_codec_bitrate);m.uint32_video_codec_bitrate=Math.round(U*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=m.uint32_video_codec_bitrate,m.uint32_video_enc_fps=Math.round(this.getDifferenceValue(C,m.uint32_video_enc_fps)/s),m.uint32_video_codec_fps=Math.round(this.getDifferenceValue(v,m.uint32_video_codec_fps)/s),Ti&&zt()===115&&f.uint32_video_width===0&&f.uint32_video_height===0&&f.uint32_video_codec_fps===0&&(m.uint32_video_codec_fps=m.uint32_video_enc_fps),T(f.uint32_key_frame_count)||(m.uint32_key_frame_count=Math.round(this.getDifferenceValue(f.uint32_key_frame_count,m.uint32_key_frame_count))),T(f.uint32_nack_count)||(m.uint32_nack_count=Math.round(this.getDifferenceValue(f.uint32_nack_count,m.uint32_nack_count))),T(f.uint32_pli_count)||(m.uint32_pli_count=Math.round(this.getDifferenceValue(f.uint32_pli_count,m.uint32_pli_count))),T(f.uint32_video_arq_packets)||(m.uint32_video_arq_packets=Math.round(this.getDifferenceValue(f.uint32_video_arq_packets,m.uint32_video_arq_packets))),T(f.uint32_encode_cost)||(m.uint32_encode_cost=Math.round(this.getDifferenceValue(f.uint32_encode_cost,m.uint32_encode_cost)/s)),T(f.uint32_send_packet_cost)||(m.uint32_send_packet_cost=Math.round(this.getDifferenceValue(f.uint32_send_packet_cost,m.uint32_send_packet_cost)/s))});let d=o.msg_down_stream_info;e.msg_down_stream_info=e.msg_down_stream_info.filter(m=>d.find(f=>f.msg_user_info.uint64_tinyid===m.msg_user_info.uint64_tinyid));let u=e.msg_down_stream_info;return u.forEach(m=>{let f=d.find(R=>R.msg_user_info.uint64_tinyid===m.msg_user_info.uint64_tinyid);if(!$t(m.msg_audio_status)&&!$t(f.msg_audio_status)){let R=m.msg_audio_status,C=f.msg_audio_status,v=this.getDifferenceValue(C.uint32_audio_cache_ms_count,R.uint32_audio_cache_ms_count);delete R.uint32_audio_cache_ms_count,R.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(C.uint32_audio_cache_ms,R.uint32_audio_cache_ms)/v)||0;let U=this.room.remotePublishedUserMap.get(m.msg_user_info.str_identifier);U&&(U.remoteAudioTrack.stat.jitterBufferDelay=R.uint32_audio_cache_ms),R.uint32_audio_origin_lost=this.getDifferenceValue(C.uint32_audio_origin_lost,R.uint32_audio_origin_lost),R.uint32_audio_receive=this.getDifferenceValue(C.uint32_audio_receive,R.uint32_audio_receive),R.uint32_audio_receive+=R.uint32_audio_origin_lost;let Ge=this.getDifferenceValue(C.uint32_audio_codec_bitrate,R.uint32_audio_codec_bitrate);R.uint32_audio_codec_bitrate=Math.round(Ge*8/s),R.uint32_audio_total_bitrate=Math.round(Ge*8/s)}else m.msg_audio_status={};if(m.msg_video_status&&f.msg_video_status){let R=f.msg_video_status;m.msg_video_status=m.msg_video_status.filter(v=>R.find(U=>U.uint32_video_stream_type===v.uint32_video_stream_type)),m.msg_video_status.forEach(v=>{let U=R.find(Uh=>Uh.uint32_video_stream_type===v.uint32_video_stream_type),Ge=U.uint32_video_receive,To=U.uint32_video_origin_lost,Lh=U.uint32_video_codec_bitrate,G=U.uint32_video_receive_fps,xh=U.uint32_video_dec_fps;v.uint32_video_origin_lost=this.getDifferenceValue(To,v.uint32_video_origin_lost),v.uint32_video_receive=this.getDifferenceValue(Ge,v.uint32_video_receive)+v.uint32_video_origin_lost;let Ph=this.getDifferenceValue(Lh,v.uint32_video_codec_bitrate);v.uint32_video_codec_bitrate=Math.round(Ph*8/s);let wh=this.getDifferenceValue(G,v.uint32_video_receive_fps);v.uint32_video_receive_fps=Math.round(wh/s),v.uint32_video_dec_fps=Math.round(this.getDifferenceValue(xh,v.uint32_video_dec_fps)/s);let Vh=this.getDifferenceValue(U.uint32_video_cache_ms_count,v.uint32_video_cache_ms_count);delete v.uint32_video_cache_ms_count,v.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(U.uint32_video_cache_ms,v.uint32_video_cache_ms)/Vh)||0})}}),n&&i.receiverStats.forEach(m=>{if(m.audio.concealedSamples&&m.audio.totalSamplesReceived){let f=n.receiverStats.find(R=>R.userId===m.userId);if(f&&f.audio.concealedSamples&&f.audio.totalSamplesReceived){let R=m.audio.concealedSamples-f.audio.concealedSamples,C=m.audio.totalSamplesReceived-f.audio.totalSamplesReceived,v=Math.floor(R/C*1e3*s);if(v>s/5){let U=u.find(Ge=>Ge.msg_user_info.str_identifier===m.userId);U&&(U.msg_audio_status.uint32_audio_block_time=v)}}}}),e}getStatsReport(s){return _(this,arguments,function*({uplinkConnection:i,downlinkConnections:e,freezeMap:t}){let o={msg_device_info:{},msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_cache_ms:0,uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},n=yield this.getStats(i,e);return JSON.stringify(this._prevReport)==="{}"&&(this._prevReport=JSON.parse(JSON.stringify(o))),this.prepareReport({stats:n,report:o,freezeMap:t}),this._prevReportTime=Date.now(),o})}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}};var ch=Se(Ne());var Md=class extends ch.default{constructor({signalChannel:e,room:t}){super();l(this,"_room");l(this,"_signalChannel");l(this,"_log");l(this,"_uplinkRTT",0);l(this,"_uplinkLoss",0);l(this,"_downlinkRTT",0);l(this,"_downlinkLoss",0);l(this,"_downlinkPrevStatMap",new Map);l(this,"_downlinkLossAndRTTMap",new Map);l(this,"_interval",-1);l(this,"_uplinkNetworkQuality",0);l(this,"_downlinkNetworkQuality",0);this._room=t,this._signalChannel=e,this._log=I.createLogger({id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info(`uplink ${this.uplinkNetworkQuality} -> ${e}, rtt: ${this._uplinkRTT}, loss: ${this._uplinkLoss}`),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:s}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info(`downlink ${this.downlinkNetworkQuality} -> ${e}, rtt: ${t}, loss: ${s}`)}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(V.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(_e.CONNECTION_STATE_CHANGED,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var c,d;if(e.data.code!==0)return;let t=e.data.data;if(t.delay&&this.updateDelay(t.delay),!this._room.uplinkConnection){this.uplinkNetworkQuality=0,this._uplinkLoss=0,this._uplinkRTT=0;return}let s=(d=(c=this._room)==null?void 0:c.uplinkConnection)==null?void 0:d.getPeerConnection();if(s&&this.isPeerConnectionDisconnected(s)){this.uplinkNetworkQuality=6,this._uplinkLoss=0,this._uplinkRTT=0;return}let o=t.expectAudPkg+t.expectVidPkg,n=t.recvAudPkg+t.recvVidPkg,a=o-n;o===0&&n===0||(a<=0?this._uplinkLoss=0:this._uplinkLoss=Math.round(a/o*100),this._uplinkRTT=t.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this._uplinkLoss,this._uplinkRTT))}handleDownlinkNetworkQuality(){return _(this,null,function*(){if(this._room.remotePublishedUserMap.size===0){this.downlinkNetworkQuality=0;return}let e=[...this._room.remotePublishedUserMap.values()],t=e.filter(a=>{var c;return((c=a.getPeerConnection())==null?void 0:c.connectionState)===se.CONNECTED});if(e.filter(a=>this.isPeerConnectionDisconnected(a.getPeerConnection())).length===e.length){this.downlinkNetworkQuality=6;return}for(let a=0;a<t.length;a++){let c=t[a].getPeerConnection();if(!c)return;let{rtt:d,totalPacketsLost:u,totalPacketsReceived:p}=yield this.getStat(c);if(!this._downlinkPrevStatMap.has(c)){this._downlinkPrevStatMap.set(c,{totalPacketsLost:u,totalPacketsReceived:p});continue}let m=0,f=this._downlinkPrevStatMap.get(c),R=u-f.totalPacketsLost,C=p-f.totalPacketsReceived;R<=0||C<0?m=0:m=Math.round(R/(R+C)*100),this._downlinkPrevStatMap.set(c,{totalPacketsLost:u,totalPacketsReceived:p}),this._downlinkLossAndRTTMap.set(c,{rtt:d,loss:m,userId:t[a].getUserId(),audioDelay:t[a].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[a].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach(a=>{this.isPeerConnectionDisconnected(a)&&(this._downlinkPrevStatMap.delete(a),this._downlinkLossAndRTTMap.delete(a))}),this._downlinkLossAndRTTMap.size===0)return;let{rtt:o,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._downlinkRTT=o,this._downlinkLoss=n,this.downlinkNetworkQuality=this.getNetworkQuality(n,o)})}getStat(e){return _(this,null,function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!Hi())return t;let s=e.getReceivers();try{for(let o=0;o<s.length;o++)(yield s[o].getStats()).forEach(c=>{c.type==="candidate-pair"&&ee(c.currentRoundTripTime)&&(t.rtt=Math.round(c.currentRoundTripTime*1e3)),c.type==="inbound-rtp"&&(c.mediaType===h.AUDIO||c.mediaType===h.VIDEO)&&(t.totalPacketsLost+=c.packetsLost,t.totalPacketsReceived+=c.packetsReceived)});return t}catch(o){return t}})}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach(s=>{t.rtt+=s.rtt,t.loss+=s.loss}),Object.keys(t).forEach(s=>{t[s]=Math.round(t[s]/e.length)})),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){e.state==="DISCONNECTED"?(this._uplinkRTT=0,this._uplinkLoss=0,this.uplinkNetworkQuality=6):e.state==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange({state:e}){e==="DISCONNECTED"?(this._uplinkLoss=0,this._uplinkRTT=0,this.uplinkNetworkQuality=6):e==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!!(e&&(e.connectionState===se.DISCONNECTED||e.connectionState===se.FAILED||e.connectionState===se.CLOSED))}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this._uplinkRTT=0,this._uplinkLoss=0)}start(){if(this._interval!==-1){this._log.info("network quality calculating is already started");return}this._log.debug("start network quality calculating"),this._interval=re.run(Ei,()=>{this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];g.emit(E.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this._uplinkRTT,loss:this._uplinkLoss},downlinks:e}),this.emit(Md.EVENT_NETWORK_QUALITY,{uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this._uplinkRTT,uplinkLoss:this._uplinkLoss,downlinkRTT:this._downlinkRTT,downlinkLoss:this._downlinkLoss})},{delay:2e3})}stop(){this._log.debug("stopped"),this._interval!==-1&&(re.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach(({srcTinyId:s,videoDelay:o,audioDelay:n})=>{let a=t.get(s);if(a){let c=this._room.remotePublishedUserMap.get(a);c==null||c.setDelay({videoDelay:o,audioDelay:n})}})}},or=Md;l(or,"EVENT_NETWORK_QUALITY","0");function $_({fn:r,context:i}){return function(...e){try{let t=r.apply(i,e);return Ns(t)?t.catch(s=>I.error(`${r.name}() error observed ${s}`)):t}catch(t){I.error(`${r.name}() error observed ${t}`)}}}var ta=class{constructor(i){this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0};this._eventMap=new Map;this._captureCostSum=0;this._captureCostCount=0;this._frameWorkType=i.frameWorkType||30,this._component=i.component||0,this.connectionType=i.connectionType||1,this._language=i.language||0,this._room=i.room,this._keyPrefix="key_point",this._log=I.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&K(this[e])&&(this[e]=$_({fn:this[e],context:this}))}),this.initData(),this.installEvents()}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:Re,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,As().then(i=>{this._basicInfo.string_os_version=Cs(),i?this._basicInfo.string_device_name=i.mobile?i.model:this._basicInfo.string_os_version:this._basicInfo.string_device_name=this._basicInfo.string_os_version})}addEvent(i,e){return this._eventMap.set(i,e),g.on(i,e),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("pagehide",this.handleUnload),this._room.once("banned",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(E.JOIN_START,this.handleJoinStart).addEvent(E.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(E.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(E.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(E.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(E.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(E.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(E.JOIN_FAILED,this.handleJoinFailed).addEvent(E.LEAVE_START,this.handleLeaveStart).addEvent(E.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(E.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(E.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(E.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(E.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(E.PUBLISH_START,this.handlePublishStart).addEvent(E.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(E.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(E.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(E.PLAY_TRACK_START,this.handlePlayStart).addEvent(E.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(E.PLAYER_STATE_CHANGED,({track:i,state:e,type:t})=>{!ft(i)||!this.hitTest(i.room)||e==="PLAYING"&&(t===h.AUDIO?this.handleAudioPlaying(i):this.handleVideoPlaying(i))}).addEvent(E.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(E.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(E.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(E.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let s=e.hasAudio||e.hasVideo||e.hasSmall,o=e.hasAuxiliary,n=t.hasAudio||t.hasVideo||t.hasSmall,a=t.hasAuxiliary;!s&&n&&this.handleRemoteStreamAdded(t.userId,"main"),!o&&a&&this.handleRemoteStreamAdded(t.userId,"auxiliary")}).addEvent(E.SINGLE_CONNECTION_STAT,({room:i,stat:e})=>{this.hitTest(i)&&(this._pathJoinRoom.int32_ice_cost=e.ice,this._pathJoinRoom.int32_dtls_cost=e.dtls,this._pathJoinRoom.int32_peer_connection_cost=e.peerConnection)})}uninstallEvents(){window.removeEventListener("unload",this.handleUnload),this._eventMap.forEach((i,e)=>g.off(e,i)),this._eventMap.clear()}destroy(){this.uninstallEvents(),re.clearTask(this._intervalId)}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(i){this.hitTest(i.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now()),i.params&&(T(i.params.frameWorkType)||(this._frameWorkType=i.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),T(i.params.component)||(this._component=i.params.component,this._basicInfo.uint32_component=this._component),T(i.params.language)||(this._language=i.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess({room:i,detailCost:e}){if(this.hitTest(i)&&e){let{totalCost:t,local:s,dns:o,tcp:n,tls:a,request:c,response:d}=e;this._pathJoinRoom.int32_schedule_cost=t,this._pathJoinRoom.int32_schedule_local=s,this._pathJoinRoom.int32_schedule_dns=o,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=a,this._pathJoinRoom.int32_schedule_request=c,this._pathJoinRoom.int32_schedule_response=d}}handleSignalConnectionStart({room:i}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd({room:i,error:e}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),e&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=e instanceof b?Number(e.getExtraCode()||e.getCode()):A.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=i.code,i.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=i.room.getSignalInfo())}handleJoinFailed({room:i,error:e}){this.hitTest(i)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=e.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=i.publishedUserList||[])}handleSendFirstVideoFrame({room:i}){!this.hitTest(i)||this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(i){this.hitTest(i.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(i){this.hitTest(i.room)&&this._pathLeaveRoom.uint64_end_time===0&&(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(i){this.hitTest(i.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(i,e){var s;let t=`${i}_${e}`;if(!this._remoteStreamStatMap.has(t)){let o={userId:i,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:P(N({},F_),{msg_user_info:new uo({userId:i,tinyId:(s=this._room.remotePublishedUserMap.get(i))==null?void 0:s.tinyId,role:20})})};o.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(t,o)}}handleSubscribeStart({room:i,remotePublishedUser:e,streamType:t,subscribeState:s}){if(!this.hitTest(i))return;let{userId:o,tinyId:n,role:a}=e,c=new uo({userId:o,tinyId:n,role:a==="anchor"?20:21}),d=Date.now(),u=`${o}_${t}`,p=this._remoteStreamStatMap.get(u);p&&p.subscribeStartTime===0&&(p.subscribeStartTime=d),t==="main"?(e.muteState.hasVideo&&(s.video||s.smallVideo)&&!this._pathMainVideoMap.has(u)&&this._pathMainVideoMap.set(u,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:o,sendSubscribeCMDTime:d}),e.muteState.hasAudio&&s.audio&&!this._pathMainAudioMap.has(u)&&this._pathMainAudioMap.set(u,{statsToReport:{msg_user_info:c,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:o,sendSubscribeCMDTime:d})):e.muteState.hasAuxiliary&&s.auxiliary&&!this._pathAuxiliaryMap.has(u)&&this._pathAuxiliaryMap.set(u,{sendSubscribeCMDTime:d})}handleSubscribed({room:i,remotePublishedUser:e,streamType:t}){if(this.hitTest(i)){let s=`${e.userId}_${t}`,o=this._remoteStreamStatMap.get(s);o&&o.subscribedTime===0&&(o.subscribedTime=Date.now())}}handlePlayStart({track:i}){if(!ft(i)||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._remoteStreamStatMap.get(e);(t==null?void 0:t.playStreamTime)===0&&(t.playStreamTime=Date.now())}handleVideoLoadedData({track:i}){if(!ft(i)||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._pathMainVideoMap.get(e);t&&t.statsToReport.uint64_combine_first_frame_time===0&&(t.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(i){let e=`${i.userId}_${i.streamType}`,t=Date.now(),s=this._pathMainVideoMap.get(e),o=this._remoteStreamStatMap.get(e);if(s&&(s.statsToReport.uint64_render_first_frame_time===0&&(s.statsToReport.uint64_render_first_frame_time=t),o)){let{statsToReport:a,playStreamTime:c,subscribedTime:d}=o;a.uint32_video_render_first===0&&c-d<=100&&(a.uint32_video_render_first=t-s.sendSubscribeCMDTime)}let n=this._pathAuxiliaryMap.get(e);if(n&&o){let{statsToReport:a,playStreamTime:c,subscribedTime:d}=o;a.uint32_video_render_first===0&&c-d<=100&&(a.uint32_video_render_first=t-n.sendSubscribeCMDTime)}}handleAudioPlaying(i){let e=`${i.userId}_${i.streamType}`,t=this._pathMainAudioMap.get(e);t&&t.statsToReport.uint64_play_first_frame_time===0&&(t.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(i){this.hitTest(i.room)&&(this._networkQuality.totalUplinkLoss+=i.uplink.loss,this._networkQuality.totalUplinkRTT+=i.uplink.rtt,this._networkQuality.count++,i.downlinks.forEach(({rtt:e,loss:t,userId:s,videoDelay:o,audioDelay:n})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(s);if(a)a.totalRTT+=e,a.totalLoss+=t,o&&(a.totalVideoDelay=(a.totalVideoDelay||0)+o,a.videoDelayCount=(a.videoDelayCount||0)+1),n&&(a.totalAudioDelay=(a.totalAudioDelay||0)+n,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let c,d,u,p;o&&(d=o,u=1),n&&(c=n,p=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(s,{totalRTT:e,totalLoss:t,count:1,totalAudioDelay:c,totalVideoDelay:d,audioDelayCount:p,videoDelayCount:u})}}))}handleHeartbeatStats(i){if(this.hitTest(i.room)){let{msg_device_info:e,msg_up_stream_info:t,msg_down_stream_info:s}=i.report;if(t.msg_video_status[0]){let{uint32_video_codec_bitrate:o,uint32_video_enc_fps:n,uint32_video_width:a,uint32_video_height:c}=t.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=o,this._localStreamStat.totalVideoFPS+=n,this._localStreamStat.totalVideoWidth+=a,this._localStreamStat.totalVideoHeight+=c,this._localStreamStat.videoCount++}if(t.msg_audio_status){let{uint32_audio_level:o}=t.msg_audio_status;Math.floor(o/dt*100)>0&&(this._localStreamStat.totalAudioLevel+=o/dt,this._localStreamStat.audioLevelCount++)}s.forEach(o=>{let{msg_user_info:n,msg_audio_status:a,msg_video_status:c}=o,d=n.str_identifier,u=this._room.remotePublishedUserMap.get(d);if(c.forEach(p=>{let m=p.uint32_video_stream_type===2,f=p.uint32_video_stream_type===7,R=`${d}_${m?"main":"auxiliary"}`,C=this._remoteStreamStatMap.get(R);if(!!C&&(m&&(u==null?void 0:u.remoteVideoTrack.isSubscribed)||f&&(u==null?void 0:u.remoteAuxiliaryTrack))){C.totalVideoFPS+=p.uint32_video_receive_fps,C.totalVideoBitrate+=p.uint32_video_codec_bitrate,C.videoCount++,C.statsToReport.uint32_video_width===0&&(C.statsToReport.uint32_video_width=p.uint32_video_width),C.statsToReport.uint32_video_height===0&&(C.statsToReport.uint32_video_height=p.uint32_video_height);let v=m?u.remoteVideoTrack:u.remoteAuxiliaryTrack;v.stat.jitterBufferDelay&&(C.videoJitterBufferDelay=v.stat.jitterBufferDelay),v.stat.framesReceived&&(C.statsToReport.uint32_video_consume_render_rate=Math.floor(v.stat.framesDecoded/v.stat.framesReceived*Zr(10,6)))}}),a){let p=`${d}_${"main"}`,m=this._remoteStreamStatMap.get(p);this._remoteStreamStatMap.has(p)&&m&&(u==null?void 0:u.remoteAudioTrack.isSubscribed)&&(m.totalAudioBitrate+=a.uint32_audio_codec_bitrate,m.audioCount++,u.remoteAudioTrack.stat.jitterBufferDelay&&(m.audioJitterBufferDelay=u.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(a.uint32_audio_level/dt*100)>0&&(m.totalAudioLevel+=a.uint32_audio_level/dt,m.audioLevelCount++))}}),e.uint32_audio_capture_cost&&(this._captureCostSum+=e.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0))}}handlePublishStart({room:i}){this.hitTest(i)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed({track:i,error:e}){let s={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof b?e.getExtraCode()||e.getCode():A.UNKNOWN);i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=s,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=s,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&pi)>=0}hasAudioFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&_i)>=0}hasAuxFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&wi)>=0}hitTest(i){return i===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let i=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=i<<16|e}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((i,e)=>{let{userId:t}=i,s=this._networkQuality.totalDownlinkRTTAndLossMap.get(t);if(s){let{totalLoss:u,count:p,audioDelayCount:m,videoDelayCount:f,totalAudioDelay:R,totalVideoDelay:C}=s;i.statsToReport.uint32_avg_down_loss=Math.floor(u/p),m&&R&&(i.statsToReport.uint32_audio_network_p2p_delay=Math.floor(R/m),i.audioJitterBufferDelay&&(i.statsToReport.uint32_p2p_delay=Math.floor(i.statsToReport.uint32_audio_network_p2p_delay+i.audioJitterBufferDelay))),f&&C&&(i.statsToReport.uint32_video_network_p2p_delay=Math.floor(C/f))}i.videoCount>0&&(i.statsToReport.uint32_video_avg_fps=Math.floor(i.totalVideoFPS/i.videoCount),i.statsToReport.uint32_video_avg_bitrate=Math.floor(i.totalVideoBitrate/i.videoCount)),i.audioCount>0&&(i.statsToReport.uint32_audio_recv_bitrate=i.statsToReport.uint32_audio_bitrate=Math.floor(i.totalAudioBitrate/i.audioCount)),i.audioLevelCount>0&&(i.statsToReport.uint32_audio_play_db=Math.floor(i.totalAudioLevel/i.audioLevelCount*100));let{callDurationCalculator:o}=this._room;o&&(i.statsToReport.uint32_audio_play_time=o.getDuration(e,h.AUDIO),i.statsToReport.uint32_video_play_time=o.getDuration(e,h.VIDEO)),i.statsToReport.uint32_video_render_first=Math.min(i.statsToReport.uint32_video_render_first,nr);let{badCaseDetector:n}=this._room,{dataFreeze:a,count:c}=n.getDataFreezeDuration(e),{renderFreeze:d}=n.getRenderFreezeDuration(e);i.statsToReport.uint32_video_block_count=c,i.statsToReport.uint32_video_block_time=Math.min(a,i.statsToReport.uint32_video_play_time),i.statsToReport.uint32_video_external_block_time=Math.min(d,i.statsToReport.uint32_video_play_time),n.isBlackStream(e)&&i.statsToReport.uint32_video_avg_fps===0?i.statsToReport.uint32_video_black_screen_subjective=1:i.statsToReport.uint32_video_black_screen_subjective=0,(i.subscribeStartTime===0||i.subscribeStartTime-i.streamAddedTime>100||i.playStreamTime===0)&&(this._pathMainAudioMap.delete(e),this._pathMainVideoMap.delete(e),i.statsToReport.uint32_video_render_first=0)}),this._pathMainAudioMap.forEach((i,e)=>{if(!this.hasAudioFlag(i.userId)){this._pathMainAudioMap.delete(e);return}i.statsToReport.uint64_play_first_frame_time-i.statsToReport.uint64_start_enter_time>nr&&(i.statsToReport.uint64_play_first_frame_time=i.statsToReport.uint64_start_enter_time+nr)}),this._pathMainVideoMap.forEach((i,e)=>{if(!this.hasVideoFlag(i.userId)){this._pathMainVideoMap.delete(e);return}i.statsToReport.uint64_render_first_frame_time-i.statsToReport.uint64_start_enter_time>nr&&(i.statsToReport.uint64_render_first_frame_time=i.statsToReport.uint64_start_enter_time+nr)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>nr&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+nr)}getReportData(){this._basicInfo.uint32_networkType=vr();let i={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new uo({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Ds(this._signalInfo.relayIp),uint32_client_ip:Ds(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*Zr(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map(e=>e.statsToReport),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map(e=>e.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(e=>e.statsToReport),uint32_info_client_ip:Ds(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport};return Zo(i),i}report(){return _(this,null,function*(){try{this.prepareReport();let i=this.getReportData();yield this.upload(i),this.initData()}catch(i){this._log.warn(i)}})}upload(i){return _(this,null,function*(){if(i.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),t=yield ba(i),s=t instanceof ArrayBuffer,o=`${Ai(e,mi.KEY_POINT)}&gzip=${+s}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(o,t)),n||Qt({url:o,body:t}),this.uploadKVStat(D),this.uploadKVStat(Wi)})}setConnectionType(i){this.connectionType=i,this._basicInfo.uint32_connection_type=i}uploadKVStat(i){return _(this,null,function*(){let e=i.getReportData();if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=P(N({},e.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(e);let t=yield ba(e),s=`${Ai(+this._room.sdkAppId,mi.KV_STAT)}&gzip=${+(t instanceof ArrayBuffer)}`,o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(s,t)),o||Qt({url:s,body:t})})}};y([it({settings:{timeout:500,retries:3}})],ta.prototype,"upload",1);var nr=5e3,F_={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_render_first:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},uo=class{constructor(i){this.str_identifier=String(i.userId),this.str_tinyid=String(i.tinyId||0),this.uint32_role=i.role}},dh=ta;var kd=class{constructor(){l(this,"_startTime");l(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=x())}stop(){this._endTime===0&&(this._endTime=x())}getDuration(){return this._endTime===0?x()-this._startTime:this._endTime-this._startTime}get endTime(){return this._endTime}},Qr=kd;var Ld=class{constructor(i){l(this,"_room",null);l(this,"_durationMap");l(this,"_eventMap",new Map);this._room=i.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(E.SUBSCRIBE_SUCCESS,this.handleSubscribed).set(E.UNSUBSCRIBE_SUCCESS,this.handleStreamStopped).set(E.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{var n;let{userId:s}=t;if(!this.hitTest(i))return;e.hasAudio&&!t.hasAudio&&this.stopDurationItem(`${s}_${"main"}`,h.AUDIO),e.hasVideo&&!t.hasVideo&&this.stopDurationItem(`${s}_${"main"}`,h.VIDEO),e.hasAuxiliary&&!t.hasAuxiliary&&this.stopDurationItem(`${s}_${"auxiliary"}`,h.VIDEO);let o=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(s);!o||(!e.hasAudio&&t.hasAudio&&o.remoteAudioTrack.isSubscribed&&this.addDuractionItem(s,h.AUDIO,"main"),!e.hasVideo&&t.hasVideo&&o.remoteVideoTrack.isSubscribed&&this.addDuractionItem(s,h.VIDEO,"main"),!e.hasAuxiliary&&t.hasAuxiliary&&o.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(s,h.VIDEO,"auxiliary"))}),this._eventMap.forEach((i,e)=>g.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>g.off(e,i,this)),this._eventMap.clear()}handleSubscribed({room:i,streamType:e,remotePublishedUser:t}){if(!this.hitTest(i))return;let{userId:s}=t,o=`${s}_${e}`;if(t.muteState.hasAudio&&e==="main")if(t.remoteAudioTrack.isSubscribed){let n=new Qr,a=this._durationMap.get(o);a?this.isRecording(a.audio)||a.audio.push(n):this._durationMap.set(o,{userId:s,type:e,audio:[n],video:[]})}else this.stopDurationItem(o,h.AUDIO);if(t.muteState.hasVideo||t.muteState.hasAuxiliary)if(t.remoteVideoTrack.isSubscribed||t.remoteAuxiliaryTrack.isSubscribed){let n=new Qr,a=this._durationMap.get(o);a?this.isRecording(a.video)||a.video.push(n):this._durationMap.set(o,{userId:s,type:e,audio:[],video:[n]})}else this.stopDurationItem(o,h.VIDEO)}handleStreamStopped({room:i,streamType:e,remotePublishedUser:t}){if(!this.hitTest(i))return;let{userId:s}=t,o=`${s}_${e}`;this.stopDurationItem(o,h.AUDIO),this.stopDurationItem(o,h.VIDEO)}isRecording(i){return i.findIndex(e=>e.endTime===0)>=0}addDuractionItem(i,e,t){let s=`${i}_${t}`,o=new Qr,n=this._durationMap.get(s);n?this.isRecording(n[e])||n[e].push(o):this._durationMap.set(s,{userId:i,type:t,audio:e===h.AUDIO?[o]:[],video:e===h.AUDIO?[]:[o]})}stopDurationItem(i,e){if(this._durationMap.has(i)){let s=this._durationMap.get(i)[e].find(o=>o.endTime===0);s&&s.stop()}}hitTest(i){return this._room===i}getDuration(i,e){return this._durationMap.has(i)?this._durationMap.get(i)[e].reduce((s,o)=>s+o.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},lh=Ld;var xd=class{constructor(i){l(this,"_room");l(this,"_renderFreezeMap",new Map);l(this,"_isVideoPlayingEventFiredMap",new Map);l(this,"_dataFreezeMap",new Map);l(this,"_monitorFreezeData",new Map);l(this,"_eventMap",new Map);this._room=i.room,this.installEvents()}installEvents(){this._eventMap.set(E.LEAVE_SUCCESS,({room:i})=>{this.hitTest(i)&&this.stop()}).set(E.PLAY_TRACK_START,this.onPlayTrackStart).set(E.UNSUBSCRIBE_SUCCESS,({room:i,streamType:e,remotePublishedUser:t})=>{if(!this.hitTest(i))return;let{userId:s}=t,o=`${s}_${e}`;this.stopDataFreeze({key:o,userId:s,type:e})}).set(E.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let{userId:s}=t;if(e.hasVideo&&!t.hasVideo){let o="main",n=`${t.userId}_${o}`;this.stopDataFreeze({key:n,userId:s,type:o})}if(e.hasAuxiliary&&!t.hasAuxiliary){let o="auxiliary",n=`${t.userId}_${o}`;this.stopDataFreeze({key:n,userId:s,type:o})}}).set(E.PLAYER_STATE_CHANGED,({track:i,state:e,reason:t,type:s})=>{if(!(!ft(i)||!this.hitTest(i.room)||s!==h.VIDEO)){if(e==="PLAYING"){let o=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.set(o,!0)}t===h.MUTE?this.onVideoTrackMuted(i):t===h.UNMUTE&&this.onVideoTrackUnmuted(i)}}).set(E.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((i,e)=>g.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>g.off(e,i,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,s=`${e}_${t}`,o=this._dataFreezeMap.get(s),n=new Qr;o?o.durationItemList.push(n):this._dataFreezeMap.set(s,{userId:e,type:t,durationItemList:[n],isFreezing(){let a=this.durationItemList[this.durationItemList.length-1];return a&&a.endTime===0}})}onVideoTrackUnmuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,s=`${e}_${t}`;this.stopDataFreeze({key:s,userId:e,type:t})}onHearBeatReport({room:i,report:e}){!this.hitTest(i)||e.msg_down_stream_info.forEach(t=>{let s=this._room.remotePublishedUserMap.get(t.msg_user_info.str_identifier);if(!s)return;let{userId:o,muteState:n}=s;t.msg_video_status.forEach(a=>{a.uint32_video_stream_type===2&&n.hasVideo&&!n.videoMuted&&s.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:o,fps:a.uint32_video_dec_fps,type:"main"}),a.uint32_video_stream_type===7&&n.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:o,fps:a.uint32_video_dec_fps,type:"auxiliary"})})})}stopDataFreeze({key:i,userId:e,type:t}){let s=this._dataFreezeMap.get(i);if(!s||!s.isFreezing())return;let o=s.durationItemList[s.durationItemList.length-1];o.stop();let n=o.getDuration();n>Oo?this._monitorFreezeData.set(i,{userId:e,type:t,duration:n}):s.durationItemList.pop()}getTotalDuration(i){return i.reduce((e,t)=>{let s=t.getDuration();return e+Math.min(s,5e3)},0)}handleRenderFreeze(s){return _(this,arguments,function*({userId:i,fps:e,type:t}){let o=`${i}_${t}`,n=this._renderFreezeMap.get(o);if(e<=2){let a=x();n&&!n.isFreeze&&(n.freezeTimeline.push({startTime:a,endTime:0}),n.isFreeze=!0),n||this._renderFreezeMap.set(o,{userId:i,type:t,isFreeze:!0,freezeTimeline:[{startTime:a,endTime:0}],renderFreezeTotal:0})}else if(n&&n.isFreeze){n.isFreeze=!1;let a=n.freezeTimeline.pop();if(a){a.endTime=x();let c=a.endTime-a.startTime;n.freezeTimeline.push(a),n.renderFreezeTotal+=Math.min(5e3,c)}}})}onPlayTrackStart({track:i}){if(!ft(i)||!this.hitTest(i.room)||i.kind!==h.VIDEO||i.hasFlag)return;let e=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.has(e)||this._isVideoPlayingEventFiredMap.set(e,!1)}getDataFreezeDuration(i){let e={dataFreeze:0,count:0},t=this._dataFreezeMap.get(i);if(t){if(t.isFreezing()){let s=t.durationItemList[t.durationItemList.length-1];s.stop(),s.getDuration()<Oo&&t.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(t.durationItemList),e.count=t.durationItemList.length}return e}getRenderFreezeDuration(i){let e=this._renderFreezeMap.get(i),t=0,s=0;if(e)if(!e.isFreeze)t=e.renderFreezeTotal;else{let o=x(),n=e.freezeTimeline[e.freezeTimeline.length-1],a=o-n.startTime;t=e.renderFreezeTotal+Math.min(a,5e3),s=e.freezeTimeline.length}return{renderFreeze:t,count:s}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(i){return this._isVideoPlayingEventFiredMap.has(i)?!this._isVideoPlayingEventFiredMap.get(i):!1}resetMonitor(){this._monitorFreezeData.clear()}hitTest(i){return i===this._room}destroy(){this.uninstallEvents()}},uh=xd;var hh=Se(Ne(),1);var H_=[1,0,0,0,1,1,0,1],ia=class extends Ye{constructor(i){if(super(i,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror"}),i instanceof ye)try{this.setTexBuffer(H_)}catch(e){i.destroy(e)}}draw2d(i,e,t,s,o){if(this.ctx2d){this.ctx2d.save(),this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0);let n=super.draw2d(i,e,t,s,o);return this.ctx2d.restore(),n}return!1}render(i){var e;return(e=this.input)!=null&&e.requestFrame(i)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}};var Pd=class{constructor(i,e){this.node=i;this.layout=e;l(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}},ra=class extends Ye{constructor(e){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0});l(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let s=new Pd(e,t);this.inputs[t.zIndex]=s}resize(e,t){let s=this.inputs.reduce((o,n)=>n?Object.assign(o,{width:Math.max(o.width,n.right),height:Math.max(o.height,n.bottom)}):o,{width:0,height:0});super.resize(s.width,s.height),this.context instanceof ye&&this.inputs.forEach(o=>{if(o){let n=this.layout2texCoords(o);o.positionBuffer?this.changeBufferData(o.positionBuffer,n):o.positionBuffer=this.createBuffer(n)}})}connect(e,...t){return super.connect(e,...t),this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex(t=>(t==null?void 0:t.node)===e)]=void 0}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),!this.inputs.reduce((o,n)=>(!n||!n.node.requestFrame(e))&&o,!0)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let o=0;o<this.inputs.length;o++){let n=this.inputs[o];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){if(!this.inputs.reduce((s,o)=>(!o||!o.node.requestFrame(e))&&s,!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let s=0;s<this.inputs.length;s++){let o=this.inputs[s];o&&this.draw2d(o.node.image,o.x,o.y,o.width,o.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:t,y:s,width:o,height:n,name:a}=this,c=Date.now(),d=(e-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:s,width:o,height:n,timestamp:c,fps:d,name:a},N({parent:this.inputs.filter(u=>u).map(u=>u.node.getInfo())},this.lastInfo)}close(){super.close(),this.inputs.forEach(e=>{var t,s;if(e&&((t=e.node)==null||t.disconnect(),e.positionBuffer&&this.context instanceof ye))try{(s=this.context.ctx)==null||s.deleteBuffer(e.positionBuffer)}catch(o){}})}};var G_=`#version 300 es
|
|
77
77
|
in vec2 a_position;
|
|
78
78
|
in vec2 a_texCoord;
|
|
79
79
|
out vec2 v_texCoord;
|
|
@@ -89,7 +89,7 @@ in vec2 v_texCoord;
|
|
|
89
89
|
out vec4 outColor;
|
|
90
90
|
void main() {
|
|
91
91
|
outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a);
|
|
92
|
-
}`,ra=class extends wr{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,logger:e.log});u(this,"ready",!1);u(this,"_bgTexture");u(this,"_waterMarkTexture");u(this,"_lastMaskTexture");u(this,"_lastMaskFbo");u(this,"_textureValid",!1);u(this,"_selfieTextureValid",!1);u(this,"_selfieSegmentation");u(this,"wasm");u(this,"_prePrograme");u(this,"_segmentationMask");u(this,"_weixin",!1);t.selfieSegmentation&&(this._selfieSegmentation=t.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this)),this.init(t).catch(()=>this.context.destroy(new Error("selfie_segmentation init faild")))}init(e){return _(this,null,function*(){var o,n;let t=e.Wasm,s=this.context.ctx;if(this.wasm=new t.AllIn1(s),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.vbMode=e.bg==="blur"?1:e.bg instanceof HTMLImageElement?2:e.bg==="green"?3:0,e.waterMark){let{x:a,y:c,width:d,height:l}=e.waterMark;this.wasm.setWaterMark(a,c,d,l)}if(e.beautyParams){let{beauty:a,brightness:c,ruddy:d}=e.beautyParams;this.wasm.setBeauty(a,c,d,(o=this.context._canvas)==null?void 0:o.width,(n=this.context._canvas)==null?void 0:n.height)}if(this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),s.uniform1i(s.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(s.uniform1i(s.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(s.uniform1i(s.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),s.uniform1i(s.getUniformLocation(this.program,"lastMask"),4),this._weixin){let a=this.context.createShader(s.FRAGMENT_SHADER,W_),c=this.context.createShader(s.VERTEX_SHADER,G_);this._prePrograme=this.context.createProgram(c,a),s.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),s.uniform1i(s.getUniformLocation(this._prePrograme,"mask"),1)}this.ready=!0})}onPredict(e){var s;let t=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture))),this.useProgram(),this._weixin?this.useTexture():this==null||this._selfieSegmentation.bindTexture(),t.activeTexture(t.TEXTURE1),(s=this._selfieSegmentation)==null||s.bindTexture2d(e),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),this.useBufferFrame(),t.drawArrays(t.TRIANGLE_STRIP,0,4),this._segmentationMask=e,this.totalFrames++}render(e){var a,c,d;let t=this.context.ctx;if(W(this.image.getVideoPlaybackQuality)&&Pe){let p=this.image.getVideoPlaybackQuality().totalVideoFrames;if(this._totalFrames===p)return!1;this._totalFrames=p,this.dropFrames=this._totalFrames-this.totalFrames}let{videoWidth:s,videoHeight:o}=this.image;this.image.width=s,this.image.height=o;let n=!1;if(this.totalFrames)this._weixin?this.useTexture():this==null||this._selfieSegmentation.bindTexture(),n=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(this.program)this.useTexture();else return!1;n=this._textureValid,this._textureValid=!0}return this.width!==s||this.height!==o||!n?(this.resize(s,o),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.image)):t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,this.image),this.ready&&(this._weixin&&(t.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask&&(t.activeTexture(t.TEXTURE1),(a=this._selfieSegmentation)==null||a.bindTexture2d(this._segmentationMask),t.bindFramebuffer(t.FRAMEBUFFER,this._lastMaskFbo||null)),t.drawArrays(t.TRIANGLE_STRIP,0,4),(c=this._selfieSegmentation)==null||c.bindTexture(),this._segmentationMask?t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,s,o):t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,s,o,0)),(d=this._selfieSegmentation)==null||d.send(s,o)),this.totalFrames||(t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),t.drawArrays(t.TRIANGLE_STRIP,0,4)),!1}close(){var t;super.close();let e=this.context.ctx;this._bgTexture&&e.deleteTexture(this._bgTexture),this._waterMarkTexture&&e.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&e.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&e.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&e.deleteProgram(this._prePrograme),(t=this.wasm)==null||t.close()}};var sa=class extends hh.EventEmitter{constructor(e){super();this.room=e;u(this,"videoContext");u(this,"_glVideoContext");u(this,"_2dVideoContext");u(this,"destination");u(this,"smallVideoContext");u(this,"smallDestination");u(this,"smallTrackSource");u(this,"smallImageSource");u(this,"_isMirror",!1);u(this,"cameraTrack");u(this,"cameraNode");u(this,"mirrorNode");u(this,"mixNode");u(this,"screenTrack");u(this,"screenNode");u(this,"selfModel",!1);u(this,"blurRadius",3);u(this,"arTrack");u(this,"Wasm");u(this,"waterMarkNode");u(this,"_waterMarkOption");u(this,"watermarkImageList",[]);u(this,"_beautyParams");u(this,"isUsingArTrack",!1);u(this,"_isMixScreen",!1);u(this,"_virtualBackground");u(this,"virtualBackgroundInstance");u(this,"_bgAssetPath");u(this,"log",I.createLogger({id:"vm"}));u(this,"_checkId",0);u(this,"_use2d",!1);u(this,"_autoSwitchRenderMode",!0);u(this,"_selfieSegmentation");u(this,"_seiEncodeProcessor");u(this,"_seiDecodeProcessor");u(this,"seiWorker");e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new Fe({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode=e==="auto",this._autoSwitchRenderMode)return;let t=e==="2d";this._use2d!==t&&(this._use2d=t,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new Fe({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this.sendCreateResult("videoCtx2d",this._2dVideoContext.ctx?void 0:new Error("create 2d context failed")),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new ye({frameRate:15,logger:this.log,name:"m"});else if(this._glVideoContext.available)return this._glVideoContext;try{this._glVideoContext.create(),this.sendCreateResult(),this._glVideoContext.on("unavailable",(e,t)=>{this.emit("error",{reason:e,error:t}),this.log.warn("video context unavailable",e,t),this.sendCreateResult("videoCtxGl",t||new Error(e)),this.update()})}catch(e){this.emit("error",{reason:"create",error:e}),this.sendCreateResult("videoCtxGl",e)}return this._glVideoContext}enablePrintDetail(e=2e3){this._checkId=re.run(Vi,()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}destroy(){var e,t;(e=this._2dVideoContext)==null||e.destroy(),(t=this._glVideoContext)==null||t.destroy(),this.smallVideoContext.destroy(),re.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(Ir||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",t){let s=e==="videoCtxGl"?512700:512701;t?D.addFailedEvent({key:s,error:t}):D.addSuccessEvent({key:s})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else if(t)if(this._use2d)this.clear();else return!0;else return!0}else this.clear(),this._use2d=!0;return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return(e=this.smallDestination)==null?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return(e=this.cameraTrack)==null?void 0:e.mediaTrack}initVirtualBackground(e){return this._selfieSegmentation=e,this._selfieSegmentation.changeModel()}_setMainOutput(e){var t;try{let s=this.cameraTrack,{small:o,settings:n,player:a}=s;o?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new Dn(this.smallVideoContext,o)),this.smallVideoContext.frameRate=o.frameRate,this.smallDestination.resolution=o,e?(this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.connect(this.smallDestination))):(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource?this.smallTrackSource.replaceTrack(this.initialTrack):(this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource"),this.smallTrackSource.width=n.width,this.smallTrackSource.height=n.height,this.smallTrackSource.connect(this.smallDestination)))):this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource),Ir&&a.setCanvas(e);let c=e&&((t=this.destination)==null?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),c=this.arTrack),this._selfieSegmentation&&e&&!this._use2d&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),this.log.info(`set main output ${c?c.label:"no output track"}`),s.setOutputMediaStreamTrack(c)}catch(s){this.log.error("set main output failed",s)}}update(){return _(this,null,function*(){var s,o;if(!this.cameraTrack||!this.cameraTrack.mediaTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:e,profile:t}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination",logger:this.log})),this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(e.width,e.height))):(this.cameraNode&&this.cameraNode.close(),this.destination||(this.destination=new vn(this.videoContext,{name:"mainDestination",logger:this.log})),this.cameraNode=new ra(this.videoContext,{input:this.cameraTrack.mediaTrack,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination)),this.videoContext.frameRate=t.frameRate,this._use2d){let n=this.cameraNode;n.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new ta(this.videoContext)),n=n.connect(this.mirrorNode),n.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new ia(this.videoContext),n.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption&&(this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y),(s=this.waterMarkNode)==null||s.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource")),(o=this.screenNode)==null||o.connect(this.mixNode,{zIndex:0}),n=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)),n.connect(this.destination)}return this.log.info(`update ${this._use2d?"2d":"webgl"}`),this._setMainOutput(this.videoContext._canvas)})}changeInput(e){var t,s,o,n;if(e instanceof ze)return this.log.info("change screen input",(t=e.mediaTrack)==null?void 0:t.label),this.setScreenTrack(e);if(e instanceof le)return this.log.info("change video input",(s=e.mediaTrack)==null?void 0:s.label),this.setCameraTrack(e);if(e instanceof Tt){this.log.info("change remote input",(o=e.mediaTrack)==null?void 0:o.label);let a=e.mediaTrack;return this._seiDecodeProcessor&&(e.pipeline[1]=this._seiDecodeProcessor),e.setOutputMediaStreamTrack(a)}this.log.warn("change unknown input",(n=e.mediaTrack)==null?void 0:n.label)}configPipeline(e){e instanceof Tt&&this._seiDecodeProcessor&&(e.pipeline[1]=this._seiDecodeProcessor)}removeInput(e){var t;e instanceof ze?((t=this.screenNode)==null||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof le?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof Tt&&e.source&&e.source.context.destroy()}setCameraTrack(e){return _(this,null,function*(){this.cameraTrack=e,this._seiEncodeProcessor&&(this.cameraTrack.pipeline[0]=this._seiEncodeProcessor),this.update()})}setScreenTrack(e){return this.screenTrack=e,this._seiEncodeProcessor&&(this.screenTrack.pipeline[0]=this._seiEncodeProcessor),this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,t){return _(this,null,function*(){let s=document.createElement("canvas");t&&e&&(s.height=t,s.width=e);let o=s.getContext("2d");if(!o)throw new b({code:A.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((n,a)=>n.zIndex-a.zIndex),this.watermarkImageList.forEach(({image:n,x:a,y:c,width:d,height:l})=>{o.drawImage(n,a,c,d,l)}),Os(s.toDataURL())})}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some(o=>o.imageUrl===e.imageUrl&&o.height===e.height&&o.width===e.width&&o.x===e.x&&o.y===e.y&&o.type===e.type&&o.zIndex===e.zIndex)||((t==="mute"||t==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(o=>o.type!==t)),this.watermarkImageList.push(e))}setBeautyParams(e){return _(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return _(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return _(this,null,function*(){let t;try{t=yield Os((e==null?void 0:e.imageElement)||e.imageUrl)}catch(l){throw new b({code:A.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:s=0,y:o=0,width:n=t.width,height:a=t.height,type:c="watermark",zIndex:d=2}=e;this.pushWaterMarkImageList({x:s,y:o,width:n,height:a,image:t,zIndex:d,type:c,imageUrl:e.imageUrl}),yield this.freshWatermark(),this.log.info("set watermark",JSON.stringify(this.watermarkImageList))})}deleteWatermark(e="watermark"){return _(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(t=>t.type!==e),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList)),yield this.freshWatermark()})}freshWatermark(){return _(this,null,function*(){var t,s,o;(t=this.waterMarkNode)==null||t.close(),delete this.waterMarkNode,delete this._waterMarkOption;let e=yield this.getWatermarkImage((s=this.cameraTrack)==null?void 0:s.settings.width,(o=this.cameraTrack)==null?void 0:o.settings.height);this._waterMarkOption={x:0,y:0,width:e.width,height:e.height,image:e},this.update()})}setVirtualBackground(e){return _(this,null,function*(){if(!e)this._virtualBackground=void 0;else{if(this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,e.type==="image"?this._virtualBackground=yield Os(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type)}this.log.info(`${this._virtualBackground?"start":"stop"} virtual background, ${(e==null?void 0:e.type)||""}, ${this.blurRadius||""}`),this.update()})}get mixScreen(){return this._isMixScreen}set mixScreen(e){var t;this._isMixScreen=e,this._isMixScreen||((t=this.screenNode)==null||t.close(),delete this.screenNode),this.update()}set mirror(e){var t;this._isMirror!==e&&(this._isMirror=e,this._isMirror||((t=this.mirrorNode)==null||t.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return _(this,null,function*(){var e;!((e=this.cameraTrack)!=null&&e.mediaTrack)||(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))})}disableAr(){var e;this.isUsingArTrack=!1,(e=this.arTrack)==null||e.stop(),this.arTrack=void 0,this.update()}clear(){var e;(e=this.videoContext)==null||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}enableSEI({encoder:e,decoder:t,seiWorker:s}){s?this.seiWorker=s:(this._seiEncodeProcessor=e,this._seiDecodeProcessor=t,this.cameraTrack&&(this.cameraTrack.pipeline[0]=this._seiEncodeProcessor),this.screenTrack&&(this.screenTrack.pipeline[0]=this._seiEncodeProcessor))}disableSEI(){var e;(e=this.seiWorker)==null||e.terminate(),delete this.seiWorker,delete this._seiEncodeProcessor,delete this._seiDecodeProcessor,this.cameraTrack&&(this.cameraTrack.pipeline[0]=void 0),this.screenTrack&&(this.screenTrack.pipeline[0]=void 0)}};var J_=0;var oa=class extends F{constructor(e){super("room");this.seq=++J_;this.role="anchor";this.joinParams=null;this.localTracks=new Set;this.enableAutoPlayDialog=!0;this.autoReceiveAudio=!0;this.autoReceiveVideo=!0;this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null};this._isUsingCachedSchedule=!1;this._log=I.createLogger({id:`r${this.seq}`});this._joinedTimestamp=0;this.isDestroyed=!1;this.useStringRoomId=!!e.useStringRoomId,de(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),de(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),de(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new dh({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new uh({room:this}),this.badCaseDetector=new lh({room:this}),this.audioManager=new bn(this),this.videoManager=new sa(this)}get isMainStreamPublished(){for(let e of this.localTracks)if(e.mediaType&4)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(e.mediaType&2)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainVideoTrack(){for(let e of this.localTracks)if(e.mediaType&4)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(e.mediaType&2)return e;return null}getLogger(){return this._log}get isJoining(){return this.state.toString()==="joining"}get isJoined(){return this.state==="joined"}get isLeft(){return this.state==="left"}addTrack(e){return _(this,null,function*(){return this.publish(e)})}removeTrack(e){return _(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return _(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(Y(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(Je(e)){let{websocketProxy:t,webtransportProxy:s,loggerProxy:o,scheduleProxy:n,unifiedProxy:a}=e;this.proxy_ws=t,this.proxy_wt=s,this.proxy_unified=a,a?(Fa([a,a]),Li(`https://${a}`)):(o&&Li(o),n&&Fa(n))}g.once(E.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:Ii.main,sched_back_domain:Ii.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return _(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(t=>{e[t.userId]=t.remoteAudioTrack.stat}),e})}getTransportStats(){return _(this,null,function*(){var t;let e={rtt:((t=this.quality)==null?void 0:t.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let s of this.quality.downlinkInfo)e.downlinksRTT[s.userId]=s.rtt;return e})}getRemoteVideoStats(){return _(this,arguments,function*(e="main"){let t={};return this.remotePublishedUserMap.forEach(s=>{let o=e==="auxiliary"?s.remoteAuxiliaryTrack:s.remoteVideoTrack;t[s.userId]=o.stat}),t})}checkDestroy(){if(this.isDestroyed)throw new b({code:A.INVALID_OPERATION,message:L({key:M.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Ae.INVALID_DESTROY),new b({code:A.INVALID_OPERATION,message:L({key:M.INVALID_DESTROY})});this._log.info("destroy room"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this.isDestroyed=!0,g.emit(E.ROOM_DESTROY,{room:this})}schedule(e,t){return _(this,null,function*(){var o,n;let s=x();try{let{isCached:a,result:c,detailCost:d}=yield uu({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:Re,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:t,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=a,this._log.info(`schedule cache:${+a} ${pt(c,{keysToExclude:["username","credential"]})}`),a&&g.once(E.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=N(N({},this.scheduleResult),c),ee((o=c.config)==null?void 0:o.retryCount)&&Ta(c.config.retryCount),Y((n=c.config)==null?void 0:n.loggerDomain)&&Li(c.config.loggerDomain),g.emit(E.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:d}),D.addSuccessEvent({key:521700,cost:x()-s,split:50})}catch(a){throw D.addFailedEvent({key:521700,error:a}),a}})}};var ph=Se(Ne(),1);var mh=Symbol("instance"),CL=Symbol("abortCtrl"),xd=Symbol("cacheResult"),lo=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,po.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},ho=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function j_(r){return typeof r=="object"&&r&&"then"in r}var mo=new Map;function Pd(r,i,e={}){return(t,s,o)=>{let n=e.action||s;if(!e.context){let c=mo.get(t)||[];mo.has(t)||mo.set(t,c),c.push({from:r,to:i,action:n})}let a=o.value;o.value=function(...c){let d=this;if(e.context&&(d=ne.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===i)return d[xd];d.state instanceof lo&&d.state.action==e.abortAction&&d.state.abort(d);let l=null;if(Array.isArray(r)?r.length==0?d.state instanceof lo&&d.state.abort(d):(typeof d.state!="string"||!r.includes(d.state))&&(l=new ho(d._state,`${d.name} ${n} to ${i} failed: current state ${d._state} not in from config`)):r!==d.state&&(l=new ho(d._state,`${d.name} ${n} to ${i} failed: current state ${d._state} not from ${r}`)),l)if(e.fail)e.fail.call(this,l);else{if(e.ignoreError)return l;throw l}let p=d.state,m=new lo(p,i,n);po.call(d,m);let f=C=>{var v;return d[xd]=C,m.aborted||(po.call(d,i),(v=e.success)===null||v===void 0||v.call(this,d[xd])),C},R=C=>{let v=C instanceof Error?C.message:String(C);if(po.call(d,p,C),e.fail)e.fail.call(this,new ho(d._state,`action '${n}' failed :${v}`,C instanceof Error?C:new Error(v)));else{if(e.ignoreError)return C;throw C}};try{let C=a.apply(this,c);return j_(C)?C.then(f).catch(R):f(C)}catch(C){R(C)}}}}var q_=(()=>typeof window!="undefined"&&window.__AFSM__?(e,t)=>{window.dispatchEvent(new CustomEvent(e,{detail:t}))}:typeof importScripts!="undefined"?(e,t)=>{postMessage({type:e,payload:t})}:()=>{})();function po(r,i){let e=this._state;this._state=r;let t=r.toString();r&&this.emit(t,e),this.emit(ne.STATECHANGED,r,e,i),this.updateDevTools({value:r,old:e,err:i instanceof Error?i.message:String(i)})}var ne=class extends ph.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=ne.INIT,i||(i=Date.now().toString(36)),t?Object.setPrototypeOf(this,t):t=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let s=t[mh];s?this.name=s.name+"-"+s.count++:t[mh]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=mo.get(i)||[],t=new Set,s=[],o=[],n=new Set,a=Object.getPrototypeOf(i);mo.has(a)&&(a.stateDiagram.forEach(d=>t.add(d)),a.allStates.forEach(d=>n.add(d))),e.forEach(({from:d,to:l,action:p})=>{typeof d=="string"?s.push({from:d,to:l,action:p}):d.length?d.forEach(m=>{s.push({from:m,to:l,action:p})}):o.push({to:l,action:p})}),s.forEach(({from:d,to:l,action:p})=>{n.add(d),n.add(l),n.add(p+"ing"),t.add(`${d} --> ${p}ing : ${p}`),t.add(`${p}ing --> ${l} : ${p} \u{1F7E2}`),t.add(`${p}ing --> ${d} : ${p} \u{1F534}`)}),o.forEach(({to:d,action:l})=>{t.add(`${l}ing --> ${d} : ${l} \u{1F7E2}`),n.forEach(p=>{p!==d&&t.add(`${p} --> ${l}ing : ${l}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:n}}),c}static get(i){let e;return typeof i=="string"?(e=ne.instances.get(i),e||ne.instances.set(i,e=new ne(i,void 0,Object.create(ne.prototype)))):(e=ne.instances2.get(i),e||ne.instances2.set(i,e=new ne(i.constructor.name,void 0,Object.create(ne.prototype)))),e}static getState(i){var e;return(e=ne.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){q_(ne.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){po.call(this,i)}};ne.STATECHANGED="stateChanged";ne.UPDATEAFSM="updateAFSM";ne.INIT="[*]";ne.ON="on";ne.OFF="off";ne.instances=new Map;ne.instances2=new WeakMap;var Ch=Se(Ne());var wd=Se(Rd());var _h=r=>{let i=ce(r),e={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return i.media.forEach((t,s)=>{var o;if(t.ssrcs&&!T(t.ssrcs[0].id)){let n=Number(t.ssrcs[0].id),a=Number((o=t.ssrcs.filter(c=>c.attribute==="cname")[1])==null?void 0:o.id);switch(s){case 0:e.audioSsrc=n;break;case 1:e.bigVideoSsrc=n,e.bigVideoRtxSsrc=a;break;case 2:e.smallVideoSsrc=n,e.smallVideoRtxSsrc=a;break;case 3:e.auxVideoSsrc=n,e.auxVideoRtxSsrc=a;break}}}),e};function fh(r){var e;let i=[];for(let t=0;t<r.rtp.length;t++){if(["rtx","red","ulpfec"].includes(r.rtp[t].codec))continue;let s=r.fmtp.filter(o=>o.payload===r.rtp[t].payload)[0];i.push({payload:r.rtp[t].payload,codec:r.rtp[t].codec,fmtp:s?s.config:"",rate:r.rtp[t].rate,rtx:((e=r.rtp[t+1])==null?void 0:e.codec)==="rtx"?r.rtp[t+1].payload:0,rtcpFb:((r==null?void 0:r.rtcpFb)||[]).filter(o=>o.payload===r.rtp[t].payload).map(({type:o,subtype:n})=>({id:o,params:n?[n]:[]}))})}return i}function X_(){return _(this,null,function*(){let r=new RTCPeerConnection;r.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_RECVONLY});let i=yield r.createOffer();if(!i.sdp)return[];let e=ce(i.sdp),t=fh(e.media[0]);return r.close(),t})}var Eh=(r,i)=>_(void 0,null,function*(){var c;let e=ce(r),t={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:!1};t.ice.ufrag=String(e.media[0].iceUfrag),t.ice.password=e.media[0].icePwd||"",e.fingerprint&&(t.dtls.hash=e.fingerprint.type,t.dtls.fingerprint=e.fingerprint.hash,t.dtls.setup=e.setup||""),e.media[0].fingerprint&&(t.dtls.hash=e.media[0].fingerprint.type,t.dtls.fingerprint=e.media[0].fingerprint.hash),t.dtls.setup=e.media[0].setup||"";let s=e.media[0],o=e.media[1];s.ext&&(t.audio.extensions=s.ext.map(d=>({id:d.value,uri:d.uri}))),o.ext&&(t.video.extensions=o.ext.map(d=>({id:d.value,uri:d.uri})));let n={codec:s.rtp[0].codec,fmtp:s.fmtp[0].config,payload:s.fmtp[0].payload,rate:s.rtp[0].rate,channel:s.rtp[0].encoding,rtcpFb:[],rtx:0};(c=s.rtcpFb)==null||c.forEach(({payload:d,type:l,subtype:p})=>{if(d===n.payload){let m={id:l,params:[]};p&&m.params.push(p),n.rtcpFb.push(m)}}),t.audio.codecs.push(n);let a=["h264","vp8"];return i&&a.shift(),t.video.codecs=[...fh(o)].filter(d=>a.includes(d.codec.toLocaleLowerCase())),t.video.decoders=(yield X_()).filter(d=>["h264","vp8"].includes(d.codec.toLocaleLowerCase())),t}),gh=({serverAbility:r,clientAbility:i,offerSDP:e,enableCustomMessage:t})=>{let s=ce(e),o={extmapAllowMixed:"extmap-allow-mixed",groups:s.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},n={candidates:r.candidates.map(a=>({component:1,foundation:"1",generation:0,ip:a.ip,port:a.port,priority:a.priority,transport:a.foundation,type:a.type})),connection:{version:4,ip:"0.0.0.0"},direction:h.TRANSCEIVER_DIRECTION_RECVONLY,ext:r.audio.extensions.map(a=>({value:a.id,uri:a.uri})),fingerprint:{type:r.dtls.hash,hash:r.dtls.fingerprint},fmtp:[{payload:r.audio.codecs[0].payload,config:r.audio.codecs[0].fmtp}],icePwd:r.ice.password,iceUfrag:r.ice.ufrag,mid:"0",payloads:String(r.audio.codecs[0].payload),port:s.media[0].port,protocol:s.media[0].protocol,type:h.AUDIO,setup:r.dtls.setup,rtcpFb:r.audio.codecs[0].rtcpfb.map(a=>({payload:r.audio.codecs[0].payload,type:a.id,subtype:a.params[0]})),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:r.audio.codecs[0].payload,codec:r.audio.codecs[0].codec,rate:r.audio.codecs[0].rate,encoding:r.audio.codecs[0].channels}]};return o.media.push(n),[1,2,3].forEach(a=>{o.media.push(Vd({mid:a,serverAbility:r,clientAbility:i,parsedOffer:s}))}),t&&o.media.push(s.media.find(a=>a.mid==="dc")),He(o)},Vd=({mid:r,serverAbility:i,clientAbility:e,parsedOffer:t,isDownlink:s=!1})=>{let o={candidates:i.candidates.map(n=>({component:1,foundation:"1",generation:0,ip:n.ip,port:n.port,priority:n.priority,transport:n.foundation,type:n.type})),connection:{version:4,ip:"0.0.0.0"},direction:h.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map(n=>({value:n.id,uri:n.uri})),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(r),payloads:"",port:t.media[0].port,protocol:t.media[0].protocol,type:h.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(s)(i.video.decoders||i.video.codecs).forEach(n=>{or(o,n)});else{let n=i.video.codecs.findIndex(c=>c.codec.toLowerCase()===(i.useVp8?"vp8":"h264")),a=i.video.codecs[n]||e.video.codecs[0];or(o,a)}return o},or=(r,i)=>{r.payloads=`${r.payloads} ${i.payload}`.trim(),r.fmtp.push({payload:i.payload,config:i.fmtp}),r.rtcpFb=[...r.rtcpFb||[],...(i.rtcpfb||i.rtcpFb).map(e=>({payload:i.payload,type:e.id,subtype:e.params[0]}))],r.rtp.push({payload:i.payload,codec:i.codec.toUpperCase(),rate:i.rate}),i.rtx&&(r.payloads=`${r.payloads} ${i.rtx}`,r.fmtp.push({payload:i.rtx,config:`apt=${i.payload}`}),r.rtp.push({payload:i.rtx,codec:"rtx",rate:i.rate}))};function Q_(r){let i=new Set(["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.ext&&(r.ext=r.ext.filter(e=>!i.has(e.uri)))}function z_(r){if(!r.rtcpFb)return;let i=[];r.rtcpFb.forEach((e,t)=>{var s;i.push(e),r.rtcpFb&&((s=r.rtcpFb[t+1])==null?void 0:s.payload)!==e.payload&&e.type!=="rrtr"&&i.push({payload:e.payload,type:"rrtr"})}),r.rtcpFb=i}function Y_(r){r.type===h.VIDEO&&r.fmtp&&r.fmtp.forEach(i=>{i.config.includes("apt")||(i.config+=";sps-pps-idr-in-keyframe=1")})}function K_(r){r.type===h.AUDIO&&r.fmtp&&r.fmtp.forEach(i=>{i.config+=";sprop-stereo=1;stereo=1"})}var Th=(r,i,e)=>{let t=wd.default.parse(r);return t.media.forEach((s,o)=>{var n;(s.type===h.AUDIO||s.type===h.VIDEO)&&(z_(s),Y_(s),K_(s),Q_(s),s.type===h.VIDEO&&(o<4?(s.payloads="",s.fmtp=[],s.rtp=[],s.rtcpFb=[],i.video.codecs.forEach(a=>or(s,a))):e&&(s.payloads="",s.fmtp=[],s.rtp=[],s.rtcpFb=[],(e.video.decoders||e.video.codecs).forEach(a=>or(s,a))))),((n=s.payloads)==null?void 0:n.includes("datachannel"))&&t.groups&&s.mid&&(t.groups[0].mids=t.groups[0].mids.replace(s.mid,"dc"),s.mid="dc")}),wd.default.write(t)};var Sh=Se(Ne());var na=class extends Sh.EventEmitter{constructor(e){super();this.room=e;u(this,"mainFpsHealth",1);u(this,"mainBitrateHealth",1);u(this,"badMainBitrateHealthCount",0);u(this,"lastEmitBadHealthTime",0);u(this,"log");!pe&&Pe&&g.on("262",this.onVideoCodecChanged,this),this.log=e.getLogger().createChild({id:"h-d"})}onVideoCodecChanged({remoteUserId:e,streamType:t,isHWCodec:s,codec:o}){if(!(e||t===7||o!=="h264")){if(!s){this.room.off("heartbeat-report",this.onHeartbeatReport,this);return}this.room.listeners("heartbeat-report").includes(this.onHeartbeatReport)||this.room.on("heartbeat-report",this.onHeartbeatReport,this)}}onHeartbeatReport(e){Date.now()-this.lastEmitBadHealthTime<30*1e3||(e.msg_up_stream_info.msg_video_status.forEach(t=>{if(t.uint32_video_enc_fps&&t.uint32_video_capture_fps){let s=t.uint32_video_enc_fps/t.uint32_video_capture_fps;t.uint32_video_stream_type===2&&(this.mainFpsHealth=s)}if(t.uint32_video_codec_bitrate&&t.uint32_video_stream_type===2){let{localMainVideoTrack:s}=this.room;s&&(this.mainBitrateHealth=t.uint32_video_codec_bitrate/1e3/s.profile.bitrate)}}),this.log.debug(`mainBitrateHealth: ${this.mainBitrateHealth} mainFpsHealth: ${this.mainFpsHealth}`),this.mainBitrateHealth>.5&&(this.badMainBitrateHealthCount=0),this.mainFpsHealth>.9&&this.mainBitrateHealth<.5&&(this.badMainBitrateHealthCount++,this.badMainBitrateHealthCount>3&&(this.badMainBitrateHealthCount=0,this.lastEmitBadHealthTime=Date.now(),this.log.warn(`bad main bitrate health: ${this.mainBitrateHealth}`),this.emit("1",{isAux:!1}))))}destroy(){g.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};u(na,"EVENT_BAD_HEALTH","bad_health");var Ih=na;var Wt=(c=>(c.TRACK="track",c.DATA_CHANNEL_MESSAGE="data_channel_msg",c[c.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",c[c.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",c.RECONNECTED="spc-reconnected",c.RECONNECT_FAILED="spc-reconnect-failed",c.ERROR="error",c.SEI_MESSAGE="sei-message",c))(Wt||{}),Rh=0,yh=!1,Z_=new Set,ef=r=>Rh>2&&!yh&&Z_.size===0&&r,tf=1,ui=class extends Ch.default{constructor({signalChannel:e,room:t,enableCustomMessage:s}){super();u(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0});u(this,"currentState","DISCONNECTED");u(this,"_room");u(this,"_signalChannel");u(this,"_peerConnection",null);u(this,"_datachannel",null);u(this,"_enableCustomMessage");u(this,"_log");u(this,"_downlinkMIDMap",new Map);u(this,"_downlinkMIDUserIDMap",new Map);u(this,"_reconnectionTimer",-1);u(this,"reconnectionCount",0);u(this,"clientAbility");u(this,"_serverAbility",null);u(this,"addDownlinkQueue",new Set);u(this,"removeDownlinkQueue",new Set);u(this,"_parsedAnswer",null);u(this,"_updateSDPPromise",null);u(this,"_waitForPCConnectedPromise");u(this,"_waitForPCConnectedPromiseReject",null);u(this,"_isSDPLogged",!1);u(this,"enableInsertableStreams",!1);u(this,"insertableStreamsAbortMap",new Map);this._room=t,this._enableCustomMessage=s,this._signalChannel=e,this._log=I.createLogger({id:`spc${tf++}`,userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableSEI&&Or&&(this.enableInsertableStreams=!0),this._room.healthDetector.on("1",({isAux:o})=>{this.useHWEncoder(!1,o?7:2)})}get isH264EncodeSupported(){let e=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="h264")),e}addAbortController(e,t){var s;(s=this.insertableStreamsAbortMap.get(e))==null||s.abort("destory"),this.insertableStreamsAbortMap.set(e,t)}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="vp8")),e}get videoCodec(){var t,s;let e=(t=this._parsedAnswer)==null?void 0:t.media[1].rtp.find(o=>["h264","vp8"].includes(o.codec.toLowerCase()));return e?e.codec.toLowerCase():(s=this._serverAbility)!=null&&s.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var e;return(e=this._serverAbility)!=null&&e.video.decoders.find(t=>t.codec.toLowerCase()==="h264")?"h264":"vp8"}get isUsingH264(){return this.videoCodec==="h264"}get is42001fSupported(){return this.clientAbility?!!this.clientAbility.video.codecs.find(e=>e.fmtp.includes("42001f")):!1}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?_h(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}get isReconnecting(){return this.currentState==="RECONNECTING"||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let e=this._peerConnection.getSenders();return e.length===0?null:e[0].transport}initialize(){return _(this,null,function*(){var t;let e;try{return this._peerConnection=new RTCPeerConnection({encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"}),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let s=this._peerConnection.iceConnectionState;this._log.debug(`ice state: ${s}`),s==="checking"&&this.stat.iceStartTime===0?this.stat.iceStartTime=Date.now():s==="connected"&&this.stat.iceEndTime===0&&(this.stat.iceEndTime=Date.now())},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=s=>this.emit("track",s),this._enableCustomMessage&&(this._datachannel=this._peerConnection.createDataChannel(`${this._room.userId}dc`),this._datachannel.binaryType="arraybuffer",this._datachannel.onopen=()=>{this._log.info("datachannel open")},this._datachannel.onclose=()=>{this._log.warn("datachannel close")},this._datachannel.onmessage=s=>{let o=new Bd(s.data);this.emit("data_channel_msg",{data:o})},this._datachannel.onerror=s=>{this._log.warn("datachannel error",s)}),this._peerConnection.addTransceiver(h.AUDIO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),e=yield this._peerConnection.createOffer(),this.clientAbility=yield Eh(e.sdp,((t=this._room.scheduleResult.config)==null?void 0:t.remove264FromSDP)||!1),yield this.setOffer(e),this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:s}=this;!s||(this._log.debug(`dtls state: ${s.state}`),s.state==="connecting"&&this.stat.dtlsStartTime===0?this.stat.dtlsStartTime=Date.now():s.state==="connected"&&this.stat.dtlsEndTime===0&&(this.stat.dtlsEndTime=Date.now()))}),D.addSuccessEvent({key:521707}),this.clientAbility}catch(s){throw D.addFailedEvent({key:521707,error:s}),this._log.error(`initialize failed ${s}
|
|
93
|
-
offer: ${e==null?void 0:e.sdp}`),s}})}connect(e,t=!1){return _(this,null,function*(){try{if(this.currentState==="CONNECTED")return;let s=x(),o={type:"answer",sdp:gh({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(o),yield this.waitForPeerConnectionConnected(),t||D.addSuccessEvent({key:521703,cost:x()-s})}catch(s){let o=s instanceof b&&s.code===A.API_CALL_ABORTED;throw o||this._log.error(`connect failed: ${s}`,e),this.reset(),!o&&!this.isReconnecting&&(D.addFailedEvent({key:521703,error:s}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),s}})}reconnect(){return _(this,null,function*(){if(this._reconnectionTimer!==-1){this._log.warn("reconnect() is reconnecting, ignore current reconnection");return}if(!this._signalChannel.isConnected){this._log.warn("reconnect() wait signal channel is connected"),this._signalChannel.once(_e.CONNECTED,this.reconnect,this);return}try{this.reconnectionCount++,this._log.warn(`reconnect() trying [${this.reconnectionCount}]`),this.reset();let e=yield this.initialize(),t=yield this._signalChannel.sendWaitForResponse({command:q.REBUILD_PEER_CONNECTION,responseCommand:V.REBUILD_PEER_CONNECTION_RES,data:{ability:e},enableLog:!1});if(t.data.code!==0)throw new b({code:t.data.code,message:t.data.message});yield this.connect(t.data.data.ability,!0),D.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),g.emit(E.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(e){if(!this.isReconnecting)return;if(e!=null&&e.message.includes("timeout")){let t=kt(this.reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${t/1e3}s`),this._reconnectionTimer=window.setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},t)}else this._log.error(`reconnect() failed ${e==null?void 0:e.code} ${e}`),D.addFailedEvent({key:521704,error:e}),this.reconnectionCount>=qt()&&this._log.warn(`SDK has tried reconnect for ${qt()} times, but all failed, please check your network`),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}})}getPeerConnection(){return this._peerConnection}startReconnection(){return _(this,null,function*(){this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect()})}stopReconnection(){this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(_e.CONNECTED,this.reconnect,this))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&((e=this._peerConnection)==null?void 0:e.connectionState)===se.CLOSED&&this.startReconnection()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){let t=this._peerConnection.iceConnectionState,s=this.getDTLSTransportState();this._log.info(`connectionState: ${e.target.connectionState} ICE: ${t} DTLS: ${s}`),e.target.connectionState===se.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===se.FAILED||e.target.connectionState===se.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),(e.target.connectionState===se.CONNECTED||e.target.connectionState===se.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),g.emit(E.SINGLE_CONNECTION_STAT,{room:this._room,stat:{ice:this.stat.iceEndTime-this.stat.iceStartTime,dtls:this.stat.dtlsEndTime-this.stat.dtlsStartTime,peerConnection:this.stat.peerConnectionEndTime-this.stat.peerConnectionStartTime}}),this.logSelectedCandidate(),this.emitConnectionStateChangedEvent("CONNECTED"))}getDTLSTransportState(){if(!this._peerConnection)return nt;let e=null;return!Ri()||this._peerConnection.getSenders().length===0?nt:(e=this._peerConnection.getSenders()[0].transport,!$i()||this._peerConnection.getReceivers().length===0?nt:e?e.state:nt)}emitConnectionStateChangedEvent(e){e!==this.currentState&&(this.currentState==="RECONNECTING"&&e==="CONNECTING"||(this.emit(Wt.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return _(this,null,function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,s]of e)if(Ci(s)){let o=e.get(s.localCandidateId),n=e.get(s.remoteCandidateId);o&&(this._log.info(`local candidate: ${o.candidateType} ${o.protocol}:${o.ip||o.address}:${o.port} ${o.networkType||""} ${o.candidateType==="relay"?`relayProtocol:${o.relayProtocol}`:""}`),o.networkType&&Ha(o.networkType)),n&&this._log.info(`remote candidate: ${n.candidateType} ${n.protocol}:${n.ip||n.address}:${n.port}`);break}})}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise?this._waitForPCConnectedPromise:(this._waitForPCConnectedPromise=new Promise((e,t)=>{if(this.currentState==="CONNECTED")return e();this._waitForPCConnectedPromiseReject=t;let s=c=>{c.state==="CONNECTED"&&(clearTimeout(a),n(),e())},o=({room:c})=>{c===this._room&&(clearTimeout(a),n(),t(new b({code:A.API_CALL_ABORTED,message:L({key:M.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{g.off(E.LEAVE_SUCCESS,o,this),this.off(Wt.CONNECTION_STATE_CHANGED,s,this)},a=setTimeout(()=>{n();let c=new b({code:A.API_CALL_TIMEOUT,message:"connection timeout"});Rh+=1,ef(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),yh=!0,this.emit(Wt.FIREWALL_RESTRICTION)),t(c)},as);g.on(E.LEAVE_SUCCESS,o,this),this.on(Wt.CONNECTION_STATE_CHANGED,s,this)}),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally(()=>{this._waitForPCConnectedPromise=null,this._waitForPCConnectedPromiseReject=null}),this._waitForPCConnectedPromise)}waitForReconnected(){return this.isReconnecting?new Promise((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)}):Promise.resolve()}addDownlink(e){return _(this,null,function*(){if(this._log.info(`addDownlink(${e.userId}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise),this.updateLocalAndRemoteSDPConfig(e),this.addDownlinkQueue.size===0)try{yield this.updateSDP(),this._log.info(`addDownlink(${e.userId}) done`)}catch(t){this._log.error(`addDownlink(${e.userId}) failed ${t}`),yield this.startReconnection()}})}updateLocalAndRemoteSDPConfig({ssrc:e,userId:t,tinyId:s}){if(!this._peerConnection)return;this._log.info(`updateLocalAndRemoteSDPConfig ${t} ${JSON.stringify(e)}`);let o=this._peerConnection.getTransceivers().slice(4).filter(m=>m.direction==="inactive").slice(0,3).map(m=>(m.direction=h.TRANSCEIVER_DIRECTION_RECVONLY,Number(m.mid)));this._parsedAnswer||(this._parsedAnswer=ce(this._peerConnection.remoteDescription.sdp));let n=this._parsedAnswer.media.filter(m=>{var f;return(f=m.ssrcs)==null?void 0:f.find(R=>{var C;return(C=R.value)==null?void 0:C.includes(s)})}),a,c,d;if(n.length===3)a=n[0],c=n[1],d=n[2];else if(o.length===3)a=this._parsedAnswer.media.find(m=>Number(m.mid)===Number(o[0])),c=this._parsedAnswer.media.find(m=>Number(m.mid)===Number(o[1])),d=this._parsedAnswer.media.find(m=>Number(m.mid)===Number(o[2]));else if(o.length===0){this._peerConnection.addTransceiver(h.AUDIO,{direction:h.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_RECVONLY}),a=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let m=Vd({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:ce(this._peerConnection.localDescription.sdp),isDownlink:!0});c=JSON.parse(JSON.stringify(m)),d=JSON.parse(JSON.stringify(m)),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a),c.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(c),d.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(d)}a.direction=h.TRANSCEIVER_DIRECTION_SENDONLY;let l=`${s}-${e.audio}`;a.ssrcs=[{id:e.audio,attribute:"cname",value:`${l}`},{id:e.audio,attribute:"msid",value:`${l}-${h.MAIN} ${l}-audio`}],c.direction=h.TRANSCEIVER_DIRECTION_SENDONLY,c.ssrcs=[{id:e.video,attribute:"cname",value:`${l}`},{id:e.video,attribute:"msid",value:`${l}-${h.MAIN} ${l}-bigvideo`},{id:e.videoRtx,attribute:"cname",value:`${l}`},{id:e.videoRtx,attribute:"msid",value:`${l}-${h.MAIN} ${l}-bigvideo`}],c.ssrcGroups=[{semantics:"FID",ssrcs:`${e.video} ${e.videoRtx}`}],d.direction=h.TRANSCEIVER_DIRECTION_SENDONLY;let p=`${l}-aux`;d.ssrcs=[{id:e.auxiliary,attribute:"cname",value:p},{id:e.auxiliary,attribute:"msid",value:`${p} ${l}-aux${h.VIDEO}`},{id:e.auxiliaryRtx,attribute:"cname",value:`${p} ${l}-aux${h.VIDEO}`},{id:e.auxiliaryRtx,attribute:"msid",value:`${p} ${l}-aux${h.VIDEO}`}],d.ssrcGroups=[{semantics:"FID",ssrcs:`${e.auxiliary} ${e.auxiliaryRtx}`}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map(m=>m.mid).join(" ")),this._downlinkMIDMap.set(t,[a.mid,c.mid,d.mid]),this._downlinkMIDUserIDMap.set(a.mid,t),this._downlinkMIDUserIDMap.set(c.mid,t),this._downlinkMIDUserIDMap.set(d.mid,t)}removeDownlink(e){return _(this,null,function*(){if(!this._downlinkMIDMap.has(e)||!this._peerConnection)return;this._log.info(`removeDownlink(${e}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise);let t=this._downlinkMIDMap.get(e),s=!1;this._peerConnection.getTransceivers().forEach(o=>{t!=null&&t.includes(Number(o.mid))&&(s=!0,o.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=ce(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(o=>{t!=null&&t.includes(Number(o.mid))&&(s=!0,o.direction="inactive",o.ssrcs=[],o.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&s&&(yield this.updateSDP()),this._downlinkMIDMap.delete(e),t==null||t.forEach(o=>this._downlinkMIDUserIDMap.delete(o)),this._log.info(`removeDownlink(${e}) done`)})}setBandwidth(e){return _(this,null,function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:s,smallVideo:o,auxVideo:n}=e;try{if(Ps()){let a=this._peerConnection.getSenders().slice(0,4);for(let d=0;d<a.length;d++){let l=a[d],p;d===0&&t?p=t:d===1&&s?p=s:d===2&&o?p=o:d===3&&n&&(p=n),p&&(yield this.setSenderMaxBitrate(l,p))}let c=!1;s&&a[1].track&&(c=this.setStartBitrate(1,s)),n&&a[3].track&&(c=this.setStartBitrate(3,n)||c),c&&(yield this.updateSDP())}else yield this.setBandwidthBySDP(e);this._log.info(`setBandwidth ${JSON.stringify(e)}`)}catch(a){this._log.error(`failed to set bandwidth: ${a}`)}})}setStartBitrate(e,t){var s,o;return(s=this._peerConnection)!=null&&s.remoteDescription&&(this._parsedAnswer||(this._parsedAnswer=ce(this._peerConnection.remoteDescription.sdp)),(o=this._parsedAnswer.media[e])!=null&&o.fmtp[0])?(this._parsedAnswer.media[e].fmtp[0].config+=`;x-google-start-bitrate=${t>5e3?5e3:t}`,!0):!1}setSenderMaxBitrate(e,t){let s=e.getParameters();return(!s.encodings||s.encodings.length===0)&&(s.encodings=[{}]),t==="unlimited"?delete s.encodings[0].maxBitrate:s.encodings[0].maxBitrate=t*1e3,e.setParameters(s)}setBandwidthBySDP({audio:e,bigVideo:t,smallVideo:s,auxVideo:o}){if(!this._peerConnection||!this._peerConnection.localDescription)return;let n=ce(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=ce(this._peerConnection.remoteDescription.sdp));let a=ie?"TIAS":"AS";e&&(n.media[0].bandwidth=[{type:a,limit:ie?e*1e3:e}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:ie?e*1e3:e}]),t&&(n.media[1].bandwidth=[{type:a,limit:ie?t*1e3:t}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:ie?t*1e3:t}]),s&&(n.media[2].bandwidth=[{type:a,limit:ie?s*1e3:s}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:ie?s*1e3:s}]),o&&(n.media[3].bandwidth=[{type:a,limit:ie?o*1e3:o}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:ie?o*1e3:o}]);let c={type:"offer",sdp:He(n)};return this.updateSDP({localDescription:c})}setScaleResolutionDownBy(e,t){if(t===1)return;let s=e.getParameters();return(!s.encodings||s.encodings.length===0)&&(s.encodings=[{}]),s.encodings[0].scaleResolutionDownBy=t,e.setParameters(s)}updateSDP({localDescription:e}={}){if(!this._parsedAnswer)return Promise.resolve();let t=He(this._parsedAnswer);return this._updateSDPPromise=new Promise((s,o)=>_(this,null,function*(){var n,a;try{!e&&this._peerConnection&&(this._log.info("creating offer"),e=yield this._peerConnection.createOffer()),e&&(yield this.setOffer(e)),yield this.setAnswer({type:"answer",sdp:t}),this._updateSDPPromise=null,s()}catch(c){this._log.error(c),!this._isSDPLogged&&this._peerConnection&&(this._log.warn(`current offer: ${this.filterSDPDirection((n=this._peerConnection.localDescription)==null?void 0:n.sdp)}
|
|
92
|
+
}`,sa=class extends Ur{constructor(e,t){super(e,t.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,logger:e.log});l(this,"ready",!1);l(this,"_bgTexture");l(this,"_waterMarkTexture");l(this,"_lastMaskTexture");l(this,"_lastMaskFbo");l(this,"_textureValid",!1);l(this,"_selfieTextureValid",!1);l(this,"_selfieSegmentation");l(this,"wasm");l(this,"_prePrograme");l(this,"_segmentationMask");l(this,"_weixin",!1);t.selfieSegmentation&&(this._selfieSegmentation=t.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this)),this.init(t).catch(()=>this.context.destroy(new Error("selfie_segmentation init faild")))}init(e){return _(this,null,function*(){var o,n;let t=e.Wasm,s=this.context.ctx;if(this.wasm=new t.AllIn1(s),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.vbMode=e.bg==="blur"?1:e.bg instanceof HTMLImageElement?2:e.bg==="green"?3:0,e.waterMark){let{x:a,y:c,width:d,height:u}=e.waterMark;this.wasm.setWaterMark(a,c,d,u)}if(e.beautyParams){let{beauty:a,brightness:c,ruddy:d}=e.beautyParams;this.wasm.setBeauty(a,c,d,(o=this.context._canvas)==null?void 0:o.width,(n=this.context._canvas)==null?void 0:n.height)}if(this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),s.uniform1i(s.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(s.uniform1i(s.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(s.uniform1i(s.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),s.uniform1i(s.getUniformLocation(this.program,"lastMask"),4),this._weixin){let a=this.context.createShader(s.FRAGMENT_SHADER,W_),c=this.context.createShader(s.VERTEX_SHADER,G_);this._prePrograme=this.context.createProgram(c,a),s.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),s.uniform1i(s.getUniformLocation(this._prePrograme,"mask"),1)}this.ready=!0})}onPredict(e){var s;let t=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture))),this.useProgram(),this._weixin?this.useTexture():this==null||this._selfieSegmentation.bindTexture(),t.activeTexture(t.TEXTURE1),(s=this._selfieSegmentation)==null||s.bindTexture2d(e),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),this.useBufferFrame(),t.drawArrays(t.TRIANGLE_STRIP,0,4),this._segmentationMask=e,this.totalFrames++}render(e){var a,c,d;let t=this.context.ctx;if(K(this.image.getVideoPlaybackQuality)&&Pe){let p=this.image.getVideoPlaybackQuality().totalVideoFrames;if(this._totalFrames===p)return!1;this._totalFrames=p,this.dropFrames=this._totalFrames-this.totalFrames}let{videoWidth:s,videoHeight:o}=this.image;this.image.width=s,this.image.height=o;let n=!1;if(this.totalFrames)this._weixin?this.useTexture():this==null||this._selfieSegmentation.bindTexture(),n=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(this.program)this.useTexture();else return!1;n=this._textureValid,this._textureValid=!0}return this.width!==s||this.height!==o||!n?(this.resize(s,o),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.image)):t.texSubImage2D(t.TEXTURE_2D,0,0,0,t.RGBA,t.UNSIGNED_BYTE,this.image),this.ready&&(this._weixin&&(t.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask&&(t.activeTexture(t.TEXTURE1),(a=this._selfieSegmentation)==null||a.bindTexture2d(this._segmentationMask),t.bindFramebuffer(t.FRAMEBUFFER,this._lastMaskFbo||null)),t.drawArrays(t.TRIANGLE_STRIP,0,4),(c=this._selfieSegmentation)==null||c.bindTexture(),this._segmentationMask?t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,s,o):t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,s,o,0)),(d=this._selfieSegmentation)==null||d.send(s,o)),this.totalFrames||(t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this._bgTexture||null),t.activeTexture(t.TEXTURE3),t.bindTexture(t.TEXTURE_2D,this._waterMarkTexture||null),t.drawArrays(t.TRIANGLE_STRIP,0,4)),!1}close(){var t;super.close();let e=this.context.ctx;this._bgTexture&&e.deleteTexture(this._bgTexture),this._waterMarkTexture&&e.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&e.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&e.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&e.deleteProgram(this._prePrograme),(t=this.wasm)==null||t.close()}};var oa=class extends hh.EventEmitter{constructor(e){super();this.room=e;l(this,"videoContext");l(this,"_glVideoContext");l(this,"_2dVideoContext");l(this,"destination");l(this,"smallVideoContext");l(this,"smallDestination");l(this,"smallTrackSource");l(this,"smallImageSource");l(this,"_isMirror",!1);l(this,"cameraTrack");l(this,"cameraNode");l(this,"mirrorNode");l(this,"mixNode");l(this,"screenTrack");l(this,"screenNode");l(this,"selfModel",!1);l(this,"blurRadius",3);l(this,"arTrack");l(this,"Wasm");l(this,"waterMarkNode");l(this,"_waterMarkOption");l(this,"watermarkImageList",[]);l(this,"_beautyParams");l(this,"isUsingArTrack",!1);l(this,"_isMixScreen",!1);l(this,"_virtualBackground");l(this,"virtualBackgroundInstance");l(this,"_bgAssetPath");l(this,"log",I.createLogger({id:"vm"}));l(this,"_checkId",0);l(this,"_use2d",!1);l(this,"_autoSwitchRenderMode",!0);l(this,"_selfieSegmentation");l(this,"_seiEncodeProcessor");l(this,"_seiDecodeProcessor");l(this,"seiWorker");e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new Fe({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(e){if(this._autoSwitchRenderMode=e==="auto",this._autoSwitchRenderMode)return;let t=e==="2d";this._use2d!==t&&(this._use2d=t,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new Fe({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this.sendCreateResult("videoCtx2d",this._2dVideoContext.ctx?void 0:new Error("create 2d context failed")),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new ye({frameRate:15,logger:this.log,name:"m"});else if(this._glVideoContext.available)return this._glVideoContext;try{this._glVideoContext.create(),this.sendCreateResult(),this._glVideoContext.on("unavailable",(e,t)=>{this.emit("error",{reason:e,error:t}),this.log.warn("video context unavailable",e,t),this.sendCreateResult("videoCtxGl",t||new Error(e)),this.update()})}catch(e){this.emit("error",{reason:"create",error:e}),this.sendCreateResult("videoCtxGl",e)}return this._glVideoContext}enablePrintDetail(e=2e3){this._checkId=re.run(Bi,()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}destroy(){var e,t;(e=this._2dVideoContext)==null||e.destroy(),(t=this._glVideoContext)==null||t.destroy(),this.smallVideoContext.destroy(),re.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(Cr||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",t){let s=e==="videoCtxGl"?512700:512701;t?D.addFailedEvent({key:s,error:t}):D.addSuccessEvent({key:s})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else if(t)if(this._use2d)this.clear();else return!0;else return!0}else this.clear(),this._use2d=!0;return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var e;return(e=this.smallDestination)==null?void 0:e.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var e;return(e=this.cameraTrack)==null?void 0:e.mediaTrack}initVirtualBackground(e){return this._selfieSegmentation=e,this._selfieSegmentation.changeModel()}_setMainOutput(e){var t;try{let s=this.cameraTrack,{small:o,settings:n,player:a}=s;o?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new On(this.smallVideoContext,o)),this.smallVideoContext.frameRate=o.frameRate,this.smallDestination.resolution=o,e?(this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.connect(this.smallDestination))):(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource?this.smallTrackSource.replaceTrack(this.initialTrack):(this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource"),this.smallTrackSource.width=n.width,this.smallTrackSource.height=n.height,this.smallTrackSource.connect(this.smallDestination)))):this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource),Cr&&a.setCanvas(e);let c=e&&((t=this.destination)==null?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),c=this.arTrack),this._selfieSegmentation&&e&&!this._use2d&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),this.log.info(`set main output ${c?c.label:"no output track"}`),s.setOutputMediaStreamTrack(c)}catch(s){this.log.error("set main output failed",s)}}update(){return _(this,null,function*(){var s,o;if(!this.cameraTrack||!this.cameraTrack.mediaTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:e,profile:t}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination",logger:this.log})),this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(e.width,e.height))):(this.cameraNode&&this.cameraNode.close(),this.destination||(this.destination=new Dn(this.videoContext,{name:"mainDestination",logger:this.log})),this.cameraNode=new sa(this.videoContext,{input:this.cameraTrack.mediaTrack,mirror:this._isMirror,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,selfieSegmentation:this._selfieSegmentation,Wasm:this.Wasm}),this.cameraNode.connect(this.destination)),this.videoContext.frameRate=t.frameRate,this._use2d){let n=this.cameraNode;n.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new ia(this.videoContext)),n=n.connect(this.mirrorNode),n.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new ra(this.videoContext),n.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption&&(this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y),(s=this.waterMarkNode)==null||s.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource")),(o=this.screenNode)==null||o.connect(this.mixNode,{zIndex:0}),n=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)),n.connect(this.destination)}return this.log.info(`update ${this._use2d?"2d":"webgl"}`),this._setMainOutput(this.videoContext._canvas)})}changeInput(e){var t,s,o,n;if(e instanceof ze)return this.log.info("change screen input",(t=e.mediaTrack)==null?void 0:t.label),this.setScreenTrack(e);if(e instanceof ue)return this.log.info("change video input",(s=e.mediaTrack)==null?void 0:s.label),this.setCameraTrack(e);if(e instanceof St){this.log.info("change remote input",(o=e.mediaTrack)==null?void 0:o.label);let a=e.mediaTrack;return this._seiDecodeProcessor&&(e.pipeline[1]=this._seiDecodeProcessor),e.setOutputMediaStreamTrack(a)}this.log.warn("change unknown input",(n=e.mediaTrack)==null?void 0:n.label)}configPipeline(e){e instanceof St&&this._seiDecodeProcessor&&(e.pipeline[1]=this._seiDecodeProcessor)}removeInput(e){var t;e instanceof ze?((t=this.screenNode)==null||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof ue?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof St&&e.source&&e.source.context.destroy()}setCameraTrack(e){return _(this,null,function*(){this.cameraTrack=e,this._seiEncodeProcessor&&(this.cameraTrack.pipeline[0]=this._seiEncodeProcessor),this.update()})}setScreenTrack(e){return this.screenTrack=e,this._seiEncodeProcessor&&(this.screenTrack.pipeline[0]=this._seiEncodeProcessor),this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,t){return _(this,null,function*(){let s=document.createElement("canvas");t&&e&&(s.height=t,s.width=e);let o=s.getContext("2d");if(!o)throw new b({code:A.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((n,a)=>n.zIndex-a.zIndex),this.watermarkImageList.forEach(({image:n,x:a,y:c,width:d,height:u})=>{o.drawImage(n,a,c,d,u)}),Ms(s.toDataURL())})}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some(o=>o.imageUrl===e.imageUrl&&o.height===e.height&&o.width===e.width&&o.x===e.x&&o.y===e.y&&o.type===e.type&&o.zIndex===e.zIndex)||((t==="mute"||t==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(o=>o.type!==t)),this.watermarkImageList.push(e))}setBeautyParams(e){return _(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return _(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return _(this,null,function*(){let t;try{t=yield Ms((e==null?void 0:e.imageElement)||e.imageUrl)}catch(u){throw new b({code:A.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:s=0,y:o=0,width:n=t.width,height:a=t.height,type:c="watermark",zIndex:d=2}=e;this.pushWaterMarkImageList({x:s,y:o,width:n,height:a,image:t,zIndex:d,type:c,imageUrl:e.imageUrl}),yield this.freshWatermark(),this.log.info("set watermark",JSON.stringify(this.watermarkImageList))})}deleteWatermark(e="watermark"){return _(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(t=>t.type!==e),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList)),yield this.freshWatermark()})}freshWatermark(){return _(this,null,function*(){var t,s,o;(t=this.waterMarkNode)==null||t.close(),delete this.waterMarkNode,delete this._waterMarkOption;let e=yield this.getWatermarkImage((s=this.cameraTrack)==null?void 0:s.settings.width,(o=this.cameraTrack)==null?void 0:o.settings.height);this._waterMarkOption={x:0,y:0,width:e.width,height:e.height,image:e},this.update()})}setVirtualBackground(e){return _(this,null,function*(){if(!e)this._virtualBackground=void 0;else{if(this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=e.assetPath,e.type==="image"?this._virtualBackground=yield Ms(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type)}this.log.info(`${this._virtualBackground?"start":"stop"} virtual background, ${(e==null?void 0:e.type)||""}, ${this.blurRadius||""}`),this.update()})}get mixScreen(){return this._isMixScreen}set mixScreen(e){var t;this._isMixScreen=e,this._isMixScreen||((t=this.screenNode)==null||t.close(),delete this.screenNode),this.update()}set mirror(e){var t;this._isMirror!==e&&(this._isMirror=e,this._isMirror||((t=this.mirrorNode)==null||t.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return _(this,null,function*(){var e;!((e=this.cameraTrack)!=null&&e.mediaTrack)||(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))})}disableAr(){var e;this.isUsingArTrack=!1,(e=this.arTrack)==null||e.stop(),this.arTrack=void 0,this.update()}clear(){var e;(e=this.videoContext)==null||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}enableSEI({encoder:e,decoder:t,seiWorker:s}){s?this.seiWorker=s:(this._seiEncodeProcessor=e,this._seiDecodeProcessor=t,this.cameraTrack&&(this.cameraTrack.pipeline[0]=this._seiEncodeProcessor),this.screenTrack&&(this.screenTrack.pipeline[0]=this._seiEncodeProcessor))}disableSEI(){var e;(e=this.seiWorker)==null||e.terminate(),delete this.seiWorker,delete this._seiEncodeProcessor,delete this._seiDecodeProcessor,this.cameraTrack&&(this.cameraTrack.pipeline[0]=void 0),this.screenTrack&&(this.screenTrack.pipeline[0]=void 0)}};var J_=0;var na=class extends F{constructor(e){super("room");this.seq=++J_;this.role="anchor";this.joinParams=null;this.localTracks=new Set;this.enableAutoPlayDialog=!0;this.autoReceiveAudio=!0;this.autoReceiveVideo=!0;this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null};this._isUsingCachedSchedule=!1;this._log=I.createLogger({id:`r${this.seq}`});this._joinedTimestamp=0;this.isDestroyed=!1;this.useStringRoomId=!!e.useStringRoomId,de(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),de(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),de(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new dh({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new lh({room:this}),this.badCaseDetector=new uh({room:this}),this.audioManager=new Nn(this),this.videoManager=new oa(this)}get isMainStreamPublished(){for(let e of this.localTracks)if(e.mediaType&4)return!0;return!1}get isAuxStreamPublished(){for(let e of this.localTracks)if(e.mediaType&2)return!0;return!1}get hasAuxStream(){for(let e of this.remotePublishedUserMap.values())if(e.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainVideoTrack(){for(let e of this.localTracks)if(e.mediaType&4)return e;return null}get localAuxVideoTrack(){for(let e of this.localTracks)if(e.mediaType&2)return e;return null}getLogger(){return this._log}get isJoining(){return this.state.toString()==="joining"}get isJoined(){return this.state==="joined"}get isLeft(){return this.state==="left"}addTrack(e){return _(this,null,function*(){return this.publish(e)})}removeTrack(e){return _(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return _(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(z(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(Je(e)){let{websocketProxy:t,webtransportProxy:s,loggerProxy:o,scheduleProxy:n,unifiedProxy:a}=e;this.proxy_ws=t,this.proxy_wt=s,this.proxy_unified=a,a?(Ha([a,a]),Pi(`https://${a}`)):(o&&Pi(o),n&&Ha(n))}g.once(E.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:Ci.main,sched_back_domain:Ci.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return _(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(t=>{e[t.userId]=t.remoteAudioTrack.stat}),e})}getTransportStats(){return _(this,null,function*(){var t;let e={rtt:((t=this.quality)==null?void 0:t.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let s of this.quality.downlinkInfo)e.downlinksRTT[s.userId]=s.rtt;return e})}getRemoteVideoStats(){return _(this,arguments,function*(e="main"){let t={};return this.remotePublishedUserMap.forEach(s=>{let o=e==="auxiliary"?s.remoteAuxiliaryTrack:s.remoteVideoTrack;t[s.userId]=o.stat}),t})}checkDestroy(){if(this.isDestroyed)throw new b({code:A.INVALID_OPERATION,message:L({key:M.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Ae.INVALID_DESTROY),new b({code:A.INVALID_OPERATION,message:L({key:M.INVALID_DESTROY})});this._log.info("destroy room"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this.isDestroyed=!0,g.emit(E.ROOM_DESTROY,{room:this})}schedule(e,t){return _(this,null,function*(){var o,n;let s=x();try{let{isCached:a,result:c,detailCost:d}=yield pl({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:Re,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:t,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=a,this._log.info(`schedule cache:${+a} ${_t(c,{keysToExclude:["username","credential"]})}`),a&&g.once(E.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=N(N({},this.scheduleResult),c),ee((o=c.config)==null?void 0:o.retryCount)&&Sa(c.config.retryCount),z((n=c.config)==null?void 0:n.loggerDomain)&&Pi(c.config.loggerDomain),g.emit(E.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:d}),D.addSuccessEvent({key:521700,cost:x()-s,split:50})}catch(a){throw D.addFailedEvent({key:521700,error:a}),a}})}};var ph=Se(Ne(),1);var mh=Symbol("instance"),CL=Symbol("abortCtrl"),wd=Symbol("cacheResult"),ho=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,_o.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},mo=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function j_(r){return typeof r=="object"&&r&&"then"in r}var po=new Map;function Vd(r,i,e={}){return(t,s,o)=>{let n=e.action||s;if(!e.context){let c=po.get(t)||[];po.has(t)||po.set(t,c),c.push({from:r,to:i,action:n})}let a=o.value;o.value=function(...c){let d=this;if(e.context&&(d=ne.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===i)return d[wd];d.state instanceof ho&&d.state.action==e.abortAction&&d.state.abort(d);let u=null;if(Array.isArray(r)?r.length==0?d.state instanceof ho&&d.state.abort(d):(typeof d.state!="string"||!r.includes(d.state))&&(u=new mo(d._state,`${d.name} ${n} to ${i} failed: current state ${d._state} not in from config`)):r!==d.state&&(u=new mo(d._state,`${d.name} ${n} to ${i} failed: current state ${d._state} not from ${r}`)),u)if(e.fail)e.fail.call(this,u);else{if(e.ignoreError)return u;throw u}let p=d.state,m=new ho(p,i,n);_o.call(d,m);let f=C=>{var v;return d[wd]=C,m.aborted||(_o.call(d,i),(v=e.success)===null||v===void 0||v.call(this,d[wd])),C},R=C=>{let v=C instanceof Error?C.message:String(C);if(_o.call(d,p,C),e.fail)e.fail.call(this,new mo(d._state,`action '${n}' failed :${v}`,C instanceof Error?C:new Error(v)));else{if(e.ignoreError)return C;throw C}};try{let C=a.apply(this,c);return j_(C)?C.then(f).catch(R):f(C)}catch(C){R(C)}}}}var q_=(()=>typeof window!="undefined"&&window.__AFSM__?(e,t)=>{window.dispatchEvent(new CustomEvent(e,{detail:t}))}:typeof importScripts!="undefined"?(e,t)=>{postMessage({type:e,payload:t})}:()=>{})();function _o(r,i){let e=this._state;this._state=r;let t=r.toString();r&&this.emit(t,e),this.emit(ne.STATECHANGED,r,e,i),this.updateDevTools({value:r,old:e,err:i instanceof Error?i.message:String(i)})}var ne=class extends ph.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=ne.INIT,i||(i=Date.now().toString(36)),t?Object.setPrototypeOf(this,t):t=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let s=t[mh];s?this.name=s.name+"-"+s.count++:t[mh]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=po.get(i)||[],t=new Set,s=[],o=[],n=new Set,a=Object.getPrototypeOf(i);po.has(a)&&(a.stateDiagram.forEach(d=>t.add(d)),a.allStates.forEach(d=>n.add(d))),e.forEach(({from:d,to:u,action:p})=>{typeof d=="string"?s.push({from:d,to:u,action:p}):d.length?d.forEach(m=>{s.push({from:m,to:u,action:p})}):o.push({to:u,action:p})}),s.forEach(({from:d,to:u,action:p})=>{n.add(d),n.add(u),n.add(p+"ing"),t.add(`${d} --> ${p}ing : ${p}`),t.add(`${p}ing --> ${u} : ${p} \u{1F7E2}`),t.add(`${p}ing --> ${d} : ${p} \u{1F534}`)}),o.forEach(({to:d,action:u})=>{t.add(`${u}ing --> ${d} : ${u} \u{1F7E2}`),n.forEach(p=>{p!==d&&t.add(`${p} --> ${u}ing : ${u}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:n}}),c}static get(i){let e;return typeof i=="string"?(e=ne.instances.get(i),e||ne.instances.set(i,e=new ne(i,void 0,Object.create(ne.prototype)))):(e=ne.instances2.get(i),e||ne.instances2.set(i,e=new ne(i.constructor.name,void 0,Object.create(ne.prototype)))),e}static getState(i){var e;return(e=ne.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){q_(ne.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){_o.call(this,i)}};ne.STATECHANGED="stateChanged";ne.UPDATEAFSM="updateAFSM";ne.INIT="[*]";ne.ON="on";ne.OFF="off";ne.instances=new Map;ne.instances2=new WeakMap;var Ch=Se(Ne());var Ud=Se(bd());var _h=r=>{let i=ce(r),e={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return i.media.forEach((t,s)=>{var o;if(t.ssrcs&&!T(t.ssrcs[0].id)){let n=Number(t.ssrcs[0].id),a=Number((o=t.ssrcs.filter(c=>c.attribute==="cname")[1])==null?void 0:o.id);switch(s){case 0:e.audioSsrc=n;break;case 1:e.bigVideoSsrc=n,e.bigVideoRtxSsrc=a;break;case 2:e.smallVideoSsrc=n,e.smallVideoRtxSsrc=a;break;case 3:e.auxVideoSsrc=n,e.auxVideoRtxSsrc=a;break}}}),e};function fh(r){var e;let i=[];for(let t=0;t<r.rtp.length;t++){if(["rtx","red","ulpfec"].includes(r.rtp[t].codec))continue;let s=r.fmtp.filter(o=>o.payload===r.rtp[t].payload)[0];i.push({payload:r.rtp[t].payload,codec:r.rtp[t].codec,fmtp:s?s.config:"",rate:r.rtp[t].rate,rtx:((e=r.rtp[t+1])==null?void 0:e.codec)==="rtx"?r.rtp[t+1].payload:0,rtcpFb:((r==null?void 0:r.rtcpFb)||[]).filter(o=>o.payload===r.rtp[t].payload).map(({type:o,subtype:n})=>({id:o,params:n?[n]:[]}))})}return i}function X_(){return _(this,null,function*(){let r=new RTCPeerConnection;r.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_RECVONLY});let i=yield r.createOffer();if(!i.sdp)return[];let e=ce(i.sdp),t=fh(e.media[0]);return r.close(),t})}var Eh=(r,i)=>_(void 0,null,function*(){var c;let e=ce(r),t={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:!1};t.ice.ufrag=String(e.media[0].iceUfrag),t.ice.password=e.media[0].icePwd||"",e.fingerprint&&(t.dtls.hash=e.fingerprint.type,t.dtls.fingerprint=e.fingerprint.hash,t.dtls.setup=e.setup||""),e.media[0].fingerprint&&(t.dtls.hash=e.media[0].fingerprint.type,t.dtls.fingerprint=e.media[0].fingerprint.hash),t.dtls.setup=e.media[0].setup||"";let s=e.media[0],o=e.media[1];s.ext&&(t.audio.extensions=s.ext.map(d=>({id:d.value,uri:d.uri}))),o.ext&&(t.video.extensions=o.ext.map(d=>({id:d.value,uri:d.uri})));let n={codec:s.rtp[0].codec,fmtp:s.fmtp[0].config,payload:s.fmtp[0].payload,rate:s.rtp[0].rate,channel:s.rtp[0].encoding,rtcpFb:[],rtx:0};(c=s.rtcpFb)==null||c.forEach(({payload:d,type:u,subtype:p})=>{if(d===n.payload){let m={id:u,params:[]};p&&m.params.push(p),n.rtcpFb.push(m)}}),t.audio.codecs.push(n);let a=["h264","vp8"];return i&&a.shift(),t.video.codecs=[...fh(o)].filter(d=>a.includes(d.codec.toLocaleLowerCase())),t.video.decoders=(yield X_()).filter(d=>["h264","vp8"].includes(d.codec.toLocaleLowerCase())),t}),gh=({serverAbility:r,clientAbility:i,offerSDP:e,enableCustomMessage:t})=>{let s=ce(e),o={extmapAllowMixed:"extmap-allow-mixed",groups:s.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},n={candidates:r.candidates.map(a=>({component:1,foundation:"1",generation:0,ip:a.ip,port:a.port,priority:a.priority,transport:a.foundation,type:a.type})),connection:{version:4,ip:"0.0.0.0"},direction:h.TRANSCEIVER_DIRECTION_RECVONLY,ext:r.audio.extensions.map(a=>({value:a.id,uri:a.uri})),fingerprint:{type:r.dtls.hash,hash:r.dtls.fingerprint},fmtp:[{payload:r.audio.codecs[0].payload,config:r.audio.codecs[0].fmtp}],icePwd:r.ice.password,iceUfrag:r.ice.ufrag,mid:"0",payloads:String(r.audio.codecs[0].payload),port:s.media[0].port,protocol:s.media[0].protocol,type:h.AUDIO,setup:r.dtls.setup,rtcpFb:r.audio.codecs[0].rtcpfb.map(a=>({payload:r.audio.codecs[0].payload,type:a.id,subtype:a.params[0]})),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:r.audio.codecs[0].payload,codec:r.audio.codecs[0].codec,rate:r.audio.codecs[0].rate,encoding:r.audio.codecs[0].channels}]};return o.media.push(n),[1,2,3].forEach(a=>{o.media.push(Bd({mid:a,serverAbility:r,clientAbility:i,parsedOffer:s}))}),t&&o.media.push(s.media.find(a=>a.mid==="dc")),He(o)},Bd=({mid:r,serverAbility:i,clientAbility:e,parsedOffer:t,isDownlink:s=!1})=>{let o={candidates:i.candidates.map(n=>({component:1,foundation:"1",generation:0,ip:n.ip,port:n.port,priority:n.priority,transport:n.foundation,type:n.type})),connection:{version:4,ip:"0.0.0.0"},direction:h.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map(n=>({value:n.id,uri:n.uri})),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(r),payloads:"",port:t.media[0].port,protocol:t.media[0].protocol,type:h.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(s)(i.video.decoders||i.video.codecs).forEach(n=>{ar(o,n)});else{let n=i.video.codecs.findIndex(c=>c.codec.toLowerCase()===(i.useVp8?"vp8":"h264")),a=i.video.codecs[n]||e.video.codecs[0];ar(o,a)}return o},ar=(r,i)=>{r.payloads=`${r.payloads} ${i.payload}`.trim(),r.fmtp.push({payload:i.payload,config:i.fmtp}),r.rtcpFb=[...r.rtcpFb||[],...(i.rtcpfb||i.rtcpFb).map(e=>({payload:i.payload,type:e.id,subtype:e.params[0]}))],r.rtp.push({payload:i.payload,codec:i.codec.toUpperCase(),rate:i.rate}),i.rtx&&(r.payloads=`${r.payloads} ${i.rtx}`,r.fmtp.push({payload:i.rtx,config:`apt=${i.payload}`}),r.rtp.push({payload:i.rtx,codec:"rtx",rate:i.rate}))};function Q_(r){let i=new Set(["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.ext&&(r.ext=r.ext.filter(e=>!i.has(e.uri)))}function z_(r){if(!r.rtcpFb)return;let i=[];r.rtcpFb.forEach((e,t)=>{var s;i.push(e),r.rtcpFb&&((s=r.rtcpFb[t+1])==null?void 0:s.payload)!==e.payload&&e.type!=="rrtr"&&i.push({payload:e.payload,type:"rrtr"})}),r.rtcpFb=i}function Y_(r){r.type===h.VIDEO&&r.fmtp&&r.fmtp.forEach(i=>{i.config.includes("apt")||(i.config+=";sps-pps-idr-in-keyframe=1")})}function K_(r){r.type===h.AUDIO&&r.fmtp&&r.fmtp.forEach(i=>{i.config+=";sprop-stereo=1;stereo=1"})}var Th=(r,i,e)=>{let t=Ud.default.parse(r);return t.media.forEach((s,o)=>{var n;(s.type===h.AUDIO||s.type===h.VIDEO)&&(z_(s),Y_(s),K_(s),Q_(s),s.type===h.VIDEO&&(o<4?(s.payloads="",s.fmtp=[],s.rtp=[],s.rtcpFb=[],i.video.codecs.forEach(a=>ar(s,a))):e&&(s.payloads="",s.fmtp=[],s.rtp=[],s.rtcpFb=[],(e.video.decoders||e.video.codecs).forEach(a=>ar(s,a))))),((n=s.payloads)==null?void 0:n.includes("datachannel"))&&t.groups&&s.mid&&(t.groups[0].mids=t.groups[0].mids.replace(s.mid,"dc"),s.mid="dc")}),Ud.default.write(t)};var Sh=Se(Ne());var aa=class extends Sh.EventEmitter{constructor(e){super();this.room=e;l(this,"mainFpsHealth",1);l(this,"mainBitrateHealth",1);l(this,"badMainBitrateHealthCount",0);l(this,"lastEmitBadHealthTime",0);l(this,"log");!pe&&Pe&&g.on("262",this.onVideoCodecChanged,this),this.log=e.getLogger().createChild({id:"h-d"})}onVideoCodecChanged({remoteUserId:e,streamType:t,isHWCodec:s,codec:o}){if(!(e||t===7||o!=="h264")){if(!s){this.room.off("heartbeat-report",this.onHeartbeatReport,this);return}this.room.listeners("heartbeat-report").includes(this.onHeartbeatReport)||this.room.on("heartbeat-report",this.onHeartbeatReport,this)}}onHeartbeatReport(e){Date.now()-this.lastEmitBadHealthTime<30*1e3||(e.msg_up_stream_info.msg_video_status.forEach(t=>{if(t.uint32_video_enc_fps&&t.uint32_video_capture_fps){let s=t.uint32_video_enc_fps/t.uint32_video_capture_fps;t.uint32_video_stream_type===2&&(this.mainFpsHealth=s)}if(t.uint32_video_codec_bitrate&&t.uint32_video_stream_type===2){let{localMainVideoTrack:s}=this.room;s&&(this.mainBitrateHealth=t.uint32_video_codec_bitrate/1e3/s.profile.bitrate)}}),this.log.debug(`mainBitrateHealth: ${this.mainBitrateHealth} mainFpsHealth: ${this.mainFpsHealth}`),this.mainBitrateHealth>.5&&(this.badMainBitrateHealthCount=0),this.mainFpsHealth>.9&&this.mainBitrateHealth<.5&&(this.badMainBitrateHealthCount++,this.badMainBitrateHealthCount>3&&(this.badMainBitrateHealthCount=0,this.lastEmitBadHealthTime=Date.now(),this.log.warn(`bad main bitrate health: ${this.mainBitrateHealth}`),this.emit("1",{isAux:!1}))))}destroy(){g.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};l(aa,"EVENT_BAD_HEALTH","bad_health");var Ih=aa;var Jt=(c=>(c.TRACK="track",c.DATA_CHANNEL_MESSAGE="data_channel_msg",c[c.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",c[c.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",c.RECONNECTED="spc-reconnected",c.RECONNECT_FAILED="spc-reconnect-failed",c.ERROR="error",c.SEI_MESSAGE="sei-message",c))(Jt||{}),Rh=0,yh=!1,Z_=new Set,ef=r=>Rh>2&&!yh&&Z_.size===0&&r,tf=1,hi=class extends Ch.default{constructor({signalChannel:e,room:t,enableCustomMessage:s}){super();l(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0});l(this,"currentState","DISCONNECTED");l(this,"_room");l(this,"_signalChannel");l(this,"_peerConnection",null);l(this,"_datachannel",null);l(this,"_enableCustomMessage");l(this,"_log");l(this,"_downlinkMIDMap",new Map);l(this,"_downlinkMIDUserIDMap",new Map);l(this,"_reconnectionTimer",-1);l(this,"reconnectionCount",0);l(this,"clientAbility");l(this,"_serverAbility",null);l(this,"addDownlinkQueue",new Set);l(this,"removeDownlinkQueue",new Set);l(this,"_parsedAnswer",null);l(this,"_updateSDPPromise",null);l(this,"_waitForPCConnectedPromise");l(this,"_waitForPCConnectedPromiseReject",null);l(this,"_isSDPLogged",!1);l(this,"enableInsertableStreams",!1);l(this,"insertableStreamsAbortMap",new Map);this._room=t,this._enableCustomMessage=s,this._signalChannel=e,this._log=I.createLogger({id:`spc${tf++}`,userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableSEI&&kr&&(this.enableInsertableStreams=!0),this._room.healthDetector.on("1",({isAux:o})=>{this.useHWEncoder(!1,o?7:2)})}get isH264EncodeSupported(){let e=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(e=e&&!!this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="h264")),e}addAbortController(e,t){var s;(s=this.insertableStreamsAbortMap.get(e))==null||s.abort("destory"),this.insertableStreamsAbortMap.set(e,t)}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="vp8")),e}get videoCodec(){var t,s;let e=(t=this._parsedAnswer)==null?void 0:t.media[1].rtp.find(o=>["h264","vp8"].includes(o.codec.toLowerCase()));return e?e.codec.toLowerCase():(s=this._serverAbility)!=null&&s.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var e;return(e=this._serverAbility)!=null&&e.video.decoders.find(t=>t.codec.toLowerCase()==="h264")?"h264":"vp8"}get isUsingH264(){return this.videoCodec==="h264"}get is42001fSupported(){return this.clientAbility?!!this.clientAbility.video.codecs.find(e=>e.fmtp.includes("42001f")):!1}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?_h(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}get isReconnecting(){return this.currentState==="RECONNECTING"||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let e=this._peerConnection.getSenders();return e.length===0?null:e[0].transport}initialize(){return _(this,null,function*(){var t;let e;try{return this._peerConnection=new RTCPeerConnection({encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"}),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let s=this._peerConnection.iceConnectionState;this._log.debug(`ice state: ${s}`),s==="checking"&&this.stat.iceStartTime===0?this.stat.iceStartTime=Date.now():s==="connected"&&this.stat.iceEndTime===0&&(this.stat.iceEndTime=Date.now())},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=s=>this.emit("track",s),this._enableCustomMessage&&(this._datachannel=this._peerConnection.createDataChannel(`${this._room.userId}dc`),this._datachannel.binaryType="arraybuffer",this._datachannel.onopen=()=>{this._log.info("datachannel open")},this._datachannel.onclose=()=>{this._log.warn("datachannel close")},this._datachannel.onmessage=s=>{let o=new Fd(s.data);this.emit("data_channel_msg",{data:o})},this._datachannel.onerror=s=>{this._log.warn("datachannel error",s)}),this._peerConnection.addTransceiver(h.AUDIO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_SENDONLY}),e=yield this._peerConnection.createOffer(),this.clientAbility=yield Eh(e.sdp,((t=this._room.scheduleResult.config)==null?void 0:t.remove264FromSDP)||!1),yield this.setOffer(e),this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:s}=this;!s||(this._log.debug(`dtls state: ${s.state}`),s.state==="connecting"&&this.stat.dtlsStartTime===0?this.stat.dtlsStartTime=Date.now():s.state==="connected"&&this.stat.dtlsEndTime===0&&(this.stat.dtlsEndTime=Date.now()))}),D.addSuccessEvent({key:521707}),this.clientAbility}catch(s){throw D.addFailedEvent({key:521707,error:s}),this._log.error(`initialize failed ${s}
|
|
93
|
+
offer: ${e==null?void 0:e.sdp}`),s}})}connect(e,t=!1){return _(this,null,function*(){try{if(this.currentState==="CONNECTED")return;let s=x(),o={type:"answer",sdp:gh({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(o),yield this.waitForPeerConnectionConnected(),t||D.addSuccessEvent({key:521703,cost:x()-s})}catch(s){let o=s instanceof b&&s.code===A.API_CALL_ABORTED;throw o||this._log.error(`connect failed: ${s}`,e),this.reset(),!o&&!this.isReconnecting&&(D.addFailedEvent({key:521703,error:s}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),s}})}reconnect(){return _(this,null,function*(){if(this._reconnectionTimer!==-1){this._log.warn("reconnect() is reconnecting, ignore current reconnection");return}if(!this._signalChannel.isConnected){this._log.warn("reconnect() wait signal channel is connected"),this._signalChannel.once(_e.CONNECTED,this.reconnect,this);return}try{this.reconnectionCount++,this._log.warn(`reconnect() trying [${this.reconnectionCount}]`),this.reset();let e=yield this.initialize(),t=yield this._signalChannel.sendWaitForResponse({command:j.REBUILD_PEER_CONNECTION,responseCommand:V.REBUILD_PEER_CONNECTION_RES,data:{ability:e},enableLog:!1});if(t.data.code!==0)throw new b({code:t.data.code,message:t.data.message});yield this.connect(t.data.data.ability,!0),D.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),g.emit(E.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(e){if(!this.isReconnecting)return;if(e!=null&&e.message.includes("timeout")){let t=Lt(this.reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${t/1e3}s`),this._reconnectionTimer=window.setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},t)}else this._log.error(`reconnect() failed ${e==null?void 0:e.code} ${e}`),D.addFailedEvent({key:521704,error:e}),this.reconnectionCount>=Xt()&&this._log.warn(`SDK has tried reconnect for ${Xt()} times, but all failed, please check your network`),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}})}getPeerConnection(){return this._peerConnection}startReconnection(){return _(this,null,function*(){this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect()})}stopReconnection(){this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(_e.CONNECTED,this.reconnect,this))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&((e=this._peerConnection)==null?void 0:e.connectionState)===se.CLOSED&&this.startReconnection()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){let t=this._peerConnection.iceConnectionState,s=this.getDTLSTransportState();this._log.info(`connectionState: ${e.target.connectionState} ICE: ${t} DTLS: ${s}`),e.target.connectionState===se.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===se.FAILED||e.target.connectionState===se.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),(e.target.connectionState===se.CONNECTED||e.target.connectionState===se.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),g.emit(E.SINGLE_CONNECTION_STAT,{room:this._room,stat:{ice:this.stat.iceEndTime-this.stat.iceStartTime,dtls:this.stat.dtlsEndTime-this.stat.dtlsStartTime,peerConnection:this.stat.peerConnectionEndTime-this.stat.peerConnectionStartTime}}),this.logSelectedCandidate(),this.emitConnectionStateChangedEvent("CONNECTED"))}getDTLSTransportState(){if(!this._peerConnection)return at;let e=null;return!bi()||this._peerConnection.getSenders().length===0?at:(e=this._peerConnection.getSenders()[0].transport,!Hi()||this._peerConnection.getReceivers().length===0?at:e?e.state:at)}emitConnectionStateChangedEvent(e){e!==this.currentState&&(this.currentState==="RECONNECTING"&&e==="CONNECTING"||(this.emit(Jt.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return _(this,null,function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,s]of e)if(yi(s)){let o=e.get(s.localCandidateId),n=e.get(s.remoteCandidateId);o&&(this._log.info(`local candidate: ${o.candidateType} ${o.protocol}:${o.ip||o.address}:${o.port} ${o.networkType||""} ${o.candidateType==="relay"?`relayProtocol:${o.relayProtocol}`:""}`),o.networkType&&Ga(o.networkType)),n&&this._log.info(`remote candidate: ${n.candidateType} ${n.protocol}:${n.ip||n.address}:${n.port}`);break}})}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise?this._waitForPCConnectedPromise:(this._waitForPCConnectedPromise=new Promise((e,t)=>{if(this.currentState==="CONNECTED")return e();this._waitForPCConnectedPromiseReject=t;let s=c=>{c.state==="CONNECTED"&&(clearTimeout(a),n(),e())},o=({room:c})=>{c===this._room&&(clearTimeout(a),n(),t(new b({code:A.API_CALL_ABORTED,message:L({key:M.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{g.off(E.LEAVE_SUCCESS,o,this),this.off(Jt.CONNECTION_STATE_CHANGED,s,this)},a=setTimeout(()=>{n();let c=new b({code:A.API_CALL_TIMEOUT,message:"connection timeout"});Rh+=1,ef(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),yh=!0,this.emit(Jt.FIREWALL_RESTRICTION)),t(c)},cs);g.on(E.LEAVE_SUCCESS,o,this),this.on(Jt.CONNECTION_STATE_CHANGED,s,this)}),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally(()=>{this._waitForPCConnectedPromise=null,this._waitForPCConnectedPromiseReject=null}),this._waitForPCConnectedPromise)}waitForReconnected(){return this.isReconnecting?new Promise((e,t)=>{this.once("spc-reconnected",e),this.once("error",t)}):Promise.resolve()}addDownlink(e){return _(this,null,function*(){if(this._log.info(`addDownlink(${e.userId}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise),this.updateLocalAndRemoteSDPConfig(e),this.addDownlinkQueue.size===0)try{yield this.updateSDP(),this._log.info(`addDownlink(${e.userId}) done`)}catch(t){this._log.error(`addDownlink(${e.userId}) failed ${t}`),yield this.startReconnection()}})}updateLocalAndRemoteSDPConfig({ssrc:e,userId:t,tinyId:s}){if(!this._peerConnection)return;this._log.info(`updateLocalAndRemoteSDPConfig ${t} ${JSON.stringify(e)}`);let o=this._peerConnection.getTransceivers().slice(4).filter(m=>m.direction==="inactive").slice(0,3).map(m=>(m.direction=h.TRANSCEIVER_DIRECTION_RECVONLY,Number(m.mid)));this._parsedAnswer||(this._parsedAnswer=ce(this._peerConnection.remoteDescription.sdp));let n=this._parsedAnswer.media.filter(m=>{var f;return(f=m.ssrcs)==null?void 0:f.find(R=>{var C;return(C=R.value)==null?void 0:C.includes(s)})}),a,c,d;if(n.length===3)a=n[0],c=n[1],d=n[2];else if(o.length===3)a=this._parsedAnswer.media.find(m=>Number(m.mid)===Number(o[0])),c=this._parsedAnswer.media.find(m=>Number(m.mid)===Number(o[1])),d=this._parsedAnswer.media.find(m=>Number(m.mid)===Number(o[2]));else if(o.length===0){this._peerConnection.addTransceiver(h.AUDIO,{direction:h.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(h.VIDEO,{direction:h.TRANSCEIVER_DIRECTION_RECVONLY}),a=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let m=Bd({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:ce(this._peerConnection.localDescription.sdp),isDownlink:!0});c=JSON.parse(JSON.stringify(m)),d=JSON.parse(JSON.stringify(m)),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a),c.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(c),d.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(d)}a.direction=h.TRANSCEIVER_DIRECTION_SENDONLY;let u=`${s}-${e.audio}`;a.ssrcs=[{id:e.audio,attribute:"cname",value:`${u}`},{id:e.audio,attribute:"msid",value:`${u}-${h.MAIN} ${u}-audio`}],c.direction=h.TRANSCEIVER_DIRECTION_SENDONLY,c.ssrcs=[{id:e.video,attribute:"cname",value:`${u}`},{id:e.video,attribute:"msid",value:`${u}-${h.MAIN} ${u}-bigvideo`},{id:e.videoRtx,attribute:"cname",value:`${u}`},{id:e.videoRtx,attribute:"msid",value:`${u}-${h.MAIN} ${u}-bigvideo`}],c.ssrcGroups=[{semantics:"FID",ssrcs:`${e.video} ${e.videoRtx}`}],d.direction=h.TRANSCEIVER_DIRECTION_SENDONLY;let p=`${u}-aux`;d.ssrcs=[{id:e.auxiliary,attribute:"cname",value:p},{id:e.auxiliary,attribute:"msid",value:`${p} ${u}-aux${h.VIDEO}`},{id:e.auxiliaryRtx,attribute:"cname",value:`${p} ${u}-aux${h.VIDEO}`},{id:e.auxiliaryRtx,attribute:"msid",value:`${p} ${u}-aux${h.VIDEO}`}],d.ssrcGroups=[{semantics:"FID",ssrcs:`${e.auxiliary} ${e.auxiliaryRtx}`}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map(m=>m.mid).join(" ")),this._downlinkMIDMap.set(t,[a.mid,c.mid,d.mid]),this._downlinkMIDUserIDMap.set(a.mid,t),this._downlinkMIDUserIDMap.set(c.mid,t),this._downlinkMIDUserIDMap.set(d.mid,t)}removeDownlink(e){return _(this,null,function*(){if(!this._downlinkMIDMap.has(e)||!this._peerConnection)return;this._log.info(`removeDownlink(${e}) trying`),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise);let t=this._downlinkMIDMap.get(e),s=!1;this._peerConnection.getTransceivers().forEach(o=>{t!=null&&t.includes(Number(o.mid))&&(s=!0,o.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=ce(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(o=>{t!=null&&t.includes(Number(o.mid))&&(s=!0,o.direction="inactive",o.ssrcs=[],o.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&s&&(yield this.updateSDP()),this._downlinkMIDMap.delete(e),t==null||t.forEach(o=>this._downlinkMIDUserIDMap.delete(o)),this._log.info(`removeDownlink(${e}) done`)})}setBandwidth(e){return _(this,null,function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:s,smallVideo:o,auxVideo:n}=e;try{if(ws()){let a=this._peerConnection.getSenders().slice(0,4);for(let d=0;d<a.length;d++){let u=a[d],p;d===0&&t?p=t:d===1&&s?p=s:d===2&&o?p=o:d===3&&n&&(p=n),p&&(yield this.setSenderMaxBitrate(u,p))}let c=!1;s&&a[1].track&&(c=this.setStartBitrate(1,s)),n&&a[3].track&&(c=this.setStartBitrate(3,n)||c),c&&(yield this.updateSDP())}else yield this.setBandwidthBySDP(e);this._log.info(`setBandwidth ${JSON.stringify(e)}`)}catch(a){this._log.error(`failed to set bandwidth: ${a}`)}})}setStartBitrate(e,t){var s,o;return(s=this._peerConnection)!=null&&s.remoteDescription&&(this._parsedAnswer||(this._parsedAnswer=ce(this._peerConnection.remoteDescription.sdp)),(o=this._parsedAnswer.media[e])!=null&&o.fmtp[0])?(this._parsedAnswer.media[e].fmtp[0].config+=`;x-google-start-bitrate=${t>5e3?5e3:t}`,!0):!1}setSenderMaxBitrate(e,t){let s=e.getParameters();return(!s.encodings||s.encodings.length===0)&&(s.encodings=[{}]),t==="unlimited"?delete s.encodings[0].maxBitrate:s.encodings[0].maxBitrate=t*1e3,e.setParameters(s)}setBandwidthBySDP({audio:e,bigVideo:t,smallVideo:s,auxVideo:o}){if(!this._peerConnection||!this._peerConnection.localDescription)return;let n=ce(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=ce(this._peerConnection.remoteDescription.sdp));let a=ie?"TIAS":"AS";e&&(n.media[0].bandwidth=[{type:a,limit:ie?e*1e3:e}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:ie?e*1e3:e}]),t&&(n.media[1].bandwidth=[{type:a,limit:ie?t*1e3:t}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:ie?t*1e3:t}]),s&&(n.media[2].bandwidth=[{type:a,limit:ie?s*1e3:s}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:ie?s*1e3:s}]),o&&(n.media[3].bandwidth=[{type:a,limit:ie?o*1e3:o}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:ie?o*1e3:o}]);let c={type:"offer",sdp:He(n)};return this.updateSDP({localDescription:c})}setScaleResolutionDownBy(e,t){if(t===1)return;let s=e.getParameters();return(!s.encodings||s.encodings.length===0)&&(s.encodings=[{}]),s.encodings[0].scaleResolutionDownBy=t,e.setParameters(s)}updateSDP({localDescription:e}={}){if(!this._parsedAnswer)return Promise.resolve();let t=He(this._parsedAnswer);return this._updateSDPPromise=new Promise((s,o)=>_(this,null,function*(){var n,a;try{!e&&this._peerConnection&&(this._log.info("creating offer"),e=yield this._peerConnection.createOffer()),e&&(yield this.setOffer(e)),yield this.setAnswer({type:"answer",sdp:t}),this._updateSDPPromise=null,s()}catch(c){this._log.error(c),!this._isSDPLogged&&this._peerConnection&&(this._log.warn(`current offer: ${this.filterSDPDirection((n=this._peerConnection.localDescription)==null?void 0:n.sdp)}
|
|
94
94
|
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)}
|
|
95
|
-
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:d,currentDirection:l,direction:p,stopped:m})=>({mid:d,currentDirection:l,direction:p,stopped:m})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._isSDPLogged=!0),this._updateSDPPromise=null,o(c)}})),this._updateSDPPromise}setTransceiverDirection(e,t){return _(this,null,function*(){if(!ie||!this._peerConnection||!this._parsedAnswer)return;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let s=this._peerConnection.getTransceivers();t.forEach(o=>{s[o].direction!==e&&(s[o].direction=e)});for(let o of t){let n=this._parsedAnswer.media[o].direction;e===z.INACTIVE&&n===z.RECVONLY&&(this._parsedAnswer.media[o].direction=e),e===z.SENDONLY&&n===z.INACTIVE&&(this._parsedAnswer.media[o].direction=z.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(e=""){return ce(e).media.map(s=>s.direction)}setOffer(e){return this._log.info("setting offer"),this._log.debug(e.sdp),this._peerConnection.setLocalDescription({type:"offer",sdp:Th(e.sdp,this.clientAbility,this._serverAbility)})}setAnswer(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._peerConnection.setRemoteDescription(e)}switchVideoEncoder(e){return _(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach(s=>{var o;if(s.type===h.VIDEO){let n=this._serverAbility.video.codecs.find(a=>a.codec.toLowerCase()===e);n&&!((o=s.payloads)!=null&&o.includes(String(n.payload)))&&(s.fmtp=[],s.payloads="",s.rtp=[],s.rtcpFb=[],or(s,n),t=!0)}}),t&&(this._log.warn(`switch video encoder to ${e}`),yield this.setOffer(this._peerConnection.localDescription),yield this.setAnswer({type:"answer",sdp:He(this._parsedAnswer)}))})}useHWEncoder(e=!0,t){return _(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let s=!1,o=[];T(t)?o=this._parsedAnswer.media.slice(1,4):t===2?o.push(this._parsedAnswer.media[1]):t===3?o.push(this._parsedAnswer.media[2]):t===7&&o.push(this._parsedAnswer.media[3]),o.forEach(n=>{var a;if(n.type===h.VIDEO){let c;e&&this.is42001fSupported?c=this.clientAbility.video.codecs.find(d=>d.fmtp.includes("42001f")):e||(c=this._serverAbility.video.codecs.find(d=>d.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=[],or(n,c),s=!0)}}),s&&(this._log.warn(`use ${e?"hw":"sw"} encoder`),yield this.setOffer(this._peerConnection.localDescription),yield this.setAnswer({type:"answer",sdp:He(this._parsedAnswer)}))})}sendDataChannelMessage(e){var t;(t=this._datachannel)==null||t.send(e)}reset(){var e;(e=this._peerConnection)==null||e.close(),this._waitForPCConnectedPromise=null,this._parsedAnswer=null}close(){this._log.info("close pc"),this.insertableStreamsAbortMap.forEach(e=>Tu(e.abort)&&e.abort("destroy")),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners()}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map(s=>t[s])}};y([Rn("reconnect")],ui.prototype,"startReconnection",1),y([si(r=>r.userId)],ui.prototype,"addDownlink",1),y([si(r=>r)],ui.prototype,"removeDownlink",1),y([$t(!0)],ui.prototype,"updateSDP",1);var Ud=class{constructor(i){u(this,"tag");u(this,"len");u(this,"data");let e=new DataView(i);this.tag=e.getUint16(),this.len=e.getUint16(2),this.data=new Uint8Array(i).slice(4,2+2+this.len).buffer}},Bd=class{constructor(i){u(this,"tinyId");u(this,"data");let e=new DataView(i),t=0,s=[];for(;t<e.byteLength;){let o=e.getUint16(t+2),n=new Ud(new Uint8Array(i).slice(t,t+2+2+o).buffer);s.push(n),t+=2+2+o}s.forEach(o=>{o.tag===1?this.tinyId=new TextDecoder().decode(o.data):o.tag===2&&(this.data=o.data)})}},Ah=new Set;function nr(){let r=Math.floor(Math.random()*4294967296);return Ah.has(r)?nr():(Ah.add(r),r)}var bh=Se(Ne());var ar=class extends bh.default{constructor(e){super();u(this,"userId");u(this,"tinyId");u(this,"_sdpSemantics");u(this,"_isUplink");u(this,"_room");u(this,"_log");u(this,"_currentState","DISCONNECTED");u(this,"_prevTime",-1);this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=I.createLogger({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:(g.emit(E.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 _o=class extends ar{constructor(e){super(P(N({},e),{isUplink:!0}));u(this,"localMainAudioTrack",null);u(this,"localMainVideoTrack",null);u(this,"localAuxAudioTrack",null);u(this,"localAuxVideoTrack",null);u(this,"_isPublishingAux",!1);u(this,"_publishingLocalAudioTrack");u(this,"_publishingLocalVideoTrack");u(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});u(this,"_flag",0);u(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:s,smallVideoSsrc:o,smallVideoRtxSsrc:n,auxVideoSsrc:a,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:s||0,small:o||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){if(!e&&this._checkPublishStateTimeoutId>0)return;let{publishState:t,serverPublishState:s}=this,o=Object.keys(t).find(n=>t[n]!==s[n]);if(o)if(e)this._log.warn(`publish state not matched, ${o} local:${t[o]} server:${s[o]} ${As()} ${wa()}`),D.addCount({key:521e3});else{this._checkPublishStateTimeoutId=re.run(fi,()=>this.checkPublishState(!0),{delay:10*1e3,count:1});return}re.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,s,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(Lt()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((s=a[1])!=null&&s.track),e.smallVideo=!!((o=a[2])!=null&&o.track),e.auxVideo=!!((n=a[3])!=null&&n.track)):a.forEach(c=>{c.track&&(c.track.kind===h.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}get serverPublishState(){return{audio:!!(this.flag&mi),bigVideo:!!(this.flag&hi),smallVideo:!!(this.flag&os),auxVideo:!!(this.flag&xi)}}get muteState(){var e,t,s;return{audio:!!((e=this.localMainAudioTrack)!=null&&e.muted),bigVideo:!!((t=this.localMainVideoTrack)!=null&&t.muted),auxVideo:!!((s=this.localAuxVideoTrack)!=null&&s.muted)}}initialize(){this.installEvents()}close(e){var s;let t=((s=this._peerConnection)==null?void 0:s.getSenders())||[];for(let o of t)o.replaceTrack(null);super.close(e),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){var e,t;this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),(e=this.singlePC)!=null&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(t=this.singlePC)==null||t.on("spc-reconnected",this.onSinglePCReconnected,this),yi&&this._room.enableSEI&&!g.listeners(E.SEND_SEI_MESSAGE).includes(this.sendSEIByWorker)&&(this.sendSEIByWorker=this.sendSEIByWorker.bind(this),g.on(E.SEND_SEI_MESSAGE,this.sendSEIByWorker))}uninstallEvents(){var e;this.off("connection-state-changed",this.handleConnectionStateChange,this),(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this),g.off(E.SEND_SEI_MESSAGE,this.sendSEIByWorker)}emitConnectionStateChangedEvent(e,t){var n,a,c;let s=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:s,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:s,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:s,state:e}))),o}onVideoEncodeFailed(e){var t,s;e&&e.isMediaTrackActive&&this.videoCodec==="h264"&&(this._log.warn("h264 encoder not working"),(t=this.singlePC)!=null&&t.isVP8EncodeSupported&&(this._log.warn("switch to vp8"),(s=this.singlePC)==null||s.switchVideoEncoder("vp8")))}publish(o){return _(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:s}){var d,l,p,m,f,R,C;if(!this.singlePC)return;yield this.singlePC.waitForPeerConnectionConnected();let{publishState:n,muteState:a}=this;if(e&&(this._publishingLocalAudioTrack=e,n.audio=!0,a.audio=e.muted),t){if(!this.singlePC.isH264EncodeSupported&&!this.singlePC.isVP8EncodeSupported)throw new b({code:A.NOT_SUPPORTED_H264,message:L({key:M.NOT_SUPPORTED_H264ENCODE})});pe&&Qt()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn("fallback video to 480p"),t.setProfile(Ze["480p_2"]),yield t.applyProfile()),this._publishingLocalVideoTrack=t,s?(n.auxVideo=!0,a.auxVideo=t.muted):(n.bigVideo=!0,a.bigVideo=t.muted)}this._isPublishingAux=s;let c;if(t&&!s&&t.small&&(c=this._room.videoManager.smallTrack,n.smallVideo=!0),yield this._signalChannel.sendWaitForResponseWithRetry({command:q.SPC_PUBLISH,responseCommand:V.SPC_PUBLISH_RESULT,data:P(N({},this.singlePC.uplinkSSRC),{state:n,muteState:a}),retries:3}),yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:c,isAuxiliary:s}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,t){this[s?"localAuxVideoTrack":"localMainVideoTrack"]=t;let{scaleResolutionDownBy:v}=t;v>1&&(this._log.warn(`setScaleResolutionDownBy ${t.streamType} ${v}`),yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[s?3:1],v))}e&&(this[s?"localAuxAudioTrack":"localMainAudioTrack"]=e),yield this.singlePC.setBandwidth({audio:((d=this.localMainAudioTrack)==null?void 0:d.profile.bitrate)||((l=this.localAuxAudioTrack)==null?void 0:l.profile.bitrate),bigVideo:(p=this.localMainVideoTrack)==null?void 0:p.profile.bitrate,smallVideo:(f=(m=this.localMainVideoTrack)==null?void 0:m.small)==null?void 0:f.bitrate,auxVideo:(R=this.localAuxVideoTrack)==null?void 0:R.profile.bitrate}),this.sendMediaSettings(),this.installTrackMuteEvents(e,t),!s&&(this._room.preferHW||((C=this._room.scheduleResult.config)==null?void 0:C.preferHW))&&t&&t.profile.width*t.profile.height>=1280*720&&this.singlePC.useHWEncoder(!0,2)})}publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:s,isAuxiliary:o}){if(!tt())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(),d=[],l=[],p=(f,R,C)=>{var U;let v=c[R].sender.replaceTrack(C);l.push(R),(U=this.singlePC)!=null&&U.enableInsertableStreams&&v.then(()=>this.createEncodedStreams(c[R].sender,f)),d.push(v)};a&&p(e.mediaType,0,a),n&&p(t.mediaType,o?3:1,n),s&&p(8,2,s);let m=this.singlePC.setTransceiverDirection(z.SENDONLY,l);return d.push(m),Promise.all(d)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._publishingLocalAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._publishingLocalVideoTrack;case 2:return this.localAuxVideoTrack||this._publishingLocalVideoTrack;default:return null}}createEncodedStreams(e,t){var a,c;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let s=e.createEncodedStreams(),o=new AbortController;(a=this.singlePC)==null||a.addAbortController(e,o),((c=this.getTrackByMediaType(t))!=null&&c.enableEncodeFrame?s.readable.pipeThrough(new TransformStream({transform:(d,l)=>{var m;let p=this.getTrackByMediaType(t);l.enqueue(((m=this.singlePC)==null?void 0:m.isUsingH264)&&p?p.encodeFrame(d,t===8):d)}}),o):s.readable).pipeTo(s.writable,o).catch(d=>{this._log.debug("encoded stream error",d),d!=="destory"&&this._log.warn(d)})}sendSEIByWorker({room:e,isMain:t}){var o;if(e!==this._room||!this._peerConnection||!this.singlePC||!this._room.videoManager.seiWorker)return;let s=this._peerConnection.getSenders()[t?1:3];if(!!s&&(s.transform||(s.transform=new RTCRtpScriptTransform(this._room.videoManager.seiWorker,{isReceiver:!1,isMain:t})),t&&((o=this.localMainVideoTrack)==null?void 0:o.small))){let n=this._peerConnection.getSenders()[2];n.transform||(n.transform=new RTCRtpScriptTransform(this._room.videoManager.seiWorker,{isReceiver:!1,isMain:t,small:!0}))}}enableSmall(e){return _(this,null,function*(){if(!this.singlePC)return;let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.singlePC.setTransceiverDirection(z.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(z.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(s){return _(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){let o=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localMainAudioTrack&&!this.localAuxAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=P(N({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=P(N({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.singlePC.setTransceiverDirection(z.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 _(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},s=yield this._signalChannel.sendWaitForResponseWithRetry({command:q.PUBLISH_STATE_CHANGE,data:t,responseCommand:V.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(s.data.code,s.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:q.UNPUBLISH,commandDesc:"unpublish",responseCommand:V.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===A.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let s=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:o,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:o=this._publishingLocalVideoTrack),xt){if(s&&s.outMediaTrack){let a=s.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=s.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=o.profile.bitrate*1e3,o.small&&(this._mediaSettings.smallVideoWidth=o.small.width,this._mediaSettings.smallVideoHeight=o.small.height,this._mediaSettings.smallVideoFps=o.small.frameRate,this._mediaSettings.smallVideoBps=o.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else s&&s.outMediaTrack&&(this._mediaSettings.audioChannel=s.profile.channelCount,this._mediaSettings.audioBps=s.profile.bitrate*1e3,this._mediaSettings.audioFs=s.profile.sampleRate),o&&o.outMediaTrack&&(this._mediaSettings.videoWidth=o.profile.width,this._mediaSettings.videoHeight=o.profile.height,this._mediaSettings.videoFps=o.profile.frameRate,this._mediaSettings.videoBps=o.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:q.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:V.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return _(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?h.AUXILIARY:h.MAIN} stream`),Lt()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return _(this,null,function*(){var o;if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield s[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)==null?void 0:o.small)&&(yield s[2].sender.replaceTrack(this._room.videoManager.smallTrack)),s[n].direction===z.INACTIVE&&(yield this.singlePC.setTransceiverDirection(z.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(e){return _(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?h.AUXILIARY:h.MAIN} stream`),Lt()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return _(this,null,function*(){if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(null);else{let o=t?3:1;yield s[o].sender.replaceTrack(null),o===1&&this._room.videoManager.hasSmall&&(yield s[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(z.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(e){return _(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders(),s=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!s||t.find(a=>a.track===s))return!1;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${s.kind} track ${s.id} on ${o?h.AUXILIARY:h.MAIN} stream`),s.kind===h.AUDIO&&t[0]&&(yield t[0].replaceTrack(s)),s.kind===h.VIDEO&&(!o&&t[1]&&(yield t[1].replaceTrack(s)),o&&t[3]&&(yield t[3].replaceTrack(s))),!0})}setBandwidth(o){return _(this,arguments,function*({bandwidth:e,type:t,videoType:s}){if(this.singlePC){let n={};t===h.AUDIO?n.audio=e:s==="big"?n.bigVideo=e:s==="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.muteState)}`),this._signalChannel.sendWaitForResponseWithRetry({command:q.UPDATE_MUTE_STAT,responseCommand:V.MUTE_RESULT,data:this.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&g.emit(E.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=h.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===h.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===h.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===h.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===h.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Pi?(this._log.error(Ae.NOT_SUPPORTED_H264ENCODE),new b({code:A.NOT_SUPPORTED_H264,message:L({key:M.NOT_SUPPORTED_H264ENCODE})})):new b({code:A.UNKNOWN,message:L({key:M.SIGNAL_RESPONSE_FAILED,data:{signalResponse:V.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return _(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}))})}};y([gt(function({localVideoTrack:r}){r==null||r.once("6",this.onVideoEncodeFailed,this)})],_o.prototype,"publish",1),y([gt(function({localVideoTrack:r}){r==null||r.off("6",this.onVideoEncodeFailed,this)})],_o.prototype,"unpublish",1);var $d=_o;function Nh(r){return Object.keys(r).filter(i=>r[i])}var Qr=class extends ar{constructor(e){super(P(N({},e),{isUplink:!1}));u(this,"_flag",0);u(this,"role","anchor");u(this,"remoteAudioTrack");u(this,"remoteVideoTrack");u(this,"remoteAuxiliaryTrack");u(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});this.flag=e.flag,this.remoteAudioTrack=new oi(this._room,this),this.remoteVideoTrack=new Tt(this._room,this),this.remoteAuxiliaryTrack=new Vr(this._room,this),this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264"}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 Ai(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,s,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===h.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){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))}uninstallEvents(){!this.singlePC||(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),s}onTrack(e){let t=e.streams[0],{track:s,receiver:o}=e;if(!t.id.includes(this.tinyId))return;let a=t.id.includes("aux")?"auxiliary":"main";this._log.debug(`ontrack ${a} ${s.kind}`);let c=h.AUDIO;s.kind===h.VIDEO&&(c=a===h.MAIN?h.VIDEO:h.AUXILIARY);let d=this.remoteAudioTrack;c===h.VIDEO?d=this.remoteVideoTrack:c===h.AUXILIARY&&(d=this.remoteAuxiliaryTrack),this._room.enableSEI&&yi&&this.receiveSEIByWorker(o,a),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(d,o),d.setInputMediaStreamTrack(s)}createEncodedStreams(e,t){if(!this.singlePC.insertableStreamsAbortMap.has(t)){let s=t.createEncodedStreams(),o=new AbortController,n={abortController:o,enqueue:c=>{var d;return(d=this.singlePC)!=null&&d.isUsingH264?e.decodeFrame(c):c}};(e.enableDecodeFrame?s.readable.pipeThrough(new TransformStream({transform:(c,d)=>d.enqueue(n.enqueue(c))})):s.readable).pipeTo(s.writable,o).catch(c=>{c!=="destory"&&this._log.warn(c)}),this.singlePC.addAbortController(t,o)}}receiveSEIByWorker(e,t){e.track.kind===h.AUDIO||!this._peerConnection||!this.singlePC||!this._room.videoManager.seiWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this._room.videoManager.seiWorker,{isReceiver:!0,userId:this.userId,streamType:t}))}subscribe(e,t){return _(this,null,function*(){try{if(this._log.info(`subscribe ${t} ${Nh(e)}`),this.hasSSRC){let s="subscribe_change";Object.values(e).find(o=>o===!0)||(s="unsubscribe"),yield this.sendSubscription(s,e)}else yield this.doSubscribe(e),this.checkTrackEnded(e)}catch(s){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${s.message} ${JSON.stringify(this.muteState)}`),new b({code:A.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):s}})}checkTrackEnded(e){var t,s,o;if((e.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||e.video&&((s=this.remoteVideoTrack.mediaTrack)==null?void 0:s.readyState)==="ended"||e.auxiliary&&((o=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:o.readState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),Pe&&ht<92)return;this.singlePC.startReconnection()}}unsubscribe(s){return _(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 o=N({},this.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(c=>c===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${Nh(o)}]`),n==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(n,o),n==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,t=this.subscribeState){let s={srcTinyId:this.tinyId,srcUserId:this.userId},o=q.UNSUBSCRIBE,n=V.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(s={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=q.SUBSCRIBE_CHANGE,n=V.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:o,data:s,responseCommand:n,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let c=new b({code:a.code,message:L({key:M.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(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn(`resubscribe ${JSON.stringify(this.subscribeState)}`),this.doSubscribe(this.subscribeState))}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return _(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 s={audioSsrc:nr(),bigVideoSsrc:nr(),bigVideoRtxSsrc:nr(),auxVideoSsrc:nr(),auxVideoRtxSsrc:nr()},{audioSsrc:o,bigVideoSsrc:n,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:d}=s;this.ssrc={audio:o,video:n,videoRtx:a,auxiliary:c,auxiliaryRtx:d},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});try{let l=yield this._signalChannel.sendWaitForResponseWithRetry({command:q.SPC_SUBSCRIBE,responseCommand:V.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:s},retries:3,retryTimeout:0});if(l.data.code!==0)throw new b({code:l.data.code,message:l.data.message})}catch(l){throw yield this.removeDownlink(),l}return}this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc})}finally{let s=this._room.scheduleResult.config;((s==null?void 0:s.jitterDelay)||(s==null?void 0:s.jitterDelayAux))&&this.setJitterBufferDelay({mainDelay:s.jitterDelay,auxDelay:s.jitterDelayAux})}}})}removeDownlink(){return _(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?void 0:e.jitterDelay)||(e==null?void 0:e.jitterDelayAux))&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)})}setJitterBufferDelay({mainDelay:e,auxDelay:t}){if(!this.singlePC||!this._peerConnection||Zt(e)&&Zt(t))return Promise.resolve();this._log.info(`set jitterBuffer main: ${e} aux: ${t}`);let s=this.singlePC.getReceiversByUserId(this.userId);return ee(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),ee(t)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=t,Zt(e)&&(this.remoteAudioTrack.jitterBufferDelay=t)),new Promise(o=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:s,resolve:o})})}doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:s,resolve:o}){let n=-1;try{if(e===0&&t===0)return s.forEach(c=>c.jitterBufferTarget=0),o();if(s.forEach(c=>{var m;let d=c.track===this.remoteAuxiliaryTrack.outMediaTrack||Zt(e)&&c.track===this.remoteAudioTrack.outMediaTrack;if(d&&Zt(t)||!d&&Zt(e))return;let l=d?t||0:e,p=(c.jitterBufferTarget||0)+100;p>l||(c.jitterBufferTarget=p,this._log.debug(`set ${d?"aux ":""}${(m=c==null?void 0:c.track)==null?void 0:m.kind} jitterBuffer delay ${p} -> ${l}`))}),!s.find(c=>{let d=c.track===this.remoteAuxiliaryTrack.outMediaTrack?t||0:e;return c.jitterBufferTarget<d}))return this._log.info(`set jitterBuffer main: ${e} aux: ${t} done`),o();n=setTimeout(()=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:s,resolve:o})},1e3)}catch(a){this._log.warn(`set jitterBuffer delay error: ${a}`),clearTimeout(n),o()}}};y([$t(),J(r=>function(...i){return new Promise((e,t)=>{let s=o=>{this.off("closed",s),t(new b({code:A.API_CALL_ABORTED,message:L({key:M.CONNECTION_ABORTED,data:o})}))};this.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this.off("closed",s)})})})],Qr.prototype,"subscribe",1),y([$t()],Qr.prototype,"unsubscribe",1),y([si(()=>"jitter")],Qr.prototype,"setJitterBufferDelay",1);var vh=Qr;function Dh(){return J(r=>function(...i){return _(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(t=>t.outMediaTrack&&t.state==="capture"),!i.length))return;g.emit("61",{room:this});let e=r.apply(this,i);return i.forEach(t=>t.publish(this,e)),e})})}function Oh(){return J(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var Mh=Se(Ne());function rf(){return Math.floor(Math.random()*16383)}var Fd=class extends Mh.EventEmitter{constructor(e,t){super();this.room=e;this.signalChannel=t;u(this,"log");u(this,"cmdIdSeqMap",new Map);u(this,"messageMap",new Map);this.log=I.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(V.RECEIVE_CUSTOM_MSG,this.onReceiveMsg)}send({cmdId:e,data:t}){let s=this.cmdIdSeqMap.get(e)||rf(),o={cmdId:e,msg:btoa(String.fromCharCode(...new Uint8Array(t))),ordered:!0,reliable:!0,streamSeq:s};this.cmdIdSeqMap.set(e,s+1),this.signalChannel.send(q.SEND_CUSTOM_MSG,o),this.log.debug(`send custom msg: ${JSON.stringify(o)}`)}onReceiveMsg(e){let{data:t}=e.data,s=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(s){let o={userId:s,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),n=>n.charCodeAt(0)).buffer};if(t.ordered){let n=`${s}_${o.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(o,!0),100)),a.cachedMessageMap.set(o.seq,{message:o});else if(Math.abs(a.lastSeq-o.seq)>Fd.SEQ_INTERVAL)this.messageMap.set(n,{lastSeq:o.seq,cachedMessageMap:new Map}),this.emitMessage(o);else if(o.seq>a.lastSeq){if(o.seq===a.lastSeq+1)this.emitMessage(o);else if(!a.cachedMessageMap.has(o.seq)){let c=setTimeout(()=>this.emitMessage(o,!0),5e3);a.cachedMessageMap.set(o.seq,{message:o,timeoutId:c})}}else this.log.debug(`drop message ${o.userId}-${o.cmdId}-${o.seq}`)}else this.emit("message",o)}}emitMessage(e,t=!1){var a;let s=this.messageMap.get(`${e.userId}_${e.cmdId}`),o=e;if(s){if(t){let c=[...s.cachedMessageMap.values()].sort((d,l)=>d.message.seq-l.message.seq);c[0]&&(o=c[0].message)}s.lastSeq!==0&&o.seq-s.lastSeq>1&&this.log.debug(`msg lost userId: ${o.userId} seq: ${s.lastSeq} -> ${o.seq}`),s.lastSeq=o.seq,clearTimeout((a=s.cachedMessageMap.get(o.seq))==null?void 0:a.timeoutId),s.cachedMessageMap.delete(o.seq)}this.log.debug(`receive custom msg: ${JSON.stringify(o)}`),this.emit("message",o);let n=s==null?void 0:s.cachedMessageMap.get(o.seq+1);n&&this.emitMessage(n.message)}},fo=Fd;u(fo,"SEQ_INTERVAL",300);var{isString:kh,isUndefined:zr,getNetworkType:sf,isEmpty:Eo}=we,At=class extends oa{constructor(e){super(e);this._heartbeat=-1;this._lastHeartBeatTime=-1;this._joinTimeout=-1;this._firstPublishedList=null;this._joinReject=null;this._isRelayChanged=!1;this.signalChannel=null;this.uplinkConnection=null;this.singlePC=null;this.enableSPC=Dr;this._changeBigSmallRecords=new Map;this._networkQuality=null;this._turnServers=[];this._syncUserListInterval=-1;this._smallStreamConfig={bitrate:100,frameRate:15,height:120,width:160};this.enableSEI=!1;this._enableAudioVolumeEvaluation=!1;this._audioVolumeIntervalId=0;this._enableMultiAuxStream=!1;this._pureAudioPushMode=!1;this.preferHW=!1;this._stats=new co(this,this._log),this.userManager=new Bn(this.userId,this._log),this._version=Re,this.sdpSemantics=dr,zr(e.sdpSemantics)?ft.isUnifiedPlanDefault()&&(this.sdpSemantics=pi):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${sf()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=zr(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&Dr,!zr(e.enableSPC)&&Dr&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new Ih(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]))}join(e,t,s){return _(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",o=>{this.emit("peer-join",o)}),this.userManager.on("2",o=>{this.closeDownLinkConnection(o,"remote user exitRoom"),this.emit("peer-leave",o)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",n=>{var o=Jd(n,[]);g.emit(E.REMOTE_PUBLISH_STATE_CHANGED,N({room:this},o)),this.emit("remote-publish-state-changed",N({},o))}),this.joinParams=e,new Promise((o,n)=>_(this,null,function*(){var a,c;this._joinReject=n;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(l){if(l instanceof b&&l.code===A.SPC_INITIALIZED_FAILED)(a=this.signalChannel)==null||a.destroy(),yield this.initialize();else return n(l)}let d=x();yield this.doJoin(e,(c=this.singlePC)==null?void 0:c.clientAbility),D.addSuccessEvent({key:521708,cost:x()-d}),o(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(d){D.addFailedEvent({key:521708,error:d}),n(d)}this._joinReject=null}))})}initSinglePC(){return _(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new ui({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",e=>this.emit("sei-message",e)),this.singlePC.once("error",()=>this.fallbackToMPC());try{return yield this.singlePC.initialize()}catch(e){throw this.fallbackToMPC(),new b({code:A.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((s,o)=>_(this,null,function*(){var c,d,l;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(_e.SETUP_FAILED,p=>{this.clearJoinTimeout(),g.emit(E.JOIN_SIGNAL_CONNECTION_END,{room:this,error:p}),o(p)}),de((d=(c=this.scheduleResult)==null?void 0:c.config)==null?void 0:d.singlePC)&&Dr&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2);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:Va(),netType:br(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig};this._log.debug(`join room signal data: ${JSON.stringify(n)}`);let a=5e3;((l=this.scheduleResult.config)==null?void 0:l.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(a=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{o(new b({code:A.JOIN_ROOM_FAILED,message:L({key:M.JOIN_ROOM_TIMEOUT})}))},a),g.emit(E.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?q.SPC_JOIN_ROOM:q.JOIN_ROOM,n),this.signalChannel.once(V.JOIN_ROOM_RESULT,p=>{this.clearJoinTimeout();let{code:m,message:f,data:R,tinyId:C}=p.data;g.emit(E.JOIN_RECEIVED_CMD_RES,{room:this,code:m}),m===0?(this._log.info("Join room success, start heartbeat"),C&&(this.tinyId=C),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=R.publishers,this.singlePC&&this.singlePC.connect(R.ability).catch(()=>{}),s()):(this._log.error(`Join room failed result: ${m} error: ${f}`),o(new b({code:A.JOIN_ROOM_FAILED,extraCode:m,message:L({key:M.JOIN_ROOM_FAILED,data:{error:f,code:m}})})))})}))}reJoin(e=!0){return _(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this.joinParams.roomId}`);let t,s=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,s.push(this.initSinglePC().then(o=>(t=o,o)))),this.signalChannel&&(this.signalChannel.race=e,this.signalChannel.close(),s.push(this.signalChannel.connect())),yield Promise.all(s),yield this.doJoin(P(N({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),t),this._log.warn("reJoin success"),Z.logSuccessEvent({userId:this.userId,eventType:Ve.REJOIN}),this.singlePC){let o=n=>{var a;n.state==="CONNECTED"&&((a=this.singlePC)==null||a.off(Wt.CONNECTION_STATE_CHANGED,o),this.uplinkConnection instanceof $d&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(c=>{c.installEvents(),c.onSinglePCReconnected()}))};this.singlePC.on(Wt.CONNECTION_STATE_CHANGED,o),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof ao&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(t){this._log.warn(`reJoin fail ${t}`),this.reset(),Z.logFailedEvent({userId:this.userId,eventType:Ve.REJOIN,error:t}),this.emit("error",new b({code:A.JOIN_ROOM_FAILED,message:L({key:M.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}})}initialize(){return _(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),s=this.signalChannel||Ql(this.userId),o=!!(s&&s.isConnected&&s.keepAlive),n;return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(n=this.scheduleResult.domains[0]),this._log.info(`${o?"reuse":"setup"} signal channel`),o?(s.url=e,s.backupUrl=t,s.room=this,this.signalChannel=s):(this.signalChannel=new jr({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,race:this.enableSPC&&!this.proxy_ws,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?n:void 0}),this._customMessageManager=new fo(this,this.signalChannel),this._customMessageManager.on("message",a=>{this.emit("custom-message",a)})),this._networkQuality||(this._networkQuality=new rr({signalChannel:this.signalChannel,room:this}),this._networkQuality.on(rr.EVENT_NETWORK_QUALITY,a=>{this.emit("network-quality",a)})),De(this,this.signalChannel).add(_e.CONNECTION_STATE_CHANGED,a=>{g.emit(E.SIGNAL_CONNECTION_STATE_CHANGED,N({room:this},a)),this.emit("signal-connection-state-changed",a)}).add(_e.RECONNECT_FAILED,a=>{this.reset(),this.emit("error",a)}).add(V.PEER_JOIN,a=>{let{srcTinyId:c,userId:d,role:l}=a.data.data;this.userManager.addUser({userId:d,tinyId:c,role:l})}).add(V.PEER_LEAVE,a=>{let{userId:c,reason:d=0}=a.data.data;this.userManager.deleteUser(c,d)}).add(V.UPDATE_REMOTE_MUTE_STAT,a=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(a.data)}).add(V.CLIENT_BANNED,a=>{let c=a.data.data,{reason:d}=c;if(Z.uploadEvent({log:`stat-banned:${d}`,userId:this.userId}),d==="user_time_out"){this._log.warn(`${d} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[d==="kick"?"error":"info"](`user was banned because of [${d}]`),this.reset(),this.emit("banned",{reason:d})}),this.signalChannel.once(_e.SETUP_SUCCESS,a=>{this.tinyId=a.signalInfo.tinyId,g.emit(E.JOIN_SIGNAL_CONNECTION_END,{room:this})}),g.emit(E.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),o&&g.emit(E.JOIN_SIGNAL_CONNECTION_END,{room:this}),o})}setSignalChannel(e){this.signalChannel=e,e||me(this)}leave(){return _(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),g.emit(E.LEAVE_SEND_CMD,{room:this}),(e=this.signalChannel)==null||e.send(q.LEAVE_ROOM)})}clearNetworkQuality(){this._networkQuality&&(this._networkQuality.stop(),this._networkQuality=null)}closeConnections(){this.remotePublishedUserMap.forEach(e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=re.run(_i,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),re.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return _(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 s=(n=this.signalChannel)!=null&&n.isConnected?gl(this.userId):[],o=P(N({str_sdk_version:is,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:s,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},t),{msg_device_info:N({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:br()},t.msg_device_info)});if(this.heartbeatReport=o,g.emit(E.HEARTBEAT_REPORT,{room:this,report:o}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(q.ON_QUALITY_REPORT,o);let a=Date.now();this._lastHeartBeatTime>0&&a-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${a-this._lastHeartBeatTime}`),this._lastHeartBeatTime=a}this.emit("heartbeat-report",P(N({},o),{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.map(({userId:s,srcTinyId:o,flag:n})=>{s===this.userId&&this.uplinkConnection&&(this.uplinkConnection.flag=n);let a=this.remotePublishedUserMap.get(s);return a&&this.checkSubscribeBigSmallVideo(a),{userId:s,tinyId:o,flag:n}});g.emit(E.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),this.userManager.setRemotePublishedUserList(t)}closeUplink(e="you unpublished"){this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection instanceof ao&&(this.uplinkConnection=null)),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:t,flag:s}){let o=new(this.singlePC?vh:bd)({userId:e,tinyId:t,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:s});this.userManager.addRemotePublishedUser(o),this.installDownlinkEvents(o,e),this.emit("remote-published",o)}closeDownLinkConnection(e,t="remote user unpublished"){let s=this.remotePublishedUserMap.get(e);s&&(s.close(t),this.emit("remote-unpublished",s))}installDownlinkEvents(e,t){e.on("error",s=>{let o=s.getCode();o!==A.ICE_TRANSPORT_ERROR&&(o===A.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",s))}),e.on("connection-state-changed",s=>{this.emit("media-connection-state-changed",P(N({},s),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=re.run(_i,this.syncUserList.bind(this)))}stopSyncUserListInterval(){re.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:q.GET_USER_LIST,responseCommand:V.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:t})=>{let{code:s,message:o}=t;if(s===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:c,role:d})=>({userId:a,tinyId:c,role:d}));throw L({key:M.SIGNAL_RESPONSE_FAILED,data:{signalResponse:V.USER_LIST_RES,code:s,message:o}})}):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||!Id)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)===se.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(s=>{if(s instanceof Ke&&!s.getIsReconnecting()){let o=s.getPeerConnection();o&&o.connectionState===se.CLOSED&&(this._log.warn(`[${s.getUserId()}] pc is closed but not reconnect`),s.startReconnection())}})}fallbackToMPC(){return _(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),Z.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(e=this.singlePC)==null||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin(!1)),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new ao({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),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()}this.remotePublishedUserMap.forEach(t=>{let s=new bd({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(s,t.userId),this.remotePublishedUserMap.set(t.userId,s),t.isMainStreamSubscribed&&s.subscribe(t.subscribeState,"main"),t.isAuxStreamSubscribed&&s.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 b({code:A.INVALID_OPERATION,message:L({key:M.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy())}switchRole(e){return _(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:q.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:V.SWITCH_ROLE_RES,retries:1};return this._log.info(`switchRole signal data: ${JSON.stringify(t.data)}`),this.signalChannel.sendWaitForResponseWithRetry(t).then(s=>{let{code:o,message:n}=s.data;if(o!==0)throw new b({code:A.SWITCH_ROLE_FAILED,message:L({key:M.SWITCH_ROLE_FAILED,data:{message:n,code:o}})});this.role=e}).catch(s=>{throw s instanceof b&&s.getCode()===A.API_CALL_TIMEOUT&&(s=new b({code:A.SWITCH_ROLE_FAILED,message:L({key:M.SWITCH_ROLE_TIMEOUT})})),this._log.error(s),s})}publish(...e){return _(this,null,function*(){let t={},s={};e.forEach(c=>{c instanceof Oe&&(c instanceof Ft?s.audio=c:t.audio=c),c instanceof le&&(c instanceof ze&&c.mediaType===2?s.video=c:t.video=c)});let o=Eo(t),n=Eo(s);(!o||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new $d({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new ao({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),this.uplinkConnection.on("connection-state-changed",c=>{this.emit("media-connection-state-changed",P(N({},c),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",c=>{let d=c.getCode();d!==A.ICE_TRANSPORT_ERROR&&(d===A.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",c))}));let a=e.map(c=>c.kind).join(",");o||(this._log.info(`publish() => main ${a}`),yield this.uplinkConnection.publish({localAudioTrack:t.audio,localVideoTrack:t.video,isAuxiliary:!1}),this._log.info("main is published")),n||(this._log.info(`publish() => aux ${a}`),yield this.uplinkConnection.publish({localAudioTrack:s.audio,localVideoTrack:s.video,isAuxiliary:!0}),this._log.info("aux is published"))})}unpublish(...e){return _(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let t={},s={};e.forEach(o=>{!o.mediaTrack||!o.isPublished||(o instanceof Oe&&(o instanceof Ft?s.audio=o:t.audio=o),o instanceof le&&(o instanceof ze&&o.mediaType===2?s.video=o:t.video=o))});try{let o=e.map(n=>n.kind).join(",");Eo(t)||(this._log.info(`unpublish() => main ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:t.audio,localVideoTrack:t.video})),Eo(s)||(this._log.info(`unpublish() => aux ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:s.audio,localVideoTrack:s.video}))}catch(o){}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():this.uplinkConnection.removeTrack(e).then(t=>(e.unpublish(),t))}replaceTrack(e){return!this.uplinkConnection||!e.mediaTrack||!tc()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{t&&g.emit(E.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return _(this,null,function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return _(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:h.VIDEO,videoType:h.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(...e){return _(this,null,function*(){if(e=e.filter(n=>!n.isSubscribed),e.length===0)return;let{userId:t}=e[0],s=this.remotePublishedUserMap.get(t);if(!s)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";try{let n=N({},s.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&&s.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),g.emit(E.SUBSCRIBE_START,{room:this,streamType:o,remotePublishedUser:s,subscribeState:n}),this._log.info(`subscribe() => ${t} ${o} [${Zn(n)}] prev: [${Zn(s.subscribeState)}]`),yield s.subscribe(n,o),this._log.info(`subscribe ${t} ${o} done`);for(let c of e)c.mediaTrack||(yield c.waitHasMediaTrack());g.emit(E.SUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:s})}catch(n){let a=n instanceof b?n.getCode():A.UNKNOWN,c=n;throw n instanceof b?a===A.REMOTE_STREAM_NOT_EXIST&&(c=new b({code:A.API_CALL_ABORTED,message:L({key:M.API_CALL_ABORTED,data:{message:n.message,userId:t,streamType:o}})}),this._log.warn(c)):(c=new b({code:a,message:L({key:M.SUBSCRIBE_FAILED,data:{message:n.message,userId:t,streamType:o}})}),this._log.error(c)),c}})}unsubscribe(...e){return _(this,null,function*(){let{userId:t}=e[0],s=this.remotePublishedUserMap.get(t);if(!s)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${t} ${o}`);try{yield s.unsubscribe({remoteTracks:e,streamType:o})}catch(n){this._log.warn(`unsubscribe() => failed ${n}`)}e.forEach(n=>{n.unsubscribe(),n.mediaType===8&&n.setMediaType(4)}),g.emit(E.UNSUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:s})})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(e=2e3,t){if(e<=0){this._enableAudioVolumeEvaluation=!1,re.clearTask(this._audioVolumeIntervalId);return}e=Math.floor(Math.max(e,100)),g.emit(E.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&re.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=re.run(ds,()=>{var o;let s=[];(o=this.remotePublishedUserMap)==null||o.forEach(n=>{if(n.muteState.hasAudio){let a=Math.floor(n.remoteAudioTrack.getAudioLevel()*100);s.push({userId:n.userId,volume:a})}}),this.emit("audio-volume",s)},{fps:1e3/e,backgroundTask:t})}getLocalAudioStats(){return _(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 _(this,null,function*(){var t,s;let e={};return e[this.userId]=((s=(t=this.uplinkConnection)==null?void 0:t.localMainVideoTrack)==null?void 0:s.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},e})}getTransportStats(){return _(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 s=yield this._stats.getReceiverStats(t);e.downlinksRTT[s.userId]=s.rtt}return e})}getRemoteVideoStats(e){return _(this,null,function*(){let t={};for(let[s,o]of this.remotePublishedUserMap)e==="main"&&o.muteState.hasVideo&&(t[s]=o.remoteVideoTrack.stat),e==="auxiliary"&&o.muteState.hasAuxiliary&&(t[s]=o.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return _(this,null,function*(){let e={};for(let[t,s]of this.remotePublishedUserMap)s.muteState.hasAudio&&(e[t]=s.remoteAudioTrack.stat);return e})}setTurnServer(e,t){this._log.info(`set turn server: ${JSON.stringify(e)} ${t||""}`);let s=[];Array.isArray(e)?e.forEach(o=>s.push(we.getTurnServer(o))):we.isPlainObject(e)&&s.push(we.getTurnServer(e)),this._turnServers=s,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:q.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:V.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:q.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:V.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?q.START_PUBLISH_TENCENT_CDN:q.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?V.START_PUBLISH_TENCENT_CDN_RES:V.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?q.STOP_PUBLISH_TENCENT_CDN:q.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?V.STOP_PUBLISH_TENCENT_CDN_RES:V.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendAbilityStatus(e){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:q.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:V.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(s=>{})}getIceServers(){return this._turnServers.length===0&&this.scheduleResult.iceServers?this.scheduleResult.iceServers:this._turnServers}getIceTransportPolicy(){return this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=we.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._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 _(this,null,function*(){let{subscribeState:t,userId:s,muteState:{hasSmall:o,hasVideo:n}}=e;if(!o&&!n||!t.video&&!t.smallVideo)return;let a=this._changeBigSmallRecords.get(s);if(!a||a.isSubscribing||a.reSubscribeCount<=0)return;let{options:c,reSubscribeCount:d}=a;if(c.video&&t.video||c.smallVideo&&t.smallVideo&&o)return;let l={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:c.video,smallVideo:c.smallVideo};try{if(!o&&l.smallVideo&&(l.video=!0,l.smallVideo=!1),l.smallVideo===t.smallVideo&&l.video===t.video)return;a.isSubscribing=!0,a.reSubscribeCount=d-1,yield e.subscribe(l,"main"),e.remoteVideoTrack.setMediaType(l.smallVideo?8:4),this._log.info(`change [${s}] to ${l.smallVideo?"small":"big"} video successfully. count ${ur-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=ur}catch(p){this._log.info(`change [${s}] to ${l.smallVideo?"small":"big"} video failed. count ${ur-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(s)}})}changeType(e,t){let o={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:ur};this._changeBigSmallRecords.set(t.userId,o),this._log.info(`set [${t.userId}] video prefer type: ${e?"small":"big"}`)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(kh(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!zr(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new b({code:A.INVALID_PARAMETER,message:L({key:M.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(!zr(e.userDefineRecordId)){let s=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(s)===null)throw new b({code:A.INVALID_PARAMETER,message:L({key:M.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!zr(e.userDefinePushArgs))if(kh(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 b({code:A.INVALID_PARAMETER,message:L({key:M.INVALID_USER_DEFINE_PUSH_ARGS})});Eo(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&Or)return this.singlePC.enableInsertableStreams=!0,this.singlePC.startReconnection()}sendSignalMessage(e){var t;return this.signalChannel?(t=this.signalChannel)==null?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new b({code:A.INVALID_OPERATION,message:"not join"}))}};y([Pd(["left",ne.INIT],"joined"),it({settings:{retries:1,timeout:0},onError(r,i,e){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),Mt(!0),this.reset(),i()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),i()):(this.reset(),this._log.error(r),e(r))}}),Wl()],At.prototype,"join",1),y([Pd("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),Jl(),Rn("leave room"),Hs({fnName:"publish",validateArgs:!1}),Hs({fnName:"unsubscribe",validateArgs:!1})],At.prototype,"leave",1),y([$t(),Dh(),it({settings:{retries:qt,timeout:r=>kt(r)},onError(r,i,e){var t;(t=r.message)!=null&&t.includes("timeout")?(this._log.warn("publish timeout"),i()):(this._log.error(`publish failed: ${r}`),e(r),g.emit(E.PUBLISH_FAILED,{room:this}))}})],At.prototype,"publish",1),y([Hs({fnName:"publish"}),cl("api-call"),$t(),Oh(),gt(function(){var r,i;this.localTracks.size===0&&Ri()&&((i=(r=this.singlePC)==null?void 0:r.getPeerConnection())==null||i.getSenders().forEach(e=>e.track&&e.replaceTrack(null)))})],At.prototype,"unpublish",1),y([si(r=>r.userId)],At.prototype,"replaceTrack",1),y([si((...r)=>r[0].userId),Nn(),jl(),it({settings:{retries:qt,timeout:r=>kt(r)},onError(r,i,e,t){r.message.includes("timeout")?(this._log.warn("subscribe timeout"),i()):(this._log.error(`subscribe failed: ${r}`),e(r),g.emit(E.SUBSCRIBE_FAILED,{room:this,remoteTracks:t}))}})],At.prototype,"subscribe",1),y([Hs({fnName:"subscribe",callback(...r){this.singlePC||r.forEach(i=>{let e=this.remotePublishedUserMap.get(i.userId);e&&!e.isMainStreamSubscribed&&!e.isAuxStreamSubscribed&&e.close("you unsubscribed")})}}),si((...r)=>r[0].userId)],At.prototype,"unsubscribe",1);io.create=io._create.bind(io,At);var Cw=io;export{Cw as default};
|
|
95
|
+
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:d,currentDirection:u,direction:p,stopped:m})=>({mid:d,currentDirection:u,direction:p,stopped:m})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._isSDPLogged=!0),this._updateSDPPromise=null,o(c)}})),this._updateSDPPromise}setTransceiverDirection(e,t){return _(this,null,function*(){if(!ie||!this._peerConnection||!this._parsedAnswer)return;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let s=this._peerConnection.getTransceivers();t.forEach(o=>{s[o].direction!==e&&(s[o].direction=e)});for(let o of t){let n=this._parsedAnswer.media[o].direction;e===Q.INACTIVE&&n===Q.RECVONLY&&(this._parsedAnswer.media[o].direction=e),e===Q.SENDONLY&&n===Q.INACTIVE&&(this._parsedAnswer.media[o].direction=Q.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(e=""){return ce(e).media.map(s=>s.direction)}setOffer(e){return this._log.info("setting offer"),this._log.debug(e.sdp),this._peerConnection.setLocalDescription({type:"offer",sdp:Th(e.sdp,this.clientAbility,this._serverAbility)})}setAnswer(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._peerConnection.setRemoteDescription(e)}switchVideoEncoder(e){return _(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach(s=>{var o;if(s.type===h.VIDEO){let n=this._serverAbility.video.codecs.find(a=>a.codec.toLowerCase()===e);n&&!((o=s.payloads)!=null&&o.includes(String(n.payload)))&&(s.fmtp=[],s.payloads="",s.rtp=[],s.rtcpFb=[],ar(s,n),t=!0)}}),t&&(this._log.warn(`switch video encoder to ${e}`),yield this.setOffer(this._peerConnection.localDescription),yield this.setAnswer({type:"answer",sdp:He(this._parsedAnswer)}))})}useHWEncoder(e=!0,t){return _(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let s=!1,o=[];T(t)?o=this._parsedAnswer.media.slice(1,4):t===2?o.push(this._parsedAnswer.media[1]):t===3?o.push(this._parsedAnswer.media[2]):t===7&&o.push(this._parsedAnswer.media[3]),o.forEach(n=>{var a;if(n.type===h.VIDEO){let c;e&&this.is42001fSupported?c=this.clientAbility.video.codecs.find(d=>d.fmtp.includes("42001f")):e||(c=this._serverAbility.video.codecs.find(d=>d.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=[],ar(n,c),s=!0)}}),s&&(this._log.warn(`use ${e?"hw":"sw"} encoder`),yield this.setOffer(this._peerConnection.localDescription),yield this.setAnswer({type:"answer",sdp:He(this._parsedAnswer)}))})}sendDataChannelMessage(e){var t;(t=this._datachannel)==null||t.send(e)}reset(){var e;(e=this._peerConnection)==null||e.close(),this._waitForPCConnectedPromise=null,this._parsedAnswer=null}close(){this._log.info("close pc"),this.insertableStreamsAbortMap.forEach(e=>vt(e.abort)&&e.abort("destroy")),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners()}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map(s=>t[s])}};y([yn("reconnect")],hi.prototype,"startReconnection",1),y([oi(r=>r.userId)],hi.prototype,"addDownlink",1),y([oi(r=>r)],hi.prototype,"removeDownlink",1),y([Ft(!0)],hi.prototype,"updateSDP",1);var $d=class{constructor(i){l(this,"tag");l(this,"len");l(this,"data");let e=new DataView(i);this.tag=e.getUint16(),this.len=e.getUint16(2),this.data=new Uint8Array(i).slice(4,2+2+this.len).buffer}},Fd=class{constructor(i){l(this,"tinyId");l(this,"data");let e=new DataView(i),t=0,s=[];for(;t<e.byteLength;){let o=e.getUint16(t+2),n=new $d(new Uint8Array(i).slice(t,t+2+2+o).buffer);s.push(n),t+=2+2+o}s.forEach(o=>{o.tag===1?this.tinyId=new TextDecoder().decode(o.data):o.tag===2&&(this.data=o.data)})}},Ah=new Set;function cr(){let r=Math.floor(Math.random()*4294967296);return Ah.has(r)?cr():(Ah.add(r),r)}var bh=Se(Ne());var dr=class extends bh.default{constructor(e){super();l(this,"userId");l(this,"tinyId");l(this,"_sdpSemantics");l(this,"_isUplink");l(this,"_room");l(this,"_log");l(this,"_currentState","DISCONNECTED");l(this,"_prevTime",-1);this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=I.createLogger({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:(g.emit(E.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 fo=class extends dr{constructor(e){super(P(N({},e),{isUplink:!0}));l(this,"localMainAudioTrack",null);l(this,"localMainVideoTrack",null);l(this,"localAuxAudioTrack",null);l(this,"localAuxVideoTrack",null);l(this,"_isPublishingAux",!1);l(this,"_publishingLocalAudioTrack");l(this,"_publishingLocalVideoTrack");l(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});l(this,"_flag",0);l(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:s,smallVideoSsrc:o,smallVideoRtxSsrc:n,auxVideoSsrc:a,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:s||0,small:o||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){if(!e&&this._checkPublishStateTimeoutId>0)return;let{publishState:t,serverPublishState:s}=this,o=Object.keys(t).find(n=>t[n]!==s[n]);if(o)if(e)this._log.warn(`publish state not matched, ${o} local:${t[o]} server:${s[o]} ${Cs()} ${Va()}`),D.addCount({key:521e3});else{this._checkPublishStateTimeoutId=re.run(gi,()=>this.checkPublishState(!0),{delay:10*1e3,count:1});return}re.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,s,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(xt()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((s=a[1])!=null&&s.track),e.smallVideo=!!((o=a[2])!=null&&o.track),e.auxVideo=!!((n=a[3])!=null&&n.track)):a.forEach(c=>{c.track&&(c.track.kind===h.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}get serverPublishState(){return{audio:!!(this.flag&_i),bigVideo:!!(this.flag&pi),smallVideo:!!(this.flag&ns),auxVideo:!!(this.flag&wi)}}get muteState(){var e,t,s;return{audio:!!((e=this.localMainAudioTrack)!=null&&e.muted),bigVideo:!!((t=this.localMainVideoTrack)!=null&&t.muted),auxVideo:!!((s=this.localAuxVideoTrack)!=null&&s.muted)}}initialize(){this.installEvents()}close(e){var s;let t=((s=this._peerConnection)==null?void 0:s.getSenders())||[];for(let o of t)o.replaceTrack(null);super.close(e),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){var e,t;this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),(e=this.singlePC)!=null&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(t=this.singlePC)==null||t.on("spc-reconnected",this.onSinglePCReconnected,this),Ni&&this._room.enableSEI&&!g.listeners(E.SEND_SEI_MESSAGE).includes(this.sendSEIByWorker)&&(this.sendSEIByWorker=this.sendSEIByWorker.bind(this),g.on(E.SEND_SEI_MESSAGE,this.sendSEIByWorker))}uninstallEvents(){var e;this.off("connection-state-changed",this.handleConnectionStateChange,this),(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this),g.off(E.SEND_SEI_MESSAGE,this.sendSEIByWorker)}emitConnectionStateChangedEvent(e,t){var n,a,c;let s=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:s,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:s,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:s,state:e}))),o}onVideoEncodeFailed(e){var t,s;e&&e.isMediaTrackActive&&this.videoCodec==="h264"&&(this._log.warn("h264 encoder not working"),(t=this.singlePC)!=null&&t.isVP8EncodeSupported&&(this._log.warn("switch to vp8"),(s=this.singlePC)==null||s.switchVideoEncoder("vp8")))}publish(o){return _(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:s}){var d,u,p,m,f,R,C;if(!this.singlePC)return;yield this.singlePC.waitForPeerConnectionConnected();let{publishState:n,muteState:a}=this;if(e&&(this._publishingLocalAudioTrack=e,n.audio=!0,a.audio=e.muted),t){if(!this.singlePC.isH264EncodeSupported&&!this.singlePC.isVP8EncodeSupported)throw new b({code:A.NOT_SUPPORTED_H264,message:L({key:M.NOT_SUPPORTED_H264ENCODE})});pe&&zt()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn("fallback video to 480p"),t.setProfile(Ze["480p_2"]),yield t.applyProfile()),this._publishingLocalVideoTrack=t,s?(n.auxVideo=!0,a.auxVideo=t.muted):(n.bigVideo=!0,a.bigVideo=t.muted)}this._isPublishingAux=s;let c;if(t&&!s&&t.small&&(c=this._room.videoManager.smallTrack,n.smallVideo=!0),yield this._signalChannel.sendWaitForResponseWithRetry({command:j.SPC_PUBLISH,responseCommand:V.SPC_PUBLISH_RESULT,data:P(N({},this.singlePC.uplinkSSRC),{state:n,muteState:a}),retries:3}),yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:c,isAuxiliary:s}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,t){this[s?"localAuxVideoTrack":"localMainVideoTrack"]=t;let{scaleResolutionDownBy:v}=t;v>1&&(this._log.warn(`setScaleResolutionDownBy ${t.streamType} ${v}`),yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[s?3:1],v))}e&&(this[s?"localAuxAudioTrack":"localMainAudioTrack"]=e),yield this.singlePC.setBandwidth({audio:((d=this.localMainAudioTrack)==null?void 0:d.profile.bitrate)||((u=this.localAuxAudioTrack)==null?void 0:u.profile.bitrate),bigVideo:(p=this.localMainVideoTrack)==null?void 0:p.profile.bitrate,smallVideo:(f=(m=this.localMainVideoTrack)==null?void 0:m.small)==null?void 0:f.bitrate,auxVideo:(R=this.localAuxVideoTrack)==null?void 0:R.profile.bitrate}),this.sendMediaSettings(),this.installTrackMuteEvents(e,t),!s&&(this._room.preferHW||((C=this._room.scheduleResult.config)==null?void 0:C.preferHW))&&t&&t.profile.width*t.profile.height>=1280*720&&this.singlePC.useHWEncoder(!0,2)})}publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:s,isAuxiliary:o}){if(!tt())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(),d=[],u=[],p=(f,R,C)=>{var U;let v=c[R].sender.replaceTrack(C);u.push(R),(U=this.singlePC)!=null&&U.enableInsertableStreams&&v.then(()=>this.createEncodedStreams(c[R].sender,f)),d.push(v)};a&&p(e.mediaType,0,a),n&&p(t.mediaType,o?3:1,n),s&&p(8,2,s);let m=this.singlePC.setTransceiverDirection(Q.SENDONLY,u);return d.push(m),Promise.all(d)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._publishingLocalAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._publishingLocalVideoTrack;case 2:return this.localAuxVideoTrack||this._publishingLocalVideoTrack;default:return null}}createEncodedStreams(e,t){var a,c;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let s=e.createEncodedStreams(),o=new AbortController;(a=this.singlePC)==null||a.addAbortController(e,o),((c=this.getTrackByMediaType(t))!=null&&c.enableEncodeFrame?s.readable.pipeThrough(new TransformStream({transform:(d,u)=>{var m;let p=this.getTrackByMediaType(t);u.enqueue(((m=this.singlePC)==null?void 0:m.isUsingH264)&&p?p.encodeFrame(d,t===8):d)}}),o):s.readable).pipeTo(s.writable,o).catch(d=>{this._log.debug("encoded stream error",d),d!=="destory"&&this._log.warn(d)})}sendSEIByWorker({room:e,isMain:t}){var o;if(e!==this._room||!this._peerConnection||!this.singlePC||!this._room.videoManager.seiWorker)return;let s=this._peerConnection.getSenders()[t?1:3];if(!!s&&(s.transform||(s.transform=new RTCRtpScriptTransform(this._room.videoManager.seiWorker,{isReceiver:!1,isMain:t})),t&&((o=this.localMainVideoTrack)==null?void 0:o.small))){let n=this._peerConnection.getSenders()[2];n.transform||(n.transform=new RTCRtpScriptTransform(this._room.videoManager.seiWorker,{isReceiver:!1,isMain:t,small:!0}))}}enableSmall(e){return _(this,null,function*(){if(!this.singlePC)return;let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.singlePC.setTransceiverDirection(Q.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(Q.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(s){return _(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){let o=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localMainAudioTrack&&!this.localAuxAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=P(N({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),c.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=P(N({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.singlePC.setTransceiverDirection(Q.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return _(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},s=yield this._signalChannel.sendWaitForResponseWithRetry({command:j.PUBLISH_STATE_CHANGE,data:t,responseCommand:V.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(s.data.code,s.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:j.UNPUBLISH,commandDesc:"unpublish",responseCommand:V.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===A.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let s=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:o,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:o=this._publishingLocalVideoTrack),Pt){if(s&&s.outMediaTrack){let a=s.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=s.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=o.profile.bitrate*1e3,o.small&&(this._mediaSettings.smallVideoWidth=o.small.width,this._mediaSettings.smallVideoHeight=o.small.height,this._mediaSettings.smallVideoFps=o.small.frameRate,this._mediaSettings.smallVideoBps=o.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else s&&s.outMediaTrack&&(this._mediaSettings.audioChannel=s.profile.channelCount,this._mediaSettings.audioBps=s.profile.bitrate*1e3,this._mediaSettings.audioFs=s.profile.sampleRate),o&&o.outMediaTrack&&(this._mediaSettings.videoWidth=o.profile.width,this._mediaSettings.videoHeight=o.profile.height,this._mediaSettings.videoFps=o.profile.frameRate,this._mediaSettings.videoBps=o.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:j.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:V.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return _(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?h.AUXILIARY:h.MAIN} stream`),xt()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return _(this,null,function*(){var o;if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield s[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)==null?void 0:o.small)&&(yield s[2].sender.replaceTrack(this._room.videoManager.smallTrack)),s[n].direction===Q.INACTIVE&&(yield this.singlePC.setTransceiverDirection(Q.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(e){return _(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?h.AUXILIARY:h.MAIN} stream`),xt()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return _(this,null,function*(){if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(null);else{let o=t?3:1;yield s[o].sender.replaceTrack(null),o===1&&this._room.videoManager.hasSmall&&(yield s[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(Q.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(e){return _(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders(),s=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!s||t.find(a=>a.track===s))return!1;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${s.kind} track ${s.id} on ${o?h.AUXILIARY:h.MAIN} stream`),s.kind===h.AUDIO&&t[0]&&(yield t[0].replaceTrack(s)),s.kind===h.VIDEO&&(!o&&t[1]&&(yield t[1].replaceTrack(s)),o&&t[3]&&(yield t[3].replaceTrack(s))),!0})}setBandwidth(o){return _(this,arguments,function*({bandwidth:e,type:t,videoType:s}){if(this.singlePC){let n={};t===h.AUDIO?n.audio=e:s==="big"?n.bigVideo=e:s==="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.muteState)}`),this._signalChannel.sendWaitForResponseWithRetry({command:j.UPDATE_MUTE_STAT,responseCommand:V.MUTE_RESULT,data:this.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&g.emit(E.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=h.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===h.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===h.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===h.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===h.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===Vi?(this._log.error(Ae.NOT_SUPPORTED_H264ENCODE),new b({code:A.NOT_SUPPORTED_H264,message:L({key:M.NOT_SUPPORTED_H264ENCODE})})):new b({code:A.UNKNOWN,message:L({key:M.SIGNAL_RESPONSE_FAILED,data:{signalResponse:V.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return _(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}))})}};y([Tt(function({localVideoTrack:r}){r==null||r.once("6",this.onVideoEncodeFailed,this)})],fo.prototype,"publish",1),y([Tt(function({localVideoTrack:r}){r==null||r.off("6",this.onVideoEncodeFailed,this)})],fo.prototype,"unpublish",1);var Hd=fo;function Nh(r){return Object.keys(r).filter(i=>r[i])}var zr=class extends dr{constructor(e){super(P(N({},e),{isUplink:!1}));l(this,"_flag",0);l(this,"role","anchor");l(this,"remoteAudioTrack");l(this,"remoteVideoTrack");l(this,"remoteAuxiliaryTrack");l(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});this.flag=e.flag,this.remoteAudioTrack=new ni(this._room,this),this.remoteVideoTrack=new St(this._room,this),this.remoteAuxiliaryTrack=new Br(this._room,this),this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264"}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 Ri(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,s,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===h.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){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))}uninstallEvents(){!this.singlePC||(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),s}onTrack(e){let t=e.streams[0],{track:s,receiver:o}=e;if(!t.id.includes(this.tinyId))return;let a=t.id.includes("aux")?"auxiliary":"main";this._log.debug(`ontrack ${a} ${s.kind}`);let c=h.AUDIO;s.kind===h.VIDEO&&(c=a===h.MAIN?h.VIDEO:h.AUXILIARY);let d=this.remoteAudioTrack;c===h.VIDEO?d=this.remoteVideoTrack:c===h.AUXILIARY&&(d=this.remoteAuxiliaryTrack),this._room.enableSEI&&Ni&&this.receiveSEIByWorker(o,a),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(d,o),d.setInputMediaStreamTrack(s)}createEncodedStreams(e,t){if(!this.singlePC.insertableStreamsAbortMap.has(t)){let s=t.createEncodedStreams(),o=new AbortController,n={abortController:o,enqueue:c=>{var d;return(d=this.singlePC)!=null&&d.isUsingH264?e.decodeFrame(c):c}};(e.enableDecodeFrame?s.readable.pipeThrough(new TransformStream({transform:(c,d)=>d.enqueue(n.enqueue(c))})):s.readable).pipeTo(s.writable,o).catch(c=>{c!=="destory"&&this._log.warn(c)}),this.singlePC.addAbortController(t,o)}}receiveSEIByWorker(e,t){e.track.kind===h.AUDIO||!this._peerConnection||!this.singlePC||!this._room.videoManager.seiWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this._room.videoManager.seiWorker,{isReceiver:!0,userId:this.userId,streamType:t}))}subscribe(e,t){return _(this,null,function*(){try{if(this._log.info(`subscribe ${t} ${Nh(e)}`),this.hasSSRC){let s="subscribe_change";Object.values(e).find(o=>o===!0)||(s="unsubscribe"),yield this.sendSubscription(s,e)}else yield this.doSubscribe(e),this.checkTrackEnded(e)}catch(s){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${s.message} ${JSON.stringify(this.muteState)}`),new b({code:A.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):s}})}checkTrackEnded(e){var t,s,o;if((e.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||e.video&&((s=this.remoteVideoTrack.mediaTrack)==null?void 0:s.readyState)==="ended"||e.auxiliary&&((o=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:o.readState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),Pe&&mt<92)return;this.singlePC.startReconnection()}}unsubscribe(s){return _(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 o=N({},this.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(c=>c===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${Nh(o)}]`),n==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(n,o),n==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,t=this.subscribeState){let s={srcTinyId:this.tinyId,srcUserId:this.userId},o=j.UNSUBSCRIBE,n=V.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(s={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=j.SUBSCRIBE_CHANGE,n=V.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:o,data:s,responseCommand:n,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let c=new b({code:a.code,message:L({key:M.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(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn(`resubscribe ${JSON.stringify(this.subscribeState)}`),this.doSubscribe(this.subscribeState))}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return _(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 s={audioSsrc:cr(),bigVideoSsrc:cr(),bigVideoRtxSsrc:cr(),auxVideoSsrc:cr(),auxVideoRtxSsrc:cr()},{audioSsrc:o,bigVideoSsrc:n,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:d}=s;this.ssrc={audio:o,video:n,videoRtx:a,auxiliary:c,auxiliaryRtx:d},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:j.SPC_SUBSCRIBE,responseCommand:V.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:s},retries:3,retryTimeout:0});if(u.data.code!==0)throw new b({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{let s=this._room.scheduleResult.config;((s==null?void 0:s.jitterDelay)||(s==null?void 0:s.jitterDelayAux))&&this.setJitterBufferDelay({mainDelay:s.jitterDelay,auxDelay:s.jitterDelayAux})}}})}removeDownlink(){return _(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?void 0:e.jitterDelay)||(e==null?void 0:e.jitterDelayAux))&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)})}setJitterBufferDelay({mainDelay:e,auxDelay:t}){if(!this.singlePC||!this._peerConnection||Zt(e)&&Zt(t))return Promise.resolve();this._log.info(`set jitterBuffer main: ${e} aux: ${t}`);let s=this.singlePC.getReceiversByUserId(this.userId);return ee(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),ee(t)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=t,Zt(e)&&(this.remoteAudioTrack.jitterBufferDelay=t)),new Promise(o=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:s,resolve:o})})}doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:s,resolve:o}){let n=-1;try{if(e===0&&t===0)return s.forEach(c=>c.jitterBufferTarget=0),o();if(s.forEach(c=>{var m;let d=c.track===this.remoteAuxiliaryTrack.outMediaTrack||Zt(e)&&c.track===this.remoteAudioTrack.outMediaTrack;if(d&&Zt(t)||!d&&Zt(e))return;let u=d?t||0:e,p=(c.jitterBufferTarget||0)+100;p>u||(c.jitterBufferTarget=p,this._log.debug(`set ${d?"aux ":""}${(m=c==null?void 0:c.track)==null?void 0:m.kind} jitterBuffer delay ${p} -> ${u}`))}),!s.find(c=>{let d=c.track===this.remoteAuxiliaryTrack.outMediaTrack?t||0:e;return c.jitterBufferTarget<d}))return this._log.info(`set jitterBuffer main: ${e} aux: ${t} done`),o();n=setTimeout(()=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:s,resolve:o})},1e3)}catch(a){this._log.warn(`set jitterBuffer delay error: ${a}`),clearTimeout(n),o()}}};y([Ft(),W(r=>function(...i){return new Promise((e,t)=>{let s=o=>{this.off("closed",s),t(new b({code:A.API_CALL_ABORTED,message:L({key:M.CONNECTION_ABORTED,data:o})}))};this.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this.off("closed",s)})})})],zr.prototype,"subscribe",1),y([Ft()],zr.prototype,"unsubscribe",1),y([oi(()=>"jitter")],zr.prototype,"setJitterBufferDelay",1);var vh=zr;function Dh(){return W(r=>function(...i){return _(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(t=>t.outMediaTrack&&t.state==="capture"),!i.length))return;g.emit("61",{room:this});let e=r.apply(this,i);return i.forEach(t=>t.publish(this,e)),e})})}function Oh(){return W(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var Mh=Se(Ne());function rf(){return Math.floor(Math.random()*16383)}var Gd=class extends Mh.EventEmitter{constructor(e,t){super();this.room=e;this.signalChannel=t;l(this,"log");l(this,"cmdIdSeqMap",new Map);l(this,"messageMap",new Map);this.log=I.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(V.RECEIVE_CUSTOM_MSG,this.onReceiveMsg)}send({cmdId:e,data:t}){let s=this.cmdIdSeqMap.get(e)||rf(),o={cmdId:e,msg:btoa(String.fromCharCode(...new Uint8Array(t))),ordered:!0,reliable:!0,streamSeq:s};this.cmdIdSeqMap.set(e,s+1),this.signalChannel.send(j.SEND_CUSTOM_MSG,o),this.log.debug(`send custom msg: ${JSON.stringify(o)}`)}onReceiveMsg(e){let{data:t}=e.data,s=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(s){let o={userId:s,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),n=>n.charCodeAt(0)).buffer};if(t.ordered){let n=`${s}_${o.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(o,!0),100)),a.cachedMessageMap.set(o.seq,{message:o});else if(Math.abs(a.lastSeq-o.seq)>Gd.SEQ_INTERVAL)this.messageMap.set(n,{lastSeq:o.seq,cachedMessageMap:new Map}),this.emitMessage(o);else if(o.seq>a.lastSeq){if(o.seq===a.lastSeq+1)this.emitMessage(o);else if(!a.cachedMessageMap.has(o.seq)){let c=setTimeout(()=>this.emitMessage(o,!0),5e3);a.cachedMessageMap.set(o.seq,{message:o,timeoutId:c})}}else this.log.debug(`drop message ${o.userId}-${o.cmdId}-${o.seq}`)}else this.emit("message",o)}}emitMessage(e,t=!1){var a;let s=this.messageMap.get(`${e.userId}_${e.cmdId}`),o=e;if(s){if(t){let c=[...s.cachedMessageMap.values()].sort((d,u)=>d.message.seq-u.message.seq);c[0]&&(o=c[0].message)}s.lastSeq!==0&&o.seq-s.lastSeq>1&&this.log.debug(`msg lost userId: ${o.userId} seq: ${s.lastSeq} -> ${o.seq}`),s.lastSeq=o.seq,clearTimeout((a=s.cachedMessageMap.get(o.seq))==null?void 0:a.timeoutId),s.cachedMessageMap.delete(o.seq)}this.log.debug(`receive custom msg: ${JSON.stringify(o)}`),this.emit("message",o);let n=s==null?void 0:s.cachedMessageMap.get(o.seq+1);n&&this.emitMessage(n.message)}},Eo=Gd;l(Eo,"SEQ_INTERVAL",300);var{isString:kh,isUndefined:Yr,getNetworkType:sf,isEmpty:go}=we,At=class extends na{constructor(e){super(e);this._heartbeat=-1;this._lastHeartBeatTime=-1;this._joinTimeout=-1;this._firstPublishedList=null;this._joinReject=null;this._isRelayChanged=!1;this.signalChannel=null;this.uplinkConnection=null;this.singlePC=null;this.enableSPC=Mr;this._changeBigSmallRecords=new Map;this._networkQuality=null;this._turnServers=[];this._syncUserListInterval=-1;this._smallStreamConfig={bitrate:100,frameRate:15,height:120,width:160};this.enableSEI=!1;this._enableAudioVolumeEvaluation=!1;this._audioVolumeIntervalId=0;this._enableMultiAuxStream=!1;this._pureAudioPushMode=!1;this.preferHW=!1;this._stats=new lo(this,this._log),this.userManager=new $n(this.userId,this._log),this._version=Re,this.sdpSemantics=ur,Yr(e.sdpSemantics)?Et.isUnifiedPlanDefault()&&(this.sdpSemantics=fi):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${sf()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=Yr(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&Mr,!Yr(e.enableSPC)&&Mr&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new Ih(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]))}join(e,t,s){return _(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",o=>{this.emit("peer-join",o)}),this.userManager.on("2",o=>{this.closeDownLinkConnection(o,"remote user exitRoom"),this.emit("peer-leave",o)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",n=>{var o=qd(n,[]);g.emit(E.REMOTE_PUBLISH_STATE_CHANGED,N({room:this},o)),this.emit("remote-publish-state-changed",N({},o))}),this.joinParams=e,new Promise((o,n)=>_(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 b&&u.code===A.SPC_INITIALIZED_FAILED)(a=this.signalChannel)==null||a.destroy(),yield this.initialize();else return n(u)}let d=x();yield this.doJoin(e,(c=this.singlePC)==null?void 0:c.clientAbility),D.addSuccessEvent({key:521708,cost:x()-d}),o(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(d){D.addFailedEvent({key:521708,error:d}),n(d)}this._joinReject=null}))})}initSinglePC(){return _(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new hi({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",e=>this.emit("sei-message",e)),this.singlePC.once("error",()=>this.fallbackToMPC());try{return yield this.singlePC.initialize()}catch(e){throw this.fallbackToMPC(),new b({code:A.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((s,o)=>_(this,null,function*(){var c,d,u;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(_e.SETUP_FAILED,p=>{this.clearJoinTimeout(),g.emit(E.JOIN_SIGNAL_CONNECTION_END,{room:this,error:p}),o(p)}),de((d=(c=this.scheduleResult)==null?void 0:c.config)==null?void 0:d.singlePC)&&Mr&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2);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:Ua(),netType:vr(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig};this._log.debug(`join room signal data: ${JSON.stringify(n)}`);let a=5e3;((u=this.scheduleResult.config)==null?void 0:u.enterRoomTimeout)&&this.scheduleResult.config.enterRoomTimeout>=1&&(a=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{o(new b({code:A.JOIN_ROOM_FAILED,message:L({key:M.JOIN_ROOM_TIMEOUT})}))},a),g.emit(E.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?j.SPC_JOIN_ROOM:j.JOIN_ROOM,n),this.signalChannel.once(V.JOIN_ROOM_RESULT,p=>{this.clearJoinTimeout();let{code:m,message:f,data:R,tinyId:C}=p.data;g.emit(E.JOIN_RECEIVED_CMD_RES,{room:this,code:m}),m===0?(this._log.info("Join room success, start heartbeat"),C&&(this.tinyId=C),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=R.publishers,this.singlePC&&this.singlePC.connect(R.ability).catch(()=>{}),s()):(this._log.error(`Join room failed result: ${m} error: ${f}`),o(new b({code:A.JOIN_ROOM_FAILED,extraCode:m,message:L({key:M.JOIN_ROOM_FAILED,data:{error:f,code:m}})})))})}))}reJoin(e=!0){return _(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this.joinParams.roomId}`);let t,s=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,s.push(this.initSinglePC().then(o=>(t=o,o)))),this.signalChannel&&(this.signalChannel.race=e,this.signalChannel.close(),s.push(this.signalChannel.connect())),yield Promise.all(s),yield this.doJoin(P(N({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),t),this._log.warn("reJoin success"),Z.logSuccessEvent({userId:this.userId,eventType:Ve.REJOIN}),this.singlePC){let o=n=>{var a;n.state==="CONNECTED"&&((a=this.singlePC)==null||a.off(Jt.CONNECTION_STATE_CHANGED,o),this.uplinkConnection instanceof Hd&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(c=>{c.installEvents(),c.onSinglePCReconnected()}))};this.singlePC.on(Jt.CONNECTION_STATE_CHANGED,o),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof co&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(t){this._log.warn(`reJoin fail ${t}`),this.reset(),Z.logFailedEvent({userId:this.userId,eventType:Ve.REJOIN,error:t}),this.emit("error",new b({code:A.JOIN_ROOM_FAILED,message:L({key:M.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}})}initialize(){return _(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),s=this.signalChannel||Qu(this.userId),o=!!(s&&s.isConnected&&s.keepAlive),n;return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(n=this.scheduleResult.domains[0]),this._log.info(`${o?"reuse":"setup"} signal channel`),o?(s.url=e,s.backupUrl=t,s.room=this,this.signalChannel=s):(this.signalChannel=new qr({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,race:this.enableSPC&&!this.proxy_ws,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?n:void 0}),this._customMessageManager=new Eo(this,this.signalChannel),this._customMessageManager.on("message",a=>{this.emit("custom-message",a)})),this._networkQuality||(this._networkQuality=new or({signalChannel:this.signalChannel,room:this}),this._networkQuality.on(or.EVENT_NETWORK_QUALITY,a=>{this.emit("network-quality",a)})),De(this,this.signalChannel).add(_e.CONNECTION_STATE_CHANGED,a=>{g.emit(E.SIGNAL_CONNECTION_STATE_CHANGED,N({room:this},a)),this.emit("signal-connection-state-changed",a)}).add(_e.RECONNECT_FAILED,a=>{this.reset(),this.emit("error",a)}).add(V.PEER_JOIN,a=>{let{srcTinyId:c,userId:d,role:u}=a.data.data;this.userManager.addUser({userId:d,tinyId:c,role:u})}).add(V.PEER_LEAVE,a=>{let{userId:c,reason:d=0}=a.data.data;this.userManager.deleteUser(c,d)}).add(V.UPDATE_REMOTE_MUTE_STAT,a=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(a.data)}).add(V.CLIENT_BANNED,a=>{let c=a.data.data,{reason:d}=c;if(Z.uploadEvent({log:`stat-banned:${d}`,userId:this.userId}),d==="user_time_out"){this._log.warn(`${d} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[d==="kick"?"error":"info"](`user was banned because of [${d}]`),this.reset(),this.emit("banned",{reason:d})}),this.signalChannel.once(_e.SETUP_SUCCESS,a=>{this.tinyId=a.signalInfo.tinyId,g.emit(E.JOIN_SIGNAL_CONNECTION_END,{room:this})}),g.emit(E.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),o&&g.emit(E.JOIN_SIGNAL_CONNECTION_END,{room:this}),o})}setSignalChannel(e){this.signalChannel=e,e||me(this)}leave(){return _(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),g.emit(E.LEAVE_SEND_CMD,{room:this}),(e=this.signalChannel)==null||e.send(j.LEAVE_ROOM)})}clearNetworkQuality(){this._networkQuality&&(this._networkQuality.stop(),this._networkQuality=null)}closeConnections(){this.remotePublishedUserMap.forEach(e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=re.run(Ei,this.doHeartbeat.bind(this),{delay:2e3}))}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),re.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return _(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 s=(n=this.signalChannel)!=null&&n.isConnected?gu(this.userId):[],o=P(N({str_sdk_version:rs,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:s,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},t),{msg_device_info:N({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:vr()},t.msg_device_info)});if(this.heartbeatReport=o,g.emit(E.HEARTBEAT_REPORT,{room:this,report:o}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(j.ON_QUALITY_REPORT,o);let a=Date.now();this._lastHeartBeatTime>0&&a-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${a-this._lastHeartBeatTime}`),this._lastHeartBeatTime=a}this.emit("heartbeat-report",P(N({},o),{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.map(({userId:s,srcTinyId:o,flag:n})=>{s===this.userId&&this.uplinkConnection&&(this.uplinkConnection.flag=n);let a=this.remotePublishedUserMap.get(s);return a&&this.checkSubscribeBigSmallVideo(a),{userId:s,tinyId:o,flag:n}});g.emit(E.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),this.userManager.setRemotePublishedUserList(t)}closeUplink(e="you unpublished"){this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection instanceof co&&(this.uplinkConnection=null)),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:t,flag:s}){let o=new(this.singlePC?vh:vd)({userId:e,tinyId:t,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:s});this.userManager.addRemotePublishedUser(o),this.installDownlinkEvents(o,e),this.emit("remote-published",o)}closeDownLinkConnection(e,t="remote user unpublished"){let s=this.remotePublishedUserMap.get(e);s&&(s.close(t),this.emit("remote-unpublished",s))}installDownlinkEvents(e,t){e.on("error",s=>{let o=s.getCode();o!==A.ICE_TRANSPORT_ERROR&&(o===A.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",s))}),e.on("connection-state-changed",s=>{this.emit("media-connection-state-changed",P(N({},s),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=re.run(Ei,this.syncUserList.bind(this)))}stopSyncUserListInterval(){re.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:j.GET_USER_LIST,responseCommand:V.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:t})=>{let{code:s,message:o}=t;if(s===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:c,role:d})=>({userId:a,tinyId:c,role:d}));throw L({key:M.SIGNAL_RESPONSE_FAILED,data:{signalResponse:V.USER_LIST_RES,code:s,message:o}})}):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||!Cd)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)===se.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(s=>{if(s instanceof Ke&&!s.getIsReconnecting()){let o=s.getPeerConnection();o&&o.connectionState===se.CLOSED&&(this._log.warn(`[${s.getUserId()}] pc is closed but not reconnect`),s.startReconnection())}})}fallbackToMPC(){return _(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),Z.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(e=this.singlePC)==null||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin(!1)),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new co({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),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()}this.remotePublishedUserMap.forEach(t=>{let s=new vd({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(s,t.userId),this.remotePublishedUserMap.set(t.userId,s),t.isMainStreamSubscribed&&s.subscribe(t.subscribeState,"main"),t.isAuxStreamSubscribed&&s.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 b({code:A.INVALID_OPERATION,message:L({key:M.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy())}switchRole(e){return _(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:j.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:V.SWITCH_ROLE_RES,retries:1};return this._log.info(`switchRole signal data: ${JSON.stringify(t.data)}`),this.signalChannel.sendWaitForResponseWithRetry(t).then(s=>{let{code:o,message:n}=s.data;if(o!==0)throw new b({code:A.SWITCH_ROLE_FAILED,message:L({key:M.SWITCH_ROLE_FAILED,data:{message:n,code:o}})});this.role=e}).catch(s=>{throw s instanceof b&&s.getCode()===A.API_CALL_TIMEOUT&&(s=new b({code:A.SWITCH_ROLE_FAILED,message:L({key:M.SWITCH_ROLE_TIMEOUT})})),this._log.error(s),s})}publish(...e){return _(this,null,function*(){let t={},s={};e.forEach(c=>{c instanceof Oe&&(c instanceof Ht?s.audio=c:t.audio=c),c instanceof ue&&(c instanceof ze&&c.mediaType===2?s.video=c:t.video=c)});let o=go(t),n=go(s);(!o||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new Hd({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new co({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,audioManager:this.audioManager}),this.uplinkConnection.on("connection-state-changed",c=>{this.emit("media-connection-state-changed",P(N({},c),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",c=>{let d=c.getCode();d!==A.ICE_TRANSPORT_ERROR&&(d===A.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",c))}));let a=e.map(c=>c.kind).join(",");o||(this._log.info(`publish() => main ${a}`),yield this.uplinkConnection.publish({localAudioTrack:t.audio,localVideoTrack:t.video,isAuxiliary:!1}),this._log.info("main is published")),n||(this._log.info(`publish() => aux ${a}`),yield this.uplinkConnection.publish({localAudioTrack:s.audio,localVideoTrack:s.video,isAuxiliary:!0}),this._log.info("aux is published"))})}unpublish(...e){return _(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let t={},s={};e.forEach(o=>{!o.mediaTrack||!o.isPublished||(o instanceof Oe&&(o instanceof Ht?s.audio=o:t.audio=o),o instanceof ue&&(o instanceof ze&&o.mediaType===2?s.video=o:t.video=o))});try{let o=e.map(n=>n.kind).join(",");go(t)||(this._log.info(`unpublish() => main ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:t.audio,localVideoTrack:t.video})),go(s)||(this._log.info(`unpublish() => aux ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:s.audio,localVideoTrack:s.video}))}catch(o){}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():this.uplinkConnection.removeTrack(e).then(t=>(e.unpublish(),t))}replaceTrack(e){return!this.uplinkConnection||!e.mediaTrack||!ic()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{t&&g.emit(E.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return _(this,null,function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return _(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:h.VIDEO,videoType:h.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(...e){return _(this,null,function*(){if(e=e.filter(n=>!n.isSubscribed),e.length===0)return;let{userId:t}=e[0],s=this.remotePublishedUserMap.get(t);if(!s)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";try{let n=N({},s.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&&s.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),g.emit(E.SUBSCRIBE_START,{room:this,streamType:o,remotePublishedUser:s,subscribeState:n}),this._log.info(`subscribe() => ${t} ${o} [${ea(n)}] prev: [${ea(s.subscribeState)}]`),yield s.subscribe(n,o),this._log.info(`subscribe ${t} ${o} done`);for(let c of e)c.mediaTrack||(yield c.waitHasMediaTrack());g.emit(E.SUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:s})}catch(n){let a=n instanceof b?n.getCode():A.UNKNOWN,c=n;throw n instanceof b?a===A.REMOTE_STREAM_NOT_EXIST&&(c=new b({code:A.API_CALL_ABORTED,message:L({key:M.API_CALL_ABORTED,data:{message:n.message,userId:t,streamType:o}})}),this._log.warn(c)):(c=new b({code:a,message:L({key:M.SUBSCRIBE_FAILED,data:{message:n.message,userId:t,streamType:o}})}),this._log.error(c)),c}})}unsubscribe(...e){return _(this,null,function*(){let{userId:t}=e[0],s=this.remotePublishedUserMap.get(t);if(!s)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${t} ${o}`);try{yield s.unsubscribe({remoteTracks:e,streamType:o})}catch(n){this._log.warn(`unsubscribe() => failed ${n}`)}e.forEach(n=>{n.unsubscribe(),n.mediaType===8&&n.setMediaType(4)}),g.emit(E.UNSUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:s})})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(e=2e3,t){if(e<=0){this._enableAudioVolumeEvaluation=!1,re.clearTask(this._audioVolumeIntervalId);return}e=Math.floor(Math.max(e,100)),g.emit(E.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&re.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=re.run(ls,()=>{var o;let s=[];(o=this.remotePublishedUserMap)==null||o.forEach(n=>{if(n.muteState.hasAudio){let a=Math.floor(n.remoteAudioTrack.getAudioLevel()*100);s.push({userId:n.userId,volume:a})}}),this.emit("audio-volume",s)},{fps:1e3/e,backgroundTask:t})}getLocalAudioStats(){return _(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 _(this,null,function*(){var t,s;let e={};return e[this.userId]=((s=(t=this.uplinkConnection)==null?void 0:t.localMainVideoTrack)==null?void 0:s.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},e})}getTransportStats(){return _(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 s=yield this._stats.getReceiverStats(t);e.downlinksRTT[s.userId]=s.rtt}return e})}getRemoteVideoStats(e){return _(this,null,function*(){let t={};for(let[s,o]of this.remotePublishedUserMap)e==="main"&&o.muteState.hasVideo&&(t[s]=o.remoteVideoTrack.stat),e==="auxiliary"&&o.muteState.hasAuxiliary&&(t[s]=o.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return _(this,null,function*(){let e={};for(let[t,s]of this.remotePublishedUserMap)s.muteState.hasAudio&&(e[t]=s.remoteAudioTrack.stat);return e})}setTurnServer(e,t){this._log.info(`set turn server: ${JSON.stringify(e)} ${t||""}`);let s=[];Array.isArray(e)?e.forEach(o=>s.push(we.getTurnServer(o))):we.isPlainObject(e)&&s.push(we.getTurnServer(e)),this._turnServers=s,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:j.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:V.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:j.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:V.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?j.START_PUBLISH_TENCENT_CDN:j.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?V.START_PUBLISH_TENCENT_CDN_RES:V.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?j.STOP_PUBLISH_TENCENT_CDN:j.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?V.STOP_PUBLISH_TENCENT_CDN_RES:V.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendAbilityStatus(e){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:j.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:V.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(s=>{})}getIceServers(){return this._turnServers.length===0&&this.scheduleResult.iceServers?this.scheduleResult.iceServers:this._turnServers}getIceTransportPolicy(){return this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=we.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._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 _(this,null,function*(){let{subscribeState:t,userId:s,muteState:{hasSmall:o,hasVideo:n}}=e;if(!o&&!n||!t.video&&!t.smallVideo)return;let a=this._changeBigSmallRecords.get(s);if(!a||a.isSubscribing||a.reSubscribeCount<=0)return;let{options:c,reSubscribeCount:d}=a;if(c.video&&t.video||c.smallVideo&&t.smallVideo&&o)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(!o&&u.smallVideo&&(u.video=!0,u.smallVideo=!1),u.smallVideo===t.smallVideo&&u.video===t.video)return;a.isSubscribing=!0,a.reSubscribeCount=d-1,yield e.subscribe(u,"main"),e.remoteVideoTrack.setMediaType(u.smallVideo?8:4),this._log.info(`change [${s}] to ${u.smallVideo?"small":"big"} video successfully. count ${hr-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=hr}catch(p){this._log.info(`change [${s}] to ${u.smallVideo?"small":"big"} video failed. count ${hr-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(s)}})}changeType(e,t){let o={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:hr};this._changeBigSmallRecords.set(t.userId,o),this._log.info(`set [${t.userId}] video prefer type: ${e?"small":"big"}`)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(kh(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!Yr(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new b({code:A.INVALID_PARAMETER,message:L({key:M.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(!Yr(e.userDefineRecordId)){let s=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(s)===null)throw new b({code:A.INVALID_PARAMETER,message:L({key:M.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!Yr(e.userDefinePushArgs))if(kh(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 b({code:A.INVALID_PARAMETER,message:L({key:M.INVALID_USER_DEFINE_PUSH_ARGS})});go(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&kr)return this.singlePC.enableInsertableStreams=!0,this.singlePC.startReconnection()}sendSignalMessage(e){var t;return this.signalChannel?(t=this.signalChannel)==null?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new b({code:A.INVALID_OPERATION,message:"not join"}))}};y([Vd(["left",ne.INIT],"joined"),it({settings:{retries:1,timeout:0},onError(r,i,e){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),kt(!0),this.reset(),i()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),i()):(this.reset(),this._log.error(r),e(r))}}),Wu()],At.prototype,"join",1),y([Vd("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),Ju(),yn("leave room"),Gs({fnName:"publish",validateArgs:!1}),Gs({fnName:"unsubscribe",validateArgs:!1})],At.prototype,"leave",1),y([Ft(),Dh(),it({settings:{retries:Xt,timeout:r=>Lt(r)},onError(r,i,e){var t;(t=r.message)!=null&&t.includes("timeout")?(this._log.warn("publish timeout"),i()):(this._log.error(`publish failed: ${r}`),e(r),g.emit(E.PUBLISH_FAILED,{room:this}))}})],At.prototype,"publish",1),y([Gs({fnName:"publish"}),du("api-call"),Ft(),Oh(),Tt(function(){var r,i;this.localTracks.size===0&&bi()&&((i=(r=this.singlePC)==null?void 0:r.getPeerConnection())==null||i.getSenders().forEach(e=>e.track&&e.replaceTrack(null)))})],At.prototype,"unpublish",1),y([oi(r=>r.userId)],At.prototype,"replaceTrack",1),y([oi((...r)=>r[0].userId),vn(),ju(),it({settings:{retries:Xt,timeout:r=>Lt(r)},onError(r,i,e,t){r.message.includes("timeout")?(this._log.warn("subscribe timeout"),i()):(this._log.error(`subscribe failed: ${r}`),e(r),g.emit(E.SUBSCRIBE_FAILED,{room:this,remoteTracks:t}))}})],At.prototype,"subscribe",1),y([Gs({fnName:"subscribe",callback(...r){this.singlePC||r.forEach(i=>{let e=this.remotePublishedUserMap.get(i.userId);e&&!e.isMainStreamSubscribed&&!e.isAuxStreamSubscribed&&e.close("you unsubscribed")})}}),oi((...r)=>r[0].userId)],At.prototype,"unsubscribe",1);ro.create=ro._create.bind(ro,At);var Cw=ro;export{Cw as default};
|