95 lines
524 KiB
JavaScript
95 lines
524 KiB
JavaScript
var Dh=Object.create;var jr=Object.defineProperty,Oh=Object.defineProperties,Ud=Object.getOwnPropertyDescriptor,Mh=Object.getOwnPropertyDescriptors,kh=Object.getOwnPropertyNames,mn=Object.getOwnPropertySymbols,Bd=Object.getPrototypeOf,na=Object.prototype.hasOwnProperty,$d=Object.prototype.propertyIsEnumerable,Lh=Reflect.get;var qr=Math.pow,sa=(r,i,e)=>i in r?jr(r,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[i]=e,v=(r,i)=>{for(var e in i||(i={}))na.call(i,e)&&sa(r,e,i[e]);if(mn)for(var e of mn(i))$d.call(i,e)&&sa(r,e,i[e]);return r},w=(r,i)=>Oh(r,Mh(i));var Fd=(r,i)=>{var e={};for(var t in r)na.call(r,t)&&i.indexOf(t)<0&&(e[t]=r[t]);if(r!=null&&mn)for(var t of mn(r))i.indexOf(t)<0&&$d.call(r,t)&&(e[t]=r[t]);return e};var Wt=(r,i)=>()=>(i||r((i={exports:{}}).exports,i),i.exports),Xr=(r,i)=>{for(var e in i)jr(r,e,{get:i[e],enumerable:!0})},xh=(r,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let s of kh(i))!na.call(r,s)&&s!==e&&jr(r,s,{get:()=>i[s],enumerable:!(t=Ud(i,s))||t.enumerable});return r};var Se=(r,i,e)=>(e=r!=null?Dh(Bd(r)):{},xh(i||!r||!r.__esModule?jr(e,"default",{value:r,enumerable:!0}):e,r));var y=(r,i,e,t)=>{for(var s=t>1?void 0:t?Ud(i,e):i,n=r.length-1,o;n>=0;n--)(o=r[n])&&(s=(t?o(i,e,s):o(s))||s);return t&&s&&jr(i,e,s),s};var u=(r,i,e)=>(sa(r,typeof i!="symbol"?i+"":i,e),e);var Ie=(r,i,e)=>Lh(Bd(r),e,i);var f=(r,i,e)=>new Promise((t,s)=>{var n=c=>{try{a(e.next(c))}catch(d){s(d)}},o=c=>{try{a(e.throw(c))}catch(d){s(d)}},a=c=>c.done?t(c.value):Promise.resolve(c.value).then(n,o);a((e=e.apply(r,i)).next())});var Ne=Wt((qf,oa)=>{"use strict";var Ph=Object.prototype.hasOwnProperty,xe="~";function Qr(){}Object.create&&(Qr.prototype=Object.create(null),new Qr().__proto__||(xe=!1));function wh(r,i,e){this.fn=r,this.context=i,this.once=e||!1}function Hd(r,i,e,t,s){if(typeof e!="function")throw new TypeError("The listener must be a function");var n=new wh(e,t||r,s),o=xe?xe+i:i;return r._events[o]?r._events[o].fn?r._events[o]=[r._events[o],n]:r._events[o].push(n):(r._events[o]=n,r._eventsCount++),r}function pn(r,i){--r._eventsCount===0?r._events=new Qr:delete r._events[i]}function be(){this._events=new Qr,this._eventsCount=0}be.prototype.eventNames=function(){var i=[],e,t;if(this._eventsCount===0)return i;for(t in e=this._events)Ph.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,n=t.length,o=new Array(n);s<n;s++)o[s]=t[s].fn;return o};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,n,o){var a=xe?xe+i:i;if(!this._events[a])return!1;var c=this._events[a],d=arguments.length,l,m;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,n),!0;case 6:return c.fn.call(c.context,e,t,s,n,o),!0}for(m=1,l=new Array(d-1);m<d;m++)l[m-1]=arguments[m];c.fn.apply(c.context,l)}else{var p=c.length,_;for(m=0;m<p;m++)switch(c[m].once&&this.removeListener(i,c[m].fn,void 0,!0),d){case 1:c[m].fn.call(c[m].context);break;case 2:c[m].fn.call(c[m].context,e);break;case 3:c[m].fn.call(c[m].context,e,t);break;case 4:c[m].fn.call(c[m].context,e,t,s);break;default:if(!l)for(_=1,l=new Array(d-1);_<d;_++)l[_-1]=arguments[_];c[m].fn.apply(c[m].context,l)}}return!0};be.prototype.on=function(i,e,t){return Hd(this,i,e,t,!1)};be.prototype.once=function(i,e,t){return Hd(this,i,e,t,!0)};be.prototype.removeListener=function(i,e,t,s){var n=xe?xe+i:i;if(!this._events[n])return this;if(!e)return pn(this,n),this;var o=this._events[n];if(o.fn)o.fn===e&&(!s||o.once)&&(!t||o.context===t)&&pn(this,n);else{for(var a=0,c=[],d=o.length;a<d;a++)(o[a].fn!==e||s&&!o[a].once||t&&o[a].context!==t)&&c.push(o[a]);c.length?this._events[n]=c.length===1?c[0]:c:pn(this,n)}return this};be.prototype.removeAllListeners=function(i){var e;return i?(e=xe?xe+i:i,this._events[e]&&pn(this,e)):(this._events=new Qr,this._eventsCount=0),this};be.prototype.off=be.prototype.removeListener;be.prototype.addListener=be.prototype.on;be.prefixed=xe;be.EventEmitter=be;typeof oa!="undefined"&&(oa.exports=be)});var ja=Wt((pE,Tu)=>{var gu=Tu.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(gu).forEach(function(r){var i=gu[r];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var Au=Wt(Zt=>{var Cr=function(r){return String(Number(r))===r?Number(r):r},Jm=function(r,i,e,t){if(t&&!e)i[t]=Cr(r[1]);else for(var s=0;s<e.length;s+=1)r[s+1]!=null&&(i[e[s]]=Cr(r[s+1]))},jm=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;Jm(e.match(r.reg),s,r.names,r.name),r.push&&i[r.push].push(s)},Su=ja(),qm=RegExp.prototype.test.bind(/^([a-z])=(.*)/);Zt.parse=function(r){var i={},e=[],t=i;return r.split(/(\r\n|\r|\n)/).filter(qm).forEach(function(s){var n=s[0],o=s.slice(2);n==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(Su[n]||[]).length;a+=1){var c=Su[n][a];if(c.reg.test(o))return jm(c,t,o)}}),i.media=e,i};var Iu=function(r,i){var e=i.split(/=(.+)/,2);return e.length===2?r[e[0]]=Cr(e[1]):e.length===1&&i.length>1&&(r[e[0]]=void 0),r};Zt.parseParams=function(r){return r.split(/;\s?/).reduce(Iu,{})};Zt.parseFmtpConfig=Zt.parseParams;Zt.parsePayloads=function(r){return r.toString().split(" ").map(Number)};Zt.parseRemoteCandidates=function(r){for(var i=[],e=r.split(" ").map(Cr),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};Zt.parseImageAttributes=function(r){return r.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(Iu,{})})};Zt.parseSimulcastStreamList=function(r){return r.split(";").map(function(i){return i.split(",").map(function(e){var t,s=!1;return e[0]!=="~"?t=Cr(e):(t=Cr(e.substring(1,e.length)),s=!0),{scid:t,paused:s}})})}});var Ru=Wt((_E,Cu)=>{var qa=ja(),Xm=/%[sdv%]/g,Qm=function(r){var i=1,e=arguments,t=e.length;return r.replace(Xm,function(s){if(i>=t)return s;var n=e[i];switch(i+=1,s){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}})},vs=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 n=0;n<i.names.length;n+=1){var o=i.names[n];i.name?s.push(e[i.name][o]):s.push(e[i.names[n]])}else s.push(e[i.name]);return Qm.apply(null,s)},zm=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Ym=["i","c","b","a"];Cu.exports=function(r,i){i=i||{},r.version==null&&(r.version=0),r.name==null&&(r.name=" "),r.media.forEach(function(n){n.payloads==null&&(n.payloads="")});var e=i.outerOrder||zm,t=i.innerOrder||Ym,s=[];return e.forEach(function(n){qa[n].forEach(function(o){o.name in r&&r[o.name]!=null?s.push(vs(n,o,r)):o.push in r&&r[o.push]!=null&&r[o.push].forEach(function(a){s.push(vs(n,o,a))})})}),r.media.forEach(function(n){s.push(vs("m",qa.m[0],n)),t.forEach(function(o){qa[o].forEach(function(a){a.name in n&&n[a.name]!=null?s.push(vs(o,a,n)):a.push in n&&n[a.push]!=null&&n[a.push].forEach(function(c){s.push(vs(o,a,c))})})})}),s.join(`\r
|
|
`)+`\r
|
|
`}});var yu=Wt(ei=>{var Ui=Au(),Km=Ru();ei.write=Km;ei.parse=Ui.parse;ei.parseParams=Ui.parseParams;ei.parseFmtpConfig=Ui.parseFmtpConfig;ei.parsePayloads=Ui.parsePayloads;ei.parseRemoteCandidates=Ui.parseRemoteCandidates;ei.parseImageAttributes=Ui.parseImageAttributes;ei.parseSimulcastStreamList=Ui.parseSimulcastStreamList});var Ed=Wt((wD,Hl)=>{var Fl=Hl.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(Fl).forEach(function(r){var i=Fl[r];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var Jl=Wt(ci=>{var Fr=function(r){return String(Number(r))===r?Number(r):r},Tf=function(r,i,e,t){if(t&&!e)i[t]=Fr(r[1]);else for(var s=0;s<e.length;s+=1)r[s+1]!=null&&(i[e[s]]=Fr(r[s+1]))},Sf=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;Tf(e.match(r.reg),s,r.names,r.name),r.push&&i[r.push].push(s)},Gl=Ed(),If=RegExp.prototype.test.bind(/^([a-z])=(.*)/);ci.parse=function(r){var i={},e=[],t=i;return r.split(/(\r\n|\r|\n)/).filter(If).forEach(function(s){var n=s[0],o=s.slice(2);n==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(Gl[n]||[]).length;a+=1){var c=Gl[n][a];if(c.reg.test(o))return Sf(c,t,o)}}),i.media=e,i};var Wl=function(r,i){var e=i.split(/=(.+)/,2);return e.length===2?r[e[0]]=Fr(e[1]):e.length===1&&i.length>1&&(r[e[0]]=void 0),r};ci.parseParams=function(r){return r.split(/;\s?/).reduce(Wl,{})};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(Fr),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(Wl,{})})};ci.parseSimulcastStreamList=function(r){return r.split(";").map(function(i){return i.split(",").map(function(e){var t,s=!1;return e[0]!=="~"?t=Fr(e):(t=Fr(e.substring(1,e.length)),s=!0),{scid:t,paused:s}})})}});var ql=Wt((UD,jl)=>{var gd=Ed(),Af=/%[sdv%]/g,Cf=function(r){var i=1,e=arguments,t=e.length;return r.replace(Af,function(s){if(i>=t)return s;var n=e[i];switch(i+=1,s){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}})},Zs=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 n=0;n<i.names.length;n+=1){var o=i.names[n];i.name?s.push(e[i.name][o]):s.push(e[i.names[n]])}else s.push(e[i.name]);return Cf.apply(null,s)},Rf=["v","o","s","i","u","e","p","c","b","t","r","z","a"],yf=["i","c","b","a"];jl.exports=function(r,i){i=i||{},r.version==null&&(r.version=0),r.name==null&&(r.name=" "),r.media.forEach(function(n){n.payloads==null&&(n.payloads="")});var e=i.outerOrder||Rf,t=i.innerOrder||yf,s=[];return e.forEach(function(n){gd[n].forEach(function(o){o.name in r&&r[o.name]!=null?s.push(Zs(n,o,r)):o.push in r&&r[o.push]!=null&&r[o.push].forEach(function(a){s.push(Zs(n,o,a))})})}),r.media.forEach(function(n){s.push(Zs("m",gd.m[0],n)),t.forEach(function(o){gd[o].forEach(function(a){a.name in n&&n[a.name]!=null?s.push(Zs(o,a,n)):a.push in n&&n[a.push]!=null&&n[a.push].forEach(function(c){s.push(Zs(o,a,c))})})})}),s.join(`\r
|
|
`)+`\r
|
|
`}});var Td=Wt(di=>{var Zi=Jl(),bf=ql();di.write=bf;di.parse=Zi.parse;di.parseParams=Zi.parseParams;di.parseFmtpConfig=Zi.parseFmtpConfig;di.parsePayloads=Zi.parsePayloads;di.parseRemoteCandidates=Zi.parseRemoteCandidates;di.parseImageAttributes=Zi.parseImageAttributes;di.parseSimulcastStreamList=Zi.parseSimulcastStreamList});import XP from"webrtc-adapter";var Ll=Se(Ne());var Gd=(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))(Gd||{}),A=Gd;var Vh=function(r){for(let i in A)if(A[i]===r)return i;return"UNKNOWN"},aa=class extends Error{constructor({name:e="RtcError",message:t,code:s=A.UNKNOWN,extraCode:n=0,constraint:o}){let a=`<${Vh(s)} 0x${s.toString(16)}>`,c=`${t}${o?` constraint: ${o}`:""}${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=n,this.name=e,this.message=c,this.constraint=o,this.originMessage=t}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},b=aa;var Wd=new Date().getTime(),ca=0,Jd=function(r){Wd=r,ca=Wd-new Date().getTime();let i=new Date;i.setTime(r),S.info(`baseTime from server: ${i} offset: ${ca}`)},zr=function(){return new Date().getTime()+ca},fn=function(){let r=new Date;return r.setTime(zr()),r.toLocaleString()};var Pe={};Xr(Pe,{bytes2ms:()=>vm,convertObjectNumberToInt:()=>jn,copyProperties:()=>Nm,deepClone:()=>Sr,deepMerge:()=>Yt,delay:()=>qn,fibonacci:()=>Tr,formatedTime:()=>Vm,getAbilityConfigUrl:()=>au,getConstructorName:()=>Wn,getContainerFromElement:()=>Pm,getEnv:()=>bm,getInternalVersion:()=>km,getLoggerUrl:()=>Si,getMuteStateFromFlag:()=>Ai,getNetworkType:()=>uu,getNumNetworkType:()=>Ir,getReconnectionTimeout:()=>Mt,getStringByteLength:()=>Jn,getTurnServer:()=>xm,getUint32Version:()=>Ha,getValueType:()=>_e,getViewListFromView:()=>ys,glog:()=>pu,ipv4ToUint32:()=>Rs,isArray:()=>he,isAudioWorkletSupported:()=>Mm,isBoolean:()=>pe,isConstructor:()=>Cs,isEmpty:()=>Ba,isFunction:()=>z,isLangChinese:()=>Nt,isMediaStreamTrack:()=>Om,isNumber:()=>ee,isObject:()=>mt,isOverseaSdkAppId:()=>Ts,isPlainObject:()=>Ge,isPortrait:()=>Fa,isPromise:()=>As,isRemoteTrack:()=>ft,isString:()=>Y,isUndefined:()=>g,loadImage:()=>bs,ms2bytes:()=>Dm,ms2samples:()=>mu,performanceNow:()=>x,promiseAny:()=>Ss,samples2ms:()=>hu,setNetworkType:()=>Ua,stringify:()=>pt,stringifyIncludeValue:()=>$a,throttlePromise:()=>Ga});var Ia={};Xr(Ia,{AUDIO_MUTE_BIT:()=>In,AUDIO_STAT_BIT:()=>mi,AUX_STAT_BIT:()=>Li,AUX_STREAM_MSID:()=>ma,BACKEND_ENV:()=>Sn,BASE_DOC_URL:()=>At,BASE_HOST:()=>jd,CAPABILITIES_KEYS:()=>Rn,CLASS_NAME:()=>sm,CLOUD_CONSOLE_URL:()=>Fh,DATA_FREEZE_TIMING:()=>Cn,DOC_URL:()=>Hh,DTLS_STATE_UNKNOWN:()=>ot,ENV_NAME:()=>Jt,EXCHANGE_SDP_TIMEOUT:()=>ga,INTERVAL:()=>wi,IS_WORKER:()=>sr,IS_WORKLET:()=>Kr,KIBANA_EVENT:()=>we,LOCAL_STREAM_PUBLISH_STATE:()=>Qd,LOGGER_CMD_TYPE:()=>li,LOGGER_DOMAIN:()=>ua,LOGGER_DOMAIN_OVERSEA:()=>la,LOG_LEVEL:()=>nt,LOG_LEVEL_NAME:()=>om,MAIN_STREAM_MSID:()=>ts,MICROPHONE_COMMUNICATIONS:()=>nm,MICROPHONE_DEFAULT:()=>Pi,NAME:()=>h,NETWORK_TYPE:()=>_n,NOT_SUPPORTED_H264:()=>xi,PAUSED_RETRY_COUNT:()=>Ta,PEERCONNECTION_CONNECTING_TIMEOUT:()=>is,PEER_CONNECTION_STATE:()=>se,PEER_LEAVE_REASON:()=>Sa,RAF:()=>ss,RECOVER_CAPTURE_INTERVAL:()=>ar,REMOTE_STREAM_TYPE_AUX:()=>fa,REMOTE_STREAM_TYPE_MAIN:()=>pa,RENDER_FREEZE_TIMING:()=>em,RIC:()=>fi,SCHEDULE_DOMAIN:()=>at,SCHEDULE_TIMEOUT:()=>rm,SDP_SEMANTICS_PLAN_B:()=>nr,SDP_SEMANTICS_UNIFIED_PLAN:()=>pi,SECOND_HOST:()=>Bh,SIGNAL_PING_PONG_INTERVAL:()=>Wh,SIGNAL_PING_TIMEOUT:()=>Gh,SIGNAL_RECONNECTION_COUNT:()=>Kh,SMALL_STAT_BIT:()=>es,SPEAKER_DEFAULT:()=>rs,STORAGE_EXPIRES_TIME:()=>En,STREAM_TYPE_BIG:()=>tm,STREAM_TYPE_SMALL:()=>im,SUBSCRIBE_SMALL_RETRY_COUNT:()=>or,SYNC_USER_LIST_INTERVAL:()=>Zh,Scene:()=>Ct,Switch:()=>qd,THIRD_HOST:()=>$h,TIMEOUT:()=>_i,TRANSPORT_DIRECTION:()=>q,TRTC_ERROR_ASSISTANCE:()=>ha,TRTC_QUALITY_BAD:()=>Qh,TRTC_QUALITY_DISCONNECTED:()=>Yh,TRTC_QUALITY_EXCELLENT:()=>jh,TRTC_QUALITY_GOOD:()=>qh,TRTC_QUALITY_POOR:()=>Xh,TRTC_QUALITY_UNKNOWN:()=>Jh,TRTC_QUALITY_VERY_BAD:()=>zh,UPDATE_OFFER_TIMEOUT:()=>Ea,VIDEO_MUTE_BIT:()=>An,VIDEO_STAT_BIT:()=>hi,audioProfileMap:()=>gn,getRetryCount:()=>jt,getScriptDir:()=>Uh,innerVersion:()=>Yr,loggerProxy:()=>Zr,screenProfileMap:()=>Tn,setLoggerProxy:()=>ki,setRetryCount:()=>_a,setVersion:()=>da,version:()=>Re,videoProfileMap:()=>Ke});var Yr="4.15.00.1600",Re="5.0.0";function da(r){Re=r;let[i,e,t]=r.split(".").map(s=>parseInt(s,10));Yr=`${i}.${Math.min(15,e)}.${Math.min(15,t)}.${e.toString().padStart(2,"0")}${t.toString().padStart(2,"0")}`}var sr=typeof importScripts!="undefined",Kr=typeof registerProcessor!="undefined",Uh=()=>{let r=sr?self.location.href:document.currentScript.src;return r.substring(0,r.lastIndexOf("/")+1)},Zr="",ki=r=>Zr=r,jd="web.sdk.qcloud.com",Bh="web.sdk.tencent.cn",$h="web.sdk.cloud.tencent.cn",Fh="https://console.cloud.tencent.com/trtc",At=`https://${jd}/trtc/webrtc/v5/doc`,Hh=`${At}/zh-cn/`,ua="https://yun.tim.qq.com",la="https://apisgp.my-imcloud.com",ha="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"},nt=(o=>(o[o.TRACE=0]="TRACE",o[o.DEBUG=1]="DEBUG",o[o.INFO=2]="INFO",o[o.WARN=3]="WARN",o[o.ERROR=4]="ERROR",o[o.NONE=5]="NONE",o))(nt||{}),Gh=18e3,Wh=2e3,_n={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},En=7*24*3600*1e3,qd=(s=>(s.USEAINS="useAINS",s.ENABLEDEBUG="enableDebug",s.USEV2="useV2",s.USEWT="useWt",s))(qd||{}),gn={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}},Ke={"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}},Tn={"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"},Sn={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Ct=(e=>(e.LIVE="live",e.RTC="rtc",e))(Ct||{}),hi=1,es=2,Li=4,mi=8,In=64,An=16,ts="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",ma="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",pa=h.MAIN,fa=h.AUXILIARY,Jh=0,jh=1,qh=2,Xh=3,Qh=4,zh=5,Yh=6,ot="unknown",se={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Xd=1/0;function _a(r){Xd=r}function jt(){return Xd}var Kh=30,we={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"},Zh=1e4,Ea=1e4,ga=1e4,pi="unified-plan",nr="plan-b",xi=1028,Qd=(t=>(t[t.UNPUBLISH=-1]="UNPUBLISH",t[t.PUBLISHING=0]="PUBLISHING",t[t.PUBLISHED=1]="PUBLISHED",t))(Qd||{}),Cn=500,em=1e3,tm=h.BIG,im=h.SMALL,is=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"},rm=2e3,sm={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},Ta=5,Pi="default",rs=Pi,nm="communications",om=Object.keys(nt),Sa=["normal leave","timeout leave","kick","role change"],or=10,ar=2e3,fi="ric",ss="raf",wi="interval",_i="timeout",Rn=["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((n,o)=>{s.onreadystatechange=()=>{if(s.readyState===4)if(s.status>=200&&s.status<300)try{let a=JSON.parse(s.response);n({data:a})}catch(a){n({data:s.response})}else o({status:s.status,statusText:s.statusText||"request failed!"})},s.timeout=t||5e3,s.open(e||"POST",r,!0),s.send(i)})}function Aa(r){return f(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 S.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}`,n="";return Array.isArray(i.type)?n=i.type.join("|"):n=i.type,`'${s}' must be type of ${n} when calling ${e}(), received type: ${_e(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}`,n=`${i.instanceOf.name||i.instanceOf}`;return`'${s}' must be instanceof ${n} when calling ${e}(), received type: ${_e(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 Er={};Xr(Er,{ANDROID_VERSION:()=>ya,CHROME_MAJOR_VERSION:()=>ht,CHROME_VERSION:()=>Hn,EDGE_VERSION:()=>bn,EDG_MAJOR_VERSION:()=>Na,EDG_VERSION:()=>Nn,FIREFOX_MAJOR_VERSION:()=>ba,FIREFOX_VERSION:()=>yn,HUAWEI_VERSION:()=>Un,IE_VERSION:()=>lm,IOS_MAIN_VERSION:()=>_s,IOS_VERSION:()=>Ti,IPADQQB_VERSION:()=>Pn,IS_ANDROID:()=>de,IS_ANDROID_WEBVIEW:()=>fm,IS_ANY_SAFARI:()=>bt,IS_CHROME:()=>fr,IS_CHROME_OS:()=>eu,IS_CHROMIUM_BASE:()=>et,IS_EDG:()=>ur,IS_EDGE:()=>dr,IS_ELECTRON:()=>mm,IS_FIREFOX:()=>te,IS_HEADLESS_CHROME:()=>Da,IS_HUAWEI:()=>pm,IS_HUAWEIBROWSER:()=>hs,IS_IE:()=>Zd,IS_IE8:()=>um,IS_IOS:()=>He,IS_IOS_13_OR_14:()=>Ma,IS_IOS_15_1:()=>Oa,IS_IPAD:()=>ns,IS_IPADQQB:()=>us,IS_IPAD_PRO:()=>Ra,IS_IPHONE:()=>Vi,IS_IPOD:()=>Kd,IS_LINUX:()=>wn,IS_LOCAL:()=>Xt,IS_MAC:()=>yt,IS_MACQQB:()=>ds,IS_MIBROWSER:()=>ls,IS_MQQB:()=>pr,IS_NATIVE_ANDROID:()=>dm,IS_OLD_ANDROID:()=>cm,IS_OPPOBROWSER:()=>ps,IS_SAFARI:()=>Ve,IS_SAFARI_15_1:()=>_m,IS_SAMSUNGBROWSER:()=>ms,IS_SOGOU:()=>as,IS_SOGOUM:()=>os,IS_TBS:()=>lt,IS_UCBROWSER:()=>va,IS_VIVOBROWSER:()=>fs,IS_WECHAT:()=>hr,IS_WIN:()=>Ei,IS_WQQB:()=>cs,IS_WX:()=>hm,IS_X5MQQB:()=>mr,IS_XWEB:()=>lr,MACQQB_VERSION:()=>xn,MI_VERSION:()=>Vn,MQQB_VERSION:()=>cr,OPPO_VERSION:()=>$n,SAFARI_VERSION:()=>_r,SAMSUNG_VERSION:()=>Bn,SOGOUM_VERSION:()=>vn,SOGOU_VERSION:()=>Dn,TBS_VERSION:()=>On,UA_DATA_STRING:()=>dt,USER_AGENT:()=>ut,VIVO_VERSION:()=>Fn,WECHAT_VERSION:()=>kn,WQQB_VERSION:()=>Ln,XWEB_VERSION:()=>Mn,browserInfo:()=>Rt,getBrowserInfo:()=>tu,getChromeMajorVersion:()=>gi,getDeviceModel:()=>ka,getOSName:()=>Gn,getOSString:()=>gs,getOSType:()=>Em,getTerminalType:()=>La,getUserAgentData:()=>Es,isLocalStorageEnabled:()=>Qt});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""},Ca=r=>{if(X(r)){let i=new RegExp(`${r}\\/(\\d+)`),e=ut.match(i);if(e&&e[1])return parseFloat(e[1])}return NaN},zd=/AppleWebKit\/([\d.]+)/i.exec(ut),am=zd?parseFloat(zd[1]):NaN,ns=X("iPad"),Ra=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&X("Macintosh"),Vi=X("iPhone")&&!ns,Kd=X("iPod"),He=Vi||ns||Kd||Ra,de=X("Android"),ya=function(){if(de){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}(),cm=de&&X("webkit")&&ya<2.3,dm=de&&ya<5&&am<537,te=X("Firefox"),yn=Ee("Firefox"),ba=Ca("Firefox"),dr=X("Edge"),bn=Ee("Edge"),ur=X("Edg"),Nn=Ee("Edg"),Na=Ca("Edg"),os=X("SogouMobileBrowser"),vn=Ee("SogouMobileBrowser"),as=X("MetaSr\\s"),Dn=Ee("MetaSr\\s"),lt=X("TBS"),On=Ee("TBS"),lr=X("XWEB"),Mn=Ee("XWEB"),um=X("MSIE\\s8\\.0"),Zd=X("MSIE\\/\\d+"),lm=function(){if(Zd){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}(),hr=X("(micromessenger|webbrowser)"),kn=Ee("MicroMessenger"),mr=!lt&&X("MQQBrowser")&&X("COVC"),pr=!lt&&X("MQQBrowser")&&!X("COVC"),cr=pr||mr?Ee("MQQBrowser"):"",cs=!lt&&X(" QQBrowser"),Ln=Ee(" QQBrowser"),ds=!lt&&X("QQBrowserLite"),xn=Ee("QQBrowserLite"),us=!lt&&X("MQBHD"),Pn=Ee("MQBHD"),Ei=X("Windows"),yt=!He&&X("MAC OS X"),wn=!de&&X("Linux"),eu=X("CrOS"),hm=X("MicroMessenger"),va=X("UCBrowser"),mm=X("Electron"),ls=X("MiuiBrowser"),Vn=Ee("MiuiBrowser"),hs=X("HuaweiBrowser"),pm=X("Huawei"),Un=Ee("HuaweiBrowser"),ms=X("SamsungBrowser"),Bn=Ee("SamsungBrowser"),ps=X("HeyTapBrowser"),$n=Ee("HeyTapBrowser"),fs=X("VivoBrowser"),Fn=Ee("VivoBrowser"),gi=()=>Ca("Chrome"),et=X("Chrome"),fr=!dr&&!as&&!os&&!lt&&!lr&&!ur&&!cs&&!ls&&!hs&&!ms&&!ps&&!fs&&et,Da=X("HeadlessChrome"),ht=gi(),Hn=Ee("Chrome"),Ve=!et&&!pr&&!mr&&!ds&&!us&&X("Safari"),bt=Ve||He,_r=Ee("Version"),fm=/Android.*(wv|.0.0.0)/.test(ut),Ti=(()=>{if(Ra)return _r;if(He){let r=ut.match(/OS (\d+)_(\d+)/i);if(r&&r[1]){let i=r[1];return r[2]&&(i+=`.${r[2]}`),i}}return""})(),_s=Number(Ti.split(".")[0]),_m=_r==="15.1",Oa=Ti==="15.1",Ma=(()=>{let r=Number(Ti.split(".")[0]);return r===14||r===13})(),Xt=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",Qt=(()=>{let r;return()=>{if(g(r))try{r=!!window.localStorage}catch(i){r=!1}return r}})(),Rt=tu();function tu(){let r=new Map([[te,["Firefox",yn]],[ur,["Edg",Nn]],[fr,["Chrome",Hn]],[Ve,["Safari",_r]],[lt,["TBS",On]],[lr,["XWEB",Mn]],[hr&&Vi,["WeChat",kn]],[cs,["QQ(Win)",Ln]],[pr,["QQ(Mobile)",cr]],[mr,["QQ(Mobile X5)",cr]],[ds,["QQ(Mac)",xn]],[us,["QQ(iPad)",Pn]],[ls,["MI",Vn]],[hs,["HW",Un]],[ms,["Samsung",Bn]],[ps,["OPPO",$n]],[fs,["VIVO",Fn]],[dr,["EDGE",bn]],[os,["SogouMobile",vn]],[as,["Sogou",Dn]]]),i="unknown",e="unknown";return r.has(!0)&&([i,e]=r.get(!0)),{name:i,version:e}}var ie=null,dt="";function Es(){return f(this,null,function*(){if(ie)return ie;if(!navigator.userAgentData||!z(navigator.userAgentData.getHighEntropyValues))return null;try{return ie=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),ie&&!dt&&(dt=`UAData: ${ie.platform}/${ie.platformVersion}`,ie.architecture&&ie.bitness&&(dt+=` ${ie.architecture}/${ie.bitness}`),ie.mobile&&(dt+=" mobile"),ie.model&&(dt+=` model: ${ie.model}`),ie.fullVersionList&&(dt+=` ${ie.fullVersionList.filter(r=>r.brand!=="Not/A)Brand").map(r=>`${r.brand}/${r.version}`).join(",")}`)),ie}catch(r){return null}})}function ka(){return(ie==null?void 0:ie.model)||""}var Yd=new Map([[de,"Android"],[He,"iOS"],[Ei,"Windows"],[yt,"MacOS"],[wn,"Linux"],[eu,"ChromeOS"]]),Gn=function(){return Yd.get(!0)?Yd.get(!0):ie?ie.platform:"unknown"},gs=()=>{let r=Gn();return r+=`/${Rt.name}/${Ve?Rt.version:Rt.version.split(".")[0]}`,ie!=null&&ie.platformVersion&&(r+=`/${ie.platformVersion}`),ie!=null&&ie.architecture&&(r+=`/${ie.architecture}`),r};function La(){return de?4:Vi?2:ns?3:yt?12:Ei?5:wn?13:1}function Em(){return de?"Android":Vi?"iPhone":ns?"iPad":yt?"Mac":Ei?"Windows":wn?"Linux":"unknown"}var iu=(r,i)=>i?`${At}/${r}/${i}`:`${At}/${r}/index.html`;var gm=()=>{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(ha);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 k(r){let{key:i,data:e,link:t,addDocLink:s=!0}=r,n="",o="",a="";z(Ae[i])?n=Ae[i](e):Y(Ae[i])&&(n=Ae[i]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:d}=gm();t?a=`${t.className}.html#${t.fnName}`:d&&d[i]&&(z(d[i])?a=d[i](e):Y(d[i])&&(a=d[i]));let l=n;return Nt()&&(c&&c[i]&&(z(c[i])?o=c[i](e):Y(c[i])&&(o=c[i])),o&&(s?l=`${o}
|
|
\u8BF7\u67E5\u770B\u6587\u6863: ${iu("zh-cn",a)}
|
|
|
|
`:l=`${o}
|
|
|
|
`,l+=n)),s&&(l+=`
|
|
Refer to: ${iu("en",a)}
|
|
`),l}var Tm=0,Sm=1,ru=2;function Im({retryFunction:r,settings:i,onError:e,onRetrying:t,onRetryFailed:s,onRetrySuccess:n,context:o}){return function(...a){let{retries:c=5,timeout:d=1e3}=i,l=0,m=-1,p=Tm,_=(R,C)=>f(this,null,function*(){let N=o||this;try{let U=yield r.apply(N,a);l>0&&n&&n.call(this,l),l=0,R(U)}catch(U){let Fe=()=>{clearTimeout(m),l=0,p=ru,C(U)},hn=()=>{p!==ru&&l<(z(c)?c():c)?(l++,p=Sm,z(t)&&t.call(this,l,Fe),m=window.setTimeout(()=>{m=-1,_(R,C)},z(d)?d(l):d)):(Fe(),z(s)&&s.call(this,U))};z(e)?e.call(this,{error:U,retry:hn,reject:C,retryFuncArgs:a,retriedCount:l}):hn()}});return new Promise(_)}}var vt=Im;var su=Se(Ne(),1),Am=new su.default,T=Am;var zt=(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))(zt||{});var xa=class{constructor(){this._roomIdMap=new Map;typeof registerProcessor=="undefined"&&(this._configs={sdkAppId:"",userId:"",version:Re,env:Jt.QCLOUD,browserVersion:Rt.name+Rt.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){Xt||!S.isAbleToUpload||this._configs.env===Jt.QCLOUD&&this.uploadEventToKibana(w(v({},i),{result:"success"}))}logFailedEvent(i){if(Xt||!S.isAbleToUpload)return;let{eventType:e,code:t,error:s,userId:n}=i,o={roomId:this._roomIdMap.get(n||this._configs.userId),userId:n,eventType:e,result:"failed",code:t||(s==null?void 0:s.extraCode)||(s==null?void 0:s.code)||A.UNKNOWN};this._configs.env===Jt.QCLOUD&&this.uploadEventToKibana(w(v({},o),{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:fn(),sdkAppId:this._configs.sdkAppId,userId:e||this._configs.userId,version:Re,log:i};t&&(s.errorInfo=t.message,t.stack&&(s.errorInfo+=`
|
|
${t.stack}`)),this.sendRequest(Si(this._configs.sdkAppId,li.LOG),s)}sendRequest(i,e){if(!S.isAbleToUpload){setTimeout(()=>{this.sendRequest(i,e)},1e3);return}qt({url:i,body:JSON.stringify(e)}).catch(()=>{})}},Z=new xa;var Pa=null,wa=!0;document&&document.head.insertAdjacentHTML("beforeend",Object.values(at).map(r=>`<link rel="dns-prefetch" href="https://${r}">`).join(`\r
|
|
`));function Ot(r){pe(r)&&r!==wa&&(wa=r,S.info(`setIsNeedToSchedule ${r}`))}T.on("28",()=>Ot(!0));T.on("63",()=>Ot(!0));T.on("84",()=>Ot(!0));T.on("201",r=>{r.state==="RECONNECTING"&&Ot(!0)});T.on("202",r=>{r.state==="RECONNECTING"&&Ot(!0)});function Cm(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"),n=gr(r,h.MAIN),o=gr(r,h.BACKUP);for(let a of s)if(a.startTime>=e&&(a.name===n||a.name===o)&&a.transferSize>0){let c=a.name===n?h.MAIN:h.BACKUP,d=Math.round(a.duration),l=Math.round(a.domainLookupStart-a.startTime),m=a.redirectStart>0?Math.round(a.redirectEnd-a.redirectStart):0,p=a.fetchStart>0?Math.round(a.domainLookupStart-a.fetchStart):0,_=Math.round(a.domainLookupEnd-a.domainLookupStart),R=Math.round(a.requestStart-a.secureConnectionStart),C=Math.round(a.secureConnectionStart-a.connectStart),N=Math.round(a.responseStart-a.requestStart),U=Math.round(a.responseEnd-a.responseStart),Fe=[_,R,C,N,U];Z.uploadEvent({log:`stat-schedule-net:${d}(${l}(${m}->${p})->${Fe.join("->")}) ${c}`,userId:i}),t=w(v({},t),{totalCost:d,local:l,dns:_,tcp:C,tls:R,request:N,response:U});break}}catch(s){S.error("getScheduleDetailCost error",s)}return t}function ou(d){return f(this,arguments,function*({userId:r,sdkAppId:i,useStringRoomId:e,roomId:t,userSig:s,version:n,frameWorkType:o,role:a,latencyLevel:c}){if(!wa&&Pa)return{isCached:!0,result:Pa};let l={delta:0,count:[1,1],msg:[],detail:[]};try{let m=new FormData;m.append("userId",String(r)),m.append("sdkAppId",String(i)),m.append("isStrGroupId",String(e)),m.append("groupId",String(t)),m.append("sdkVersion",n),m.append("userSig",String(s)),a&&m.append("role",String(a)),c&&m.append("latencyLevel",String(c)),o&&m.append("frameWorkType",String(o));let p=x(),_=yield ym(m,l,i);_.config&&(_.config.loggerDomain&&ki(_.config.loggerDomain),pe(_.config.scheduleCache)&&Ot(!_.config.scheduleCache)),l.delta=x()-p;let R=Cm(Number(i),r,p);return Pa=_,{isCached:!1,result:_,detailCost:R}}catch(m){let p=he(m)?m[0]:m,_=ee(p.code)?p.code:0,R=`schedule failed${p.message?`: ${p.message}`:""}`,C=new b({code:A.SCHEDULE_FAILED,extraCode:_,message:k({key:M.JOIN_ROOM_FAILED,data:{error:R,code:_}})});throw S.error(R,_),C}})}var Ii={main:"",backup:""};function Va(r){he(r)?(Ii.main=r[0],Ii.backup=r[1]):Ii.main=r}function gr(r,i=h.MAIN,e=!1){return`https://${Ii[i]||cu(r,i,e)}/api/v1/config`}function au(r,i=h.MAIN){return`https://${Ii[i]||cu(r,i)}/api/v1/trtcAutoConf`}function cu(r,i=h.MAIN,e=!1){if(Ts(r))return i===h.MAIN?at.MAIN_OVERSEA:at.BACKUP_OVERSEA;let t;return Ts(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 Rm(r,i,e){return new Promise((t,s)=>{qt({url:r,body:i,timeout:e.timeout}).then(n=>{n.data.code===0?t(n.data.data):s({code:n.data.code,message:n.data.msg})}).catch(s)})}var nu=(r,i)=>vt({retryFunction:Rm,settings:{retries:3,timeout:0},onError:i,onRetrying:r});function ym(r,i,e){return new Promise((t,s)=>{let n=null;Ss([nu(o=>i.count[0]=o+1,({error:o,retry:a,retriedCount:c,retryFuncArgs:d})=>{i.msg[0]=o.message,n||(c>=2&&(d[0]=gr(e,h.MAIN,!0)),a())})(gr(e,h.MAIN),r,{get timeout(){return Tr(2+i.count[0])*1e3}}),nu(o=>i.count[1]=o+1,({error:o,retry:a,retriedCount:c,retryFuncArgs:d})=>{i.msg[1]=o.message,n||(c>=2&&(d[0]=gr(e,h.BACKUP,!0)),a())})(gr(e,h.BACKUP),r,{get timeout(){return Tr(2+i.count[1])*1e3}})]).then(o=>{n=o,t(n)}).catch(s)})}var bm=function(){return new URLSearchParams(location.search).get("trtc_env")||""},Ts=r=>Number(r)<14e8,Si=function(r,i){let e;Zr?e=Zr:e=Ts(r)?la:ua;let t=Math.floor(Math.random()*qr(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${t}&sdkappid=${r}&cmdtype=${i}`},Is="unknown";function uu(){if(Is!=="unknown")return Is;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&&(Is=lu(t,s)),Is}function lu(r,i){if(_n[r])return r;switch(r){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function Ua(r){Is=lu(r)}function Ir(){return _n[uu()]}function Nm(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 hu(r/4,i)}function hu(r,i=48e3){return r*1e3/i}function Dm(r,i=48e3){return mu(r,i)*4}function mu(r,i=48e3){return r*i/1e3}var pu=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},Nt=()=>{let r=navigator.language;return r=r.substring(0,2),r==="zh"},Ge=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 Tr(r,i=1,e=1){return r<=1?e:Tr(r-1,e,i+e)}function Mt(r){return r>8?30*1e3:Tr(r)*1e3}function _e(r){return Reflect.apply(Object.prototype.toString,r,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var z=r=>typeof r=="function",g=r=>typeof r=="undefined",Y=r=>typeof r=="string",ee=r=>typeof r=="number",pe=r=>typeof r=="boolean",mt=r=>_e(r)==="object",he=r=>_e(r)==="array",Om=r=>_e(r)==="MediaStreamTrack".toLowerCase(),ft=r=>r.isRemote,As=r=>_e(r)==="promise",Cs=r=>z(r)&&r.prototype.constructor===r,Wn=r=>Cs(r)?r.prototype.constructor.name:"",Mm=typeof AudioWorkletNode!="undefined";function Ss(r){return new Promise((i,e)=>{let t=[];r.forEach(s=>{s.then(i).catch(n=>{t.push(n),t.length===r.length&&e(t)})})})}function x(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var du=r=>+r<10?`0${r}`:r,km=r=>{let i=r.match(/^\d+\.\d+\.\d+/)[0];if(!i)return r;let e=i.split("."),t=du(e[1])+du(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${t}`},Lm=Object.prototype.hasOwnProperty,{toString:W_}=Object.prototype;function Ba(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(Ge(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(Lm.call(r,i))return!1;return!0}}return!1}function Ai(r,i){return{userId:i,hasAudio:!!(r&mi),hasVideo:!!(r&hi),hasAuxiliary:!!(r&Li),hasSmall:!!(r&es),audioMuted:!!(r&In),videoMuted:!!(r&An),audioAvailable:!!(r&mi)&&!(r&In),videoAvailable:!!(r&hi)&&!(r&An)}}function xm(r){let i={urls:`turn:${r.url}`};return!g(r.username)&&!g(r.credential)&&(i.username=r.username,i.credential=r.credential,i.credentialType="password",g(r.credentialType)||(i.credentialType=r.credentialType)),i}function Rs(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 Yt=function(r,i,e,t){if(!(mt(r)&&mt(i)))return 0;let s=0,n=Object.keys(i),o;for(let a=0,c=n.length;a<c;a++)if(o=n[a],!(g(i[o])||e&&e.includes(o)))if(mt(r[o])&&mt(i[o]))s+=Yt(r[o],i[o],e,t);else{if(t&&t.includes(i[o]))continue;r[o]!==i[o]&&(r[o]=Sr(i[o]),s+=1)}return s};function Sr(r){if(he(r)){let i=[];return r.forEach((e,t)=>{i[t]=Sr(e)}),i}if(mt(r)){let i={};return Object.keys(r).forEach(e=>{i[e]=Sr(r[e])}),i}return r}var ys=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},Pm=r=>Y(r)?document.getElementById(r):r,wm=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"}),Vm=()=>wm.format(new Date);function pt(r,{keysToInclude:i,keysToExclude:e}){try{if(he(r))return`[${r.map(o=>pt(o,{keysToInclude:i,keysToExclude:e})).join(",")}]`;if(!Ge(r)||!he(i)&&!he(e))return JSON.stringify(r);let t={},s=new Set(i),n=new Set(e);return Object.keys(r).forEach(o=>{(n.size===0&&s.has(o)||s.size===0&&!n.has(o))&&(t[o]=Ge(r[o])||he(r[o])?JSON.parse(pt(r[o],{keysToExclude:e,keysToInclude:i})):r[o])}),JSON.stringify(t)}catch(t){return"{}"}}function $a(r,i=!1){let e=[];return Object.keys(r).forEach(t=>{i===r[t]&&e.push(t)}),pt(r,{keysToInclude:e})}function Jn(r){return r.replace(/[\u4e00-\u9fa5]/g,"aa").length}var Fa=()=>{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},bs=r=>f(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})}),Ha=r=>{let i=r.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]<<0},jn=r=>(Object.keys(r).forEach(i=>{ee(r[i])&&(i.startsWith("uint")||i.startsWith("int"))?r[i]=Math.floor(r[i]):(Ge(r[i])||he(r[i]))&&jn(r[i])}),r);function qn(r){return new Promise(i=>setTimeout(i,r))}var Ga=(r,i)=>{let e=null;return function(...t){return e||(e=r.apply(i||this,t),e.finally(()=>e=null),e)}};var Um=Object.prototype.hasOwnProperty;var fu=r=>typeof r=="function",Kt=r=>typeof r=="undefined";var _u=r=>typeof r=="boolean";var Bm=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 Eu(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(Bm(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(Um.call(r,i))return!1;return!0}}return!1}var Ar=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=_u(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}`:""}]`),S.log(i,e,Kt(this.userId)||Eu(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=zt;var $m="%cTRTC%c%s",Fm="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",Hm="display: inline",Gm=!(He||de||Da),Wa=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);!sr&&!Kr&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){T.on(E.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var e;((e=i==null?void 0:i.config)==null?void 0:e.logLevelToUpload)&&nt[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),T.on(E.JOIN_SUCCESS,({room:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),T.once(E.JOIN_FAILED,()=>{this.startUpload()}),T.on(E.LEAVE_SUCCESS,({room:i})=>{this.deleteJoinedUser(i.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(i){this._localJoinedUser.set(i.userId,i),this.startUpload()}deleteJoinedUser(i){this._localJoinedUser.delete(i)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),2e3)}getLogsToUpload(){let i={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return i;let e=0;for(;e<this._queue.length&&e!==50;e++){let t=this._queue[e];if(t.forAllJoinedClients)this._localJoinedUser.forEach(({userId:s,sdkAppId:n})=>{i.map.has(s)?i.map.get(s).logs.push(t):i.map.set(s,{userId:s,sdkAppId:n,logs:[t]})});else if(Y(t.userId)&&ee(t.sdkAppId)){let{userId:s,sdkAppId:n}=t;i.map.has(s)?i.map.get(s).logs.push(t):i.map.set(s,{userId:s,sdkAppId:n,logs:[t]})}}return i.map.size>0&&(i.splicedQueue=this._queue.splice(0,e)),i}upload(){return f(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:i,splicedQueue:e}=this.getLogsToUpload();if(i.size===0)return;try{let s=[...i.values()];for(let n=0;n<s.length;n++){let{userId:o,sdkAppId:a,logs:c}=s[n];yield this.uploadLogWithRetry(JSON.stringify({timestamp:fn(),sdkAppId:String(a),userId:o,version:Re,log:c.map(d=>d.log).join(`
|
|
`)}),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:()=>qt({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(zr());let t=String(e.getMilliseconds());return"padStart"in String.prototype&&(t=t.toString().padStart(3,"0")),`[${e.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${t}] <${nt[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){g(nt[i])||(this._logLevel!==i&&this.info("setLogLevel",i),this._logLevel=i)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(i){if(Y(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch(e){return""}}log(i,e,t=!0,s,n){var c;e.unshift(this.getPrefix(i));let o={log:e.reduce((d,l)=>`${d} ${this.logChunkToString(l)}`.trim(),""),level:i,userId:s,sdkAppId:n,forAllJoinedClients:t};if(T.emit(E.LOG,{log:o}),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push(o),i<this._logLevel)return;let a=((c=nt[i])==null?void 0:c.toLowerCase())||"info";Gm?console[a]($m,Fm,Hm,...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 Ar(i)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;nt[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}},S=new Wa;var Wm=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)})},Ns=Wm;var Ja=class{constructor(){u(this,"_prefix","TRTC");u(this,"_queue",new Map);this.checkStorage()}getRealKey(i){return`${this._prefix}_${i}`}checkStorage(){if(!Qt())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 n=JSON.parse(s);if(n&&n.expiresIn<Date.now())return!0}return!1}).forEach(t=>localStorage.removeItem(t))}doFlush(){if(!!Qt())try{for(let[i,e]of this._queue)localStorage.setItem(i,JSON.stringify(e))}catch(i){S.warn(i)}}getItem(i){if(!Qt())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){S.warn(e)}}setItem(i,e){if(!!Qt())try{let t={expiresIn:Date.now()+En,value:e};this._queue.set(this.getRealKey(i),t)}catch(t){S.warn(t)}}deleteItem(i){if(!Qt())return!1;try{return i=this.getRealKey(i),this._queue.delete(i),localStorage.removeItem(i),!0}catch(e){return S.warn(e),!1}}clear(){if(!!Qt())try{localStorage.clear()}catch(i){S.warn(i)}}},Xn=new Ja;var ii={};Xr(ii,{HTTPS_API:()=>sp,IS_GET_CAPABILITIES_SUPPORTED:()=>Ka,IS_GET_SETTINGS_SUPPORTED:()=>Lt,IS_SEI_SUPPORTED:()=>_t,IS_SPC_SUPPORTED:()=>Rr,basis:()=>ap,checkSystemRequirementsInternal:()=>Kn,decodeSupportStatus:()=>Yn,encodeSupportStatus:()=>Qa,getBrowserInfo:()=>ep,getDisplayResolution:()=>vu,isAddTransceiverSupported:()=>tt,isBrowserSupported:()=>za,isGetReceiversSupported:()=>Bi,isGetSendersSupported:()=>Ri,isGetTransceiversSupported:()=>kt,isGetUserMediaSupported:()=>Du,isMediaDevicesSupported:()=>zn,isMediaSessionSupported:()=>ku,isMediaStreamTrackProcessorSupported:()=>tp,isReplaceTrackSupported:()=>Ya,isScreenCaptureApiAvailable:()=>Ds,isSelectedCandidatePair:()=>Ci,isSetParametersSupported:()=>Ms,isSmallStreamAPISupported:()=>Mu,isSmallStreamSupported:()=>Os,isStopTransceiverSupported:()=>op,isTRTCSupported:()=>ip,isUnifiedPlanDefault:()=>np,isUsedInHttpProtocol:()=>ti,isWebAudioSupported:()=>Ou,isWebCodecSupported:()=>Zn,isWebCodecsSupported:()=>Nu,isWebRTCSupported:()=>Za,isWebTransportSupported:()=>Lu});var Xa=Se(yu(),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}},Zm=new Map([[te,["Firefox",yn]],[ur,["Edg",Nn]],[fr,["Chrome",Hn]],[Ve,["Safari",_r]],[lt,["TBS",On]],[lr,["XWEB",Mn]],[hr&&Vi,["WeChat",kn]],[cs,["QQ(Win)",Ln]],[pr,["QQ(Mobile)",cr]],[mr,["QQ(Mobile X5)",cr]],[ds,["QQ(Mac)",xn]],[us,["QQ(iPad)",Pn]],[ls,["MI",Vn]],[hs,["HW",Un]],[ms,["Samsung",Bn]],[ps,["OPPO",$n]],[fs,["VIVO",Fn]],[dr,["EDGE",bn]],[os,["SogouMobile",vn]],[as,["Sogou",Dn]]]);function ep(){let r=Zm.get(!0),i=r?r[0]:"unknown",e=r?r[1]:"unknown";return{browserName:i,browserVersion:e}}var za=function(){return!(va||dr||ur&&Na<80||te&&ba<56)},Nu=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every(i=>i in window)},zn=function(){if(!navigator.mediaDevices)return ti()||S.error(Ae.NOT_SUPPORTED_MEDIA),!1;let r=["getUserMedia","enumerateDevices"];return r.filter(i=>i in navigator.mediaDevices).length===r.length},bu=!1;function ti(){return location.protocol==="http:"&&!Xt?(bu||S.error(k({key:M.NOT_SUPPORTED_HTTP})),bu=!0,!0):!1}var tp=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},Qa=function(){return f(this,null,function*(){if(K.detail.isH264EncodeSupported&&K.detail.isVp8EncodeSupported)return{isH264EncodeSupported:K.detail.isH264EncodeSupported,isVp8EncodeSupported:K.detail.isVp8EncodeSupported};let r,i=!1,e=!1;try{let t=new RTCPeerConnection,s=document.createElement(h.CANVAS);s.getContext("2d");let n=s.captureStream(0);return t.addTrack(n.getVideoTracks()[0],n),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}}})},Yn=function(){return f(this,null,function*(){if(K.detail.isH264DecodeSupported&&K.detail.isVp8DecodeSupported)return{isH264DecodeSupported:K.detail.isH264DecodeSupported,isVp8DecodeSupported:K.detail.isVp8DecodeSupported};let r,i=!1,e=!1;try{let t=new RTCPeerConnection;return r=yield t.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),r.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),r.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),t.close(),{isH264DecodeSupported:i,isVp8DecodeSupported:e}}catch(t){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}})},Kn=Ga(()=>f(void 0,null,function*(){if(K.result&&K.detail.isH264EncodeSupported&&K.detail.isVp8EncodeSupported&&K.detail.isH264DecodeSupported&&K.detail.isVp8DecodeSupported)return K;let r=za(),i=Za(),e=Nu(),t=zn(),{isH264EncodeSupported:s,isVp8EncodeSupported:n}=yield Qa(),{isH264DecodeSupported:o,isVp8DecodeSupported:a}=yield Yn();if(!s||!n){let c=yield Qa();S.warn(`detect encode again h264:${s} vp8:${n} result: ${JSON.stringify(c)}`),s=c.isH264EncodeSupported,n=c.isVp8EncodeSupported}if(s&&o&&de&&et&&!lr&&!lt){let{encode:c,decode:d}=yield rp();s=c,c&&(o=d)}return K.result=r&&i&&t&&(s||n)&&(o||a),K.detail.isBrowserSupported=r,K.detail.isWebRTCSupported=i,K.detail.isWebCodecsSupported=e,K.detail.isMediaDevicesSupported=t,K.detail.isScreenShareSupported=Ds(),K.detail.isSmallStreamSupported=Os(),K.detail.isH264EncodeSupported=s,K.detail.isVp8EncodeSupported=n,K.detail.isH264DecodeSupported=o,K.detail.isVp8DecodeSupported=a,K.result||S.error(`${navigator.userAgent} ${$a(K.detail,!1)}`),cp(),K})),ip=function(){return K.result},Ds=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},Qn=null;function rp(){return f(this,null,function*(){return Qn||(Qn=new Promise(r=>f(this,null,function*(){let i={encode:!1,decode:!1},e=()=>{};try{S.warn("detectH264Supported start");let t=document.createElement("canvas"),s=t.getContext("2d");t.width=320,t.height=240;let n=setInterval(()=>{s.fillText("test",Math.floor(Math.random()*320),Math.floor(Math.random()*240))},66),o=-1,a=-1;e=()=>{clearInterval(o),clearInterval(n),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 m=yield d.createOffer();yield d.setLocalDescription(m),yield l.setRemoteDescription(m);let p=yield l.createAnswer(),_=Xa.default.parse(p.sdp),R=_.media[0].rtp.findIndex(C=>C.codec==="H264");_.media[0].rtp=[_.media[0].rtp[R]],_.media[0].fmtp=_.media[0].fmtp.filter(C=>C.payload===_.media[0].rtp[0].payload),_.media[0].rtcpFb&&(_.media[0].rtcpFb=_.media[0].rtcpFb.filter(C=>C.payload===_.media[0].rtp[0].payload)),p.sdp=Xa.default.write(_),yield l.setLocalDescription(p),yield d.setRemoteDescription(p),o=setInterval(()=>f(this,null,function*(){i.encode&&i.decode&&(e(),r(i));let C=yield d.getSenders()[0].getStats(),N=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||N.forEach(U=>{U.type==="inbound-rtp"&&U.mediaType===h.VIDEO&&U.bytesReceived>0&&(i.decode=!0)})}),100)}catch(t){e(),S.warn(t),r(i)}})).then(r=>((!r.encode||!r.decode)&&S.warn(`detectH264Supported encode: ${r.encode} decode: ${r.decode} ${dt}`),r)),Qn)})}var sp=(r,i,e)=>{location.protocol==="http:"&&!Xt&&(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")?!(pe(r.selected)&&!r.selected):!1};function vu(){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 Du(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function Ou(){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 Mu(){return"captureStream"in HTMLCanvasElement.prototype}function Os(){return hr||He||ht&&ht<63?!1:!!(za()&&Mu())}var np=function(){if(g(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 Bi(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function Ri(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function kt(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function tt(){return _s===11?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var Rr=(()=>!(!tt()||et&&ht<86))();function op(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}function Ya(){return"RTCRtpSender"in window&&"replaceTrack"in window.RTCRtpSender.prototype}function Ms(){return"RTCRtpSender"in window&&"setParameters"in window.RTCRtpSender.prototype&&Ri()}var Lt=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,Ka=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,_t="RTCRtpSender"in window&&"createEncodedStreams"in window.RTCRtpSender.prototype&&gi()>=86,Za=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(i=>i in window).length>0};function Zn(){let r={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return g(window.AudioDecoder)||(r.AudioDecoder=!0),g(window.AudioEncoder)||(r.AudioEncoder=!0),g(window.VideoDecoder)||(r.VideoDecoder=!0),g(window.VideoEncoder)||(r.VideoEncoder=!0),g(window.ImageDecoder)||(r.ImageDecoder=!0),r}function ku(){return"mediaSession"in navigator&&!g(navigator.mediaSession.setActionHandler)}function Lu(){return!g(window.WebTransport)}function ap(){let r={browser:`${Rt.name}/${Rt.version}`,os:Gn(),displayResolution:vu(),isScreenShareSupported:Ds(),isWebRTCSupported:Za(),isGetUserMediaSupported:Du(),isWebAudioSupported:Ou(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:Zn(),isMediaSessionSupported:ku(),isWebTransportSupported:Lu()};return navigator.userAgent.includes("miniProgram")&&(r.browser=`mini/${r.browser}`),r}var xu="checkResult";function cp(){Xn.setItem(xu,{ua:navigator.userAgent,checkResult:K})}(function(){ti();let i=Xn.getItem(xu);i&&i.ua===navigator.userAgent&&(K=i.checkResult),Kn()})();var wu=Se(Ne(),1);var Pu=Symbol("instance"),NE=Symbol("abortCtrl"),eo=Symbol("cacheResult"),ks=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,Ps.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},Ls=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function dp(r){return typeof r=="object"&&r&&"then"in r}var xs=new Map;function ue(r,i,e={}){return(t,s,n)=>{let o=e.action||s;if(!e.context){let c=xs.get(t)||[];xs.has(t)||xs.set(t,c),c.push({from:r,to:i,action:o})}let a=n.value;n.value=function(...c){let d=this;if(e.context&&(d=$.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===i)return e.sync?d[eo]:Promise.resolve(d[eo]);d.state instanceof ks&&d.state.action==e.abortAction&&d.state.abort(d);let l=null;Array.isArray(r)?r.length==0?d.state instanceof ks&&d.state.abort(d):(typeof d.state!="string"||!r.includes(d.state))&&(l=new Ls(d._state,`${d.name} ${o} to ${i} failed: current state ${d._state} not from ${r.join("|")}`)):r!==d.state&&(l=new Ls(d._state,`${d.name} ${o} to ${i} failed: current state ${d._state} not from ${r}`));let m=N=>{if(e.fail&&e.fail.call(this,N),e.sync){if(e.ignoreError)return N;throw N}else return e.ignoreError?Promise.resolve(N):Promise.reject(N)};if(l)return m(l);let p=d.state,_=new ks(p,i,o);Ps.call(d,_);let R=N=>{var U;return d[eo]=N,_.aborted||(Ps.call(d,i),(U=e.success)===null||U===void 0||U.call(this,d[eo])),N},C=N=>{let U=N instanceof Error?N.message:String(N);return Ps.call(d,p,N),m(new Ls(d._state,`action '${o}' failed :${U}`,N instanceof Error?N:new Error(U)))};try{let N=a.apply(this,c);return dp(N)?N.then(R).catch(C):e.sync?R(N):Promise.resolve(R(N))}catch(N){return C(N)}}}}var up=(()=>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 Ps(r,i){let e=this._state;this._state=r;let t=r.toString();r&&this.emit(t,e),this.emit($.STATECHANGED,r,e,i),this.updateDevTools({value:r,old:e,err:i instanceof Error?i.message:String(i)})}var $=class extends wu.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=$.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[Pu];s?this.name=s.name+"-"+s.count++:t[Pu]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=xs.get(i)||[],t=new Set,s=[],n=[],o=new Set,a=Object.getPrototypeOf(i);xs.has(a)&&(a.stateDiagram.forEach(d=>t.add(d)),a.allStates.forEach(d=>o.add(d))),e.forEach(({from:d,to:l,action:m})=>{typeof d=="string"?s.push({from:d,to:l,action:m}):d.length?d.forEach(p=>{s.push({from:p,to:l,action:m})}):n.push({to:l,action:m})}),s.forEach(({from:d,to:l,action:m})=>{o.add(d),o.add(l),o.add(m+"ing"),t.add(`${d} --> ${m}ing : ${m}`),t.add(`${m}ing --> ${l} : ${m} \u{1F7E2}`),t.add(`${m}ing --> ${d} : ${m} \u{1F534}`)}),n.forEach(({to:d,action:l})=>{t.add(`${l}ing --> ${d} : ${l} \u{1F7E2}`),o.forEach(m=>{m!==d&&t.add(`${m} --> ${l}ing : ${l}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:o}}),c}static get(i){let e;return typeof i=="string"?(e=$.instances.get(i),e||$.instances.set(i,e=new $(i,void 0,Object.create($.prototype)))):(e=$.instances2.get(i),e||$.instances2.set(i,e=new $(i.constructor.name,void 0,Object.create($.prototype)))),e}static getState(i){var e;return(e=$.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){up($.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){Ps.call(this,i)}};$.STATECHANGED="stateChanged";$.UPDATEAFSM="updateAFSM";$.INIT="[*]";$.ON="on";$.OFF="off";$.instances=new Map;$.instances2=new WeakMap;var Vu=(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)},lp=(window==null?void 0:window.cancelIdleCallback)||function(r){clearTimeout(r)},hp=(window==null?void 0:window.cancelAnimationFrame)||(window==null?void 0:window.mozCancelAnimationFrame),ws=class{static generateTaskID(){return this.currentTaskID++}static run(i=_i,e,t){i===wi?t=v({delay:2e3,count:0,backgroundTask:!0},t):i===fi?t=v({delay:1e4,count:0},t):i===ss?t=v({fps:60,delay:16.6,count:0,backgroundTask:!0},t):t=v({delay:2e3,count:0,backgroundTask:!0},t),mt(e)&&(t=v(v({},t),e)),z(i)&&(e=i,i=_i);let s=v({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([`
|
|
let timerID = null;
|
|
self.onmessage = function (e) {
|
|
if (e.data === 'start') {
|
|
timerID = setInterval(() => {
|
|
self.postMessage('tick');
|
|
}, ${i.delay});
|
|
} else if (e.data === 'stop') {
|
|
clearInterval(timerID);
|
|
}
|
|
};
|
|
`],{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=Vu(s,{timeout:i.delay})};return i.ricID=Vu(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 n=()=>{if(document.hidden){let o=x()-e;o>=i.delay?s():i.timeoutID=setTimeout(s,i.delay-o)}};document.addEventListener("visibilitychange",n),i.onVisibilitychange=n,document.hidden&&n()}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:n,onVisibilitychange:o,worker:a}=this.taskMap.get(i);return a&&a.terminate(),e&&clearInterval(e),t&&clearTimeout(t),s&&hp(s),n&&lp(n),o&&document.removeEventListener("visibilitychange",o),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}};ws.taskMap=new Map,ws.currentTaskID=1;var re=ws;var LE={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 xt={};Xr(xt,{create:()=>De,remove:()=>me});var Vs=new WeakMap;function De(r,i){Vs.has(r)||Vs.set(r,[]);let e=Vs.get(r),s={add:(n,o)=>("addEventListener"in i?(e.push(i.removeEventListener.bind(i,n,o)),i.addEventListener(n,o)):(e.push(i.off.bind(i,n,o)),i.on(n,o)),s)};return s}function me(r){let i=Vs.get(r);i&&(i.forEach(e=>e()),Vs.delete(r))}var Pt=new WeakMap;function it({settings:r={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(s,n,o){let a=vt({retryFunction:o.value,settings:r,onError({error:c,retry:d,reject:l,retryFuncArgs:m}){var p;i?i.call(this,c,()=>{var _;(_=Pt.get(s))!=null&&_.has(n)?d():l(c)},l,m):(p=Pt.get(s))!=null&&p.has(n)?d():l(c)},onRetrying(c,d){var l;z(e)&&e.call(this,c,d),(l=Pt.get(s))!=null&&l.has(n)&&(Pt.get(s).get(n).stopRetry=d)},onRetryFailed:t});return o.value=function(...c){let d=Pt.get(s);return d?d.set(n,{args:c}):Pt.set(s,new Map([[n,{args:c}]])),a.apply(this,c).finally(()=>{var l;return(l=Pt.get(s))==null?void 0:l.delete(n)})},o}}function Us({fnName:r,callback:i,validateArgs:e=!0}){return function(t,s,n){let o=n.value;return n.value=function(...a){var c,d;if((c=Pt.get(t))!=null&&c.has(r)){let{stopRetry:l,args:m}=Pt.get(t).get(r),p=!0;if(e){for(let _ of m)if(!a.find(R=>R===_)){p=!1;break}}p&&(i&&i.apply(this,a),l&&l(),(d=Pt.get(t))==null||d.delete(r))}return o.apply(this,a)},n}}var mp=1,pp=0,to=class{constructor(i=!0){this.countMap=new Map;this.distributionMap=new Map;this.log=S.createLogger({id:"kv"});i&&(T.on("102",({track:e,cost:t})=>{this.addSuccessEvent({key:e.kind===h.AUDIO?io.START_MICROPHONE:ec.START_CAMERA,cost:t})}),T.on("103",({track:e,error:t})=>{this.addFailedEvent({key:e.kind===h.AUDIO?io.START_MICROPHONE:ec.START_CAMERA,error:t})}))}getReportData(){let i={msg_sdk_basic_info:{uint32_sdk_version:Ha(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,n])=>({uint32_item_key:s,uint32_item_value:n}))}))};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 n;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=((n=this.distributionMap)==null?void 0:n.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 n=((a=this.distributionMap)==null?void 0:a.get(i))||new Map,o=0;if(ee(t))o=Math.floor(e/t);else for(let c=t.length-1;c>0;c--)if(e>t[c]){o=c;break}n.set(o,(n.get(o)||0)+1),this.distributionMap.set(i,n)}addSuccessEvent({key:i,cost:e,timeKey:t,split:s}){if(!!i&&(this.addEnum({key:i,value:mp,useUV:!1}),e)){let n=+String(i).slice(-3);n<800&&n>=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:(!g(e.extraCode)||!g(e.code))&&(t=e.extraCode||e.code)),this.addEnum({key:i,value:pp,useUV:!1}),this.addEnum({key:i,value:t,useUV:!1})}},ro=(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))(ro||{}),tc=(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))(tc||{}),ic=(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))(ic||{}),rc=(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))(rc||{});var io=(t=>(t[t.START_MICROPHONE=501700]="START_MICROPHONE",t[t.MICROPHONE_CAHNNELS=501701]="MICROPHONE_CAHNNELS",t[t.MICROPHONE_SAMPLERATE=501702]="MICROPHONE_SAMPLERATE",t))(io||{});var ec=(i=>(i[i.START_CAMERA=511700]="START_CAMERA",i))(ec||{});var fp=new to(!0),$i=new to(!1);var D=fp;var wt=class extends ${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=Ta,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 f(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=k({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():Oa?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);xt==null||xt.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(){T.on(E.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(){this.track&&me(this.track)}unbindEvents(){this.element&&me(this.element),this.unbindTrackEvents(),T.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),He&&(this._interval=re.run(_i,()=>{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:n}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${s} message: ${n} userAgent: ${navigator.userAgent}`),Z.uploadEvent({log:`stat-${this.kind}-${we.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)=>{qn(e).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var n,o,a;this._log.warn(`element onerror ${(o=(n=this.element)==null?void 0:n.error)==null?void 0:o.code} fired after recreated mediaStream`),s((a=this.element)==null?void 0:a.error)}),qn(5e3).then(()=>{var n,o;(!this.isPlaying||((n=this.element)==null?void 0:n.error))&&s((o=this.element)==null?void 0:o.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()}})],wt.prototype,"doReplayByRecreateMediaStream",1),y([ue([],"PLAYING",{sync:!0})],wt.prototype,"handlePlaying",1),y([ue("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],wt.prototype,"handlePaused",1),y([ue([],"STOPPED",{sync:!0})],wt.prototype,"handleStopped",1);var ri="trtc_autoplay",sc=`${ri}_mask`,yr=`${ri}_wrapper`,Bu=`${ri}_header`,nc=`${ri}_content`,so=`${ri}_action_wrapper`,oc=`${ri}_question`,ac=`${ri}_collapse`,no=`${ri}_action_confirm`,$u=`${ri}_detail`,Fu="#2473E8",dc="dialog",_p=`${dc}-show`,Ep=`${dc}-1`,gp=`${dc}-2`,Hu=!1,uc=()=>!!document.querySelector(`.${yr}`),Wu=`${At}/${Nt()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,Gu=`<br><a href='${Wu}' target='_blank'>${Nt()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,Tp=`${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${Gu}`:`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. ${Gu}`}`,cc=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.'),!Hu){let i=document.createElement("style");i.innerHTML=`.${sc}{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;}.${sc} div:not(.${so}){display:block !important;}.${yr}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${yr} a{color:${Fu};}.${Bu}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${nc}{margin:8px 0;}.${so}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${ac}{margin-right:auto;cursor:pointer}.${oc}{height:100%;line-height:16px;cursor:pointer;}.${no}{margin-left:8px;color:#fff;background:${Fu};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${no}:hover{opacity:0.9;}.${ac},.${no},.${nc},.${oc}{font-size:14px;}@media screen and (max-width:750px){.${yr}{width:80vw;}}`,document.head.appendChild(i),Hu=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${sc}"><div class='${yr}'><div class='${Bu}'>${location.host}</div><div class='${nc}'>${this.content}</div><div class='${$u}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${Tp}</div><div class='${so}'></div></div></div>`.trim();let e=document.createElement("button");e.className=no,e.innerText=Nt()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let t=document.createElement("div");t.className=oc,t.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
|
|
<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">
|
|
<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"/>
|
|
<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"/>
|
|
<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"/>
|
|
</svg>
|
|
`,t.onclick=this.onQuestionClick.bind(this);let s=document.createElement("div");s.className=ac,s.innerText=`${Nt()?"\u8BE6\u60C5 >":"Detail >"}`,s.onclick=this.onCollapseClick.bind(this);let n=i.content.firstChild,o=n.querySelector(`.${so}`);return o.appendChild(s),o.appendChild(t),o.appendChild(e),n}addDiaLog(){uc()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${yr}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",S.info("show autoplay dialog"),Z.uploadEvent({log:_p}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){S.warn("confirm clicked, try resume stream"),T.emit(E.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${$u}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||Z.uploadEvent({log:Ep}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Wu,"_blank"),this._isQuestionClicked||Z.uploadEvent({log:gp}),this._isQuestionClicked=!0}},Ju=cc;var We=class extends wt{constructor(e){super(e,h.VIDEO);u(this,"viewMirror",!1);u(this,"objectFit");u(this,"container");u(this,"canvas");this.container=e.container,this.canvas=e.canvas,g(e.viewMirror)||(this.viewMirror=e.viewMirror),g(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&&!uc()&&(this._log.info(`${this.kind} player auto resume when paused`),this.resume(),this._pausedRetryCount--)),this.viewMirror&&this.element){let n=this.element.style.transform;t===h.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=n.replace("scaleX(-1)",""):t===h.LEAVE_PICTURE_IN_PICTURE&&!n.includes("scaleX")&&(this.element.style.transform=`${n} 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 Fi(r,i){return f(this,null,function*(){if(!r.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield r.audioWorklet.addModule(i),S.info("worklet addModule success")}catch(e){throw S.info(`worklet addModule catch error. ${e.message}`),e}})}typeof window!="undefined"&&(window.AudioContext=window.AudioContext||window.webkitAudioContext||window.mozAudioContext);var Hi=new window.AudioContext({sampleRate:48e3}),oo=()=>{Hi.state==="suspended"?(Hi.resume(),document.addEventListener("click",oo)):Hi.state==="interrupted"?Hi.resume():document.removeEventListener("click",oo)};document.addEventListener("click",oo);Hi.onstatechange=()=>{S.info(`context state: ${Hi.state}`),oo()};var Je=r=>Hi;var Et=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){S.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){S.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}},ao=class extends Et{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,n=0,o=`M${s},${n}`;for(let a=0;a<e.length;a++)n=e[a]/128*100/2,o+=`L${s},${n}`,s+=t;return o}},Bs=class{constructor(){this.source=new Et;this.gain=new Et;this.destination=new Et}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(Sp(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}},br=class extends Bs{constructor(e){super();this.context=e;this.denoiser=new Et;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}},co=class{constructor(){this.audioContext=Je("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]}},ju=new WeakMap;function Sp(r){let i=ju.get(r);if(i)return i;let e=Je();if(r instanceof HTMLAudioElement)i=e.createMediaElementSource(r);else if(r instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([r]));else return r;return ju.set(r,i),i}var Ip=`
|
|
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;}
|
|
break;case"setIntervalTime":this.intervalTime=data.intervalTime;break;case"unmute":this.unmute=true;break;case"stop":this.isStop=true;break;}};}
|
|
process(inputs,outputs){const input=inputs[0];const output=outputs[0];if(!input&&!output){return true;}
|
|
if(this.isStop){return false;}
|
|
const l=output?output[0].length:0;const cl=this.cache.length;if(cl>l){output[0].set(this.cache.slice(0,l));this.cache=this.cache.slice(l);}else if(this.unmute){output[0].set(input[0]);}
|
|
const firstChannel=cl>l?output[0]:input[0];if(!firstChannel){return true;}
|
|
let sum=0;let rms;for(let i=0;i<firstChannel.length;++i){sum+=firstChannel[i]*firstChannel[i];}
|
|
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});}
|
|
return true;}}
|
|
registerProcessor("volume-meter",VolumeMeter);
|
|
`,Gi=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,T.on(E.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){return Gi.workletReady||(Gi.workletReady=Fi(Gi.audioContext,URL.createObjectURL(new Blob([Ip],{type:"application/javascript"})))),Gi.workletReady.then(()=>this.initAudioWorklet()).catch(()=>this.initScriptProcessor())}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Gi.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:we.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=Je("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{let e=i.inputBuffer.getChannelData(0),t=0;for(let s=0;s<e.length;++s)t+=e[s]*e[s];this._volume=Math.sqrt(t/e.length)||0}}catch(i){this._log.error(`volumeMeter init script processor error: ${i}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,T.off(E.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}},$s=Gi;u($s,"audioContext",Je("volume-meter")),u($s,"workletReady");var uo=class extends Et{constructor(e){super();u(this,"_volumeMeter");this._volumeMeter=new $s(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return f(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),s=new Float32Array(t>>2);e.copyTo(s,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:s},[s.buffer]),e.close()}}};var zu=Se(Ne(),1);var Xu=r=>i=>i.deviceId===r;var Fs=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&&Nr(this.devices[0])){this.devices=t;return}e&&(t.forEach(s=>{if(s.deviceId&&!this.devices.find(Xu(s.deviceId))){let n=`${this.kind}${this.type}Added`;S.warn(`${n}: ${JSON.stringify(s)}`),e.emit(n,s)}}),this.devices.forEach(s=>{if(s.deviceId&&!t.find(Xu(s.deviceId))){let n=`${this.kind}${this.type}Removed`;S.warn(`${n}: ${JSON.stringify(s)}`),e.emit(n,s)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},lc=class extends zu.EventEmitter{constructor(){super();u(this,"audioInputs",new Fs(h.AUDIO));u(this,"videoInputs",new Fs(h.VIDEO));u(this,"audioOutputs",new Fs(h.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||re.run(wi,()=>{this.update()},{delay:1e4}))}init(){lo().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return f(this,arguments,function*(e=0){let t=yield lo(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}},ge=Kr||sr?null:new lc;function Nr(r){return r.deviceId===r.groupId&&r.groupId===""}function lo(){return f(this,arguments,function*(r=0){if(ti()||!zn())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(r!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{Nr(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){S.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&&hc.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(s.getCapabilities=()=>e.getCapabilities()),s})})}function Ue(r=!1){return ge.update(r?1:0).then(i=>i.audioInputs.devices)}function je(r=!1){return ge.update(r?2:0).then(i=>i.videoInputs.devices)}var Qu=!1;function Yu(){return f(this,null,function*(){try{Qu||(Qu=!0,S.info(`speakers:${(yield Wi()).map(r=>` ${r.deviceId.slice(0,8)}: ${r.label}`)}`))}catch(r){}})}function Wi(r=!1){return f(this,null,function*(){return ge.update(r?1:0).then(i=>i.audioOutputs.devices)})}var hc=new Set;function Ku(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!!hc.has(t)}function Zu(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!!hc.has(t)}function mc(r,i){return f(this,null,function*(){let t=(yield Ue()).find(s=>s.deviceId===Pi);return(t==null?void 0:t.groupId)===r&&t.label===i})}function el(n){return f(this,arguments,function*({newDeviceId:r,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:s}){return r!==i?!1:s===h.AUDIO&&r===Pi?yield mc(e,t):!0})}var ho,pc=class extends Bs{constructor(e){super();this.log=e;u(this,"volumeMeter");u(this,"volumeDestination");u(this,"analyser",new ao);this.volumeMeter=new uo({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()}},vr=class extends wt{constructor(e){super(e,h.AUDIO);u(this,"_outputDeviceId");u(this,"_volume",1);u(this,"_destination",Je("player").createMediaStreamDestination());u(this,"pipeline");u(this,"volumeMeterMode","worklet");this.pipeline=new pc(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=ho||new Audio;t.setAttribute("autoplay","autoplay"),t.srcObject=this.getMediaStream(),t.muted=this.muted,this.element=t,t===ho&&(ho=void 0),this.bindElementEvents()}play(){return f(this,null,function*(){if(!!this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?this.pipeline.volumeMeter.init():this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(Je("player").createAnalyser()),this.setVolume(this._volume),Yu(),Ie(vr.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destory(),super.stop(e)}setSinkId(e){return f(this,null,function*(){var t,s;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(s=(t=this.element).setSinkId)==null?void 0:s.call(t,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){!this.element||(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}},mo=class extends vr{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)}},po=class extends vr{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,n;((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=((n=e.getSettings())==null?void 0:n.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&&bt&&(ho=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var Ji=class extends ${constructor({userId:e,sdkAppId:t,mediaType:s,room:n,PlayerClass:o=s===1?po:We}){var a;super();u(this,"id",Ns());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=S.createLogger({id:`${this.kind[0]}t`,userId:(a=n||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 o({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(ve.PLAYER_STATE_CHANGED,c=>{T.emit(E.PLAYER_STATE_CHANGED,v({track:this},c)),this.emit("player-state-changed",c)}),this.kind===h.VIDEO&&(this.player.on(ve.LOADED_DATA,()=>{T.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||S}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"}play(e,t){return f(this,null,function*(){let s=he(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(t)}`),t&&!g(t.muted)&&this.setPlayerMute(t.muted),t&&!g(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof We&&(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&&!g(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===h.VIDEO)&&this.setPlayerMute(!0),t&&!g(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof We&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,s&&(this.container=s,this.player instanceof We&&this.player.setContainer(s)),T.emit(E.PLAY_TRACK_START,{track:this}),!this._outputTrack){this.log.info("play has not mediaTrack, abort");return}this._log.info(`play with options: ${JSON.stringify(t)}`);try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(),he(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(n){throw this.handleAutoPlayFailed(),this.emit("error",n),n}})}setMirror(e,t){if(this.isScreen||this.kind!==h.VIDEO||g(e)||e===this.mirror)return;this.mirror=e;let s=this.player;t&&(s=t);let n=this.manager;if(pe(this.mirror)){s.setViewMirror(this.mirror),n&&(n.mirror=!1);return}switch(this.mirror){case"view":{n&&(n.mirror=!1),s.setViewMirror(!0);break}case"publish":{n&&(n.mirror=!0),s.setViewMirror(!0);break}case"both":n&&(n.mirror=!0),s.setViewMirror(!1)}}playSubContainer(e,t){return f(this,null,function*(){if(!this._outputTrack||this.kind===h.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((n,o)=>{var a;e.find(c=>o===c)||(n.stop(),(a=this.subVideoPlayerMap)==null||a.delete(o))});for(let[n,o]of e.entries()){let a=this.subVideoPlayerMap.get(o);a?t&&(g(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(o,new We({id:this.userId||this.id,track:this.playerMediaTrack,container:o,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${n+1}`})}))}let s=[...this.subVideoPlayerMap.values()];for(let n of s)n.setViewMirror(this.player.mirror),yield n.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 f(this,null,function*(){var e;!this.isPlayCalled||(yield(e=this.player)==null?void 0:e.resume())})}close(){this.log.info("close"),this.isPlayCalled&&this.stop()}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),T.emit(e?E.TRACK_MUTED:E.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(e){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 Ju;else{let e=()=>{this.resume().then(()=>{document.removeEventListener("click",e,!0)})};document.addEventListener("click",e,!0)}}getVideoFrame(){return this.player instanceof We?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([],$.INIT,{sync:!0})],Ji.prototype,"close",1);var Ap=Object.prototype.hasOwnProperty,{toString:NT}=Object.prototype;function Cp(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(Ge(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(Ap.call(r,i))return!1;return!0}}return!1}var Ut=Cp;var Rp=function(r){return f(this,null,function*(){let i=bp(r);S.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],s=["label","deviceId"];i.audio&&(e=yield Ue(),S.info(`microphones: ${pt(e,{keysToInclude:s})}`)),i.video&&(t=yield je(),S.info(`cameras: ${pt(t,{keysToInclude:s})}`));try{let n=yield navigator.mediaDevices.getUserMedia(i);return Ka&&n.getTracks().forEach(o=>{S.info(`${o.kind} capabilities: ${pt(o.getCapabilities(),{keysToInclude:Rn})}`)}),n}catch(n){let{message:o}=n;throw n.name==="NotFoundError"&&(r.video&&t&&t.length===0&&(o=k({key:M.CAMERA_NOT_FOUND})),r.audio&&e&&e.length===0&&(o=k({key:M.MICROPHONE_NOT_FOUND}))),new b({code:A.INITIALIZE_FAILED,name:n.name,message:o,constraint:n.constraint})}})},yp=vt({retryFunction:Rp,settings:{retries:3,timeout:500},onError:({error:r,retry:i,reject:e,retryFuncArgs:t,retriedCount:s})=>{let n=s+1;r.name==="NotReadableError"||r.name==="OverconstrainedError"?(n===1?t[0].video&&(t[0].maxResolution=!1,(!Ve||t[0].width*t[0].height<=1920*1080)&&t[0].frameRate&&(t[0].frameRate=t[0].frameRate>10?10:5)):n===2?t[0].useDeviceIdOnly=!0:n===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(r),t[0].microphoneId&&tl(t[0].microphoneId,!1),t[0].cameraId&&tl(t[0].cameraId,!0)},onRetrying:r=>{S.warn(`getUserMedia NotReadableError observed, retrying [${r}/3]`)},onRetryFailed:r=>{Z.logFailedEvent({eventType:we.GET_USER_MEDIA_RETRY,error:r})},onRetrySuccess:r=>{Z.logSuccessEvent({eventType:we.GET_USER_MEDIA_RETRY}),Z.uploadEvent({log:`stat-${we.GET_USER_MEDIA_RETRY}-success-${r}`})}});function tl(r,i){return f(this,null,function*(){let t=(i?yield je():yield Ue()).find(s=>s.deviceId===r);t&&z(t.getCapabilities)&&S.warn(pt(t.getCapabilities(),{keysToInclude:Rn}))})}function bp(r){return{audio:Np(r),video:vp(r)}}function Np(r){if(!r.audio)return!1;if(r.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:r.sampleRate};return!Ut(r.microphoneId)&&(i.deviceId=r.useExactDeviceId?{exact:r.microphoneId}:r.microphoneId,r.useDeviceIdOnly)?i:(ee(r.channelCount)&&(i.channelCount=r.channelCount),pe(r.echoCancellation)&&!r.echoCancellation&&(i.echoCancellation=!1),pe(r.noiseSuppression)&&!r.noiseSuppression&&(i.noiseSuppression=!1),pe(r.autoGainControl)&&!r.autoGainControl&&(i.autoGainControl=!1),Ut(i)?!0:i)}function vp(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&&!Ut(e)?e:(r.width&&(e.width={ideal:r.width},i&&!te&&(e.width.max=r.width)),r.height&&(e.height={ideal:r.height},i&&!te&&(e.height.max=r.height)),te&&yt&&r.width&&r.height&&r.width*r.height<352*288&&(e.width=r.width,e.height=r.height),r.frameRate&&(e.frameRate=r.frameRate),Ut(e)?!0:e)}var il=yp;function fo(r){return W((i,e)=>function(...t){return f(this,null,function*(){return yield r.apply(this,t),i.apply(this,t)})})}function yi(r){return W((i,e)=>function(...t){return f(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 rl=(()=>{let r=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&S.info(`visibility change: ${document.visibilityState}`),!r&&(document.addEventListener("visibilitychange",()=>{S.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),r=!0)}})();var Dp=0,_o=class{constructor(){this.log=S.createLogger({id:`fq${++Dp}`});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 n,o;let t=v({},i),s=new Promise((a,c)=>{t.resolve=a,t.reject=c});return t.promise=s,e?this.length<=1?this.queue.push(t):(o=(n=this.lastQueueItem)==null?void 0:n.promise)==null||o.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:n}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(s,n).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},Gs=new WeakMap,Eo=new WeakMap;function Bt(r=!1){return function(i,e,t){let s=t.value;return t.value=function(...n){let o=Gs.get(this)||new _o;return Gs.set(this,o),o.push({fn:s,args:n,context:this},r)},t}}function sl(r){return function(i,e,t){let s=t.value;return t.value=function(...n){let o=Gs.get(this);if(o){let a=o.queue.filter((c,d)=>{if(d===0)return!0;let l=!0;return c.args.forEach(m=>{n.find(p=>p===m)||(l=!1)}),l?(c.reject(new b({code:A.API_CALL_ABORTED,message:r})),!1):!0});o.queue=a}return s.apply(this,n)},t}}function go(r){return function(i,e,t){let s=t.value;return t.value=function(...n){var a,c,d;let o=[];return(c=(a=Gs.get(this))==null?void 0:a.queue)==null||c.forEach(l=>o.push(l)),(d=Eo.get(this))==null||d.forEach(l=>l==null?void 0:l.queue.forEach(m=>o.push(m))),o.forEach(l=>{l.reject(new b({code:A.API_CALL_ABORTED,message:r}))}),Gs.delete(this),Eo.delete(this),s.apply(this,n)},t}}function si(r){return function(i,e,t){let s=t.value,n=o=>r(...o);return t.value=function(...o){let a=Eo.get(this)||new Map,c=a.get(n(o))||new _o;return a.set(n(o),c),Eo.set(this,a),c.push({fn:s,args:o,context:this})},t}}var fc=class extends Ji{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,"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 f(this,null,function*(){var t;try{let s=x();T.emit(E.LOCAL_TRACK_CAPTURE_START,{track:this});let n;e.customSource?(n=new MediaStream,n.addTrack(e.customSource)):((t=this.mediaTrack)==null||t.stop(),n=yield il(e));let o=n.getTracks()[0];return yield this.setInputMediaStreamTrack(o),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),T.emit(E.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:x()-s}),n}catch(s){throw T.emit(E.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:s}),this.log.error(`getUserMedia error observed ${s}`),s}})}setInputMediaStreamTrack(e){return this.state===$.INIT&&this.setStateToCapture(),super.setInputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;return super.setOutputMediaStreamTrack(e),(t=this.room)==null?void 0:t.replaceTrack(this)}publish(e,t){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),t}unpublish(){this.room&&this.room.localTracks.delete(this),T.emit(E.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return f(this,null,function*(){if(this.mediaTrack&&Lt){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:s}=this.mediaTrack;(yield el({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=s,t&&(this.groupId=t),lo().then(o=>{let a=o.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&&!Zu(this.mediaTrack)||this.kind===h.VIDEO&&!Ku(this.mediaTrack)||this._isRecapturing||e&&yt&&Ve)}onTrackMuted(){if(super.onTrackMuted(),rl(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<ar){setTimeout(()=>this.onTrackMuted(),ar);return}this._onMuteTimeoutId=setTimeout(()=>f(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((He||de)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return f(this,null,function*(){if(Ie(fc.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<ar){setTimeout(()=>this.onTrackEnded(),ar);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return f(this,null,function*(){var s;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),(s=this._inputTrack)==null||s.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let t={useExactDeviceId:!0};if(e==="user"||e==="environment")t.facingMode=e;else{let n;(this.kind==="audio"?yield Ue():yield je()).find(a=>a.deviceId===e)&&(n=e),t.deviceId=n}return this.capture(t).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),T.emit(E.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(n=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${n.message}`),this.emit("5",n),T.emit(E.LOCAL_TRACK_RECAPTURE,{track:this,error:n})})})}getRecoverCaptureDeviceId(){return f(this,null,function*(){let e=this instanceof le;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let s=(Ws.get(t)||0)+1;if(Ws.set(t,s),s>=3){let n=e?(yield je()).find(o=>!Ws.has(o.deviceId)):(yield Ue()).find(o=>!Ws.has(o.deviceId));n&&(this.log.warn(`${t} capture fail ${s} times, change new ${n.deviceId}`),t=n.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=fc;y([ue($.INIT,"capture",{ignoreError:!0,sync:!0})],qe.prototype,"setStateToCapture",1),y([Bt()],qe.prototype,"capture",1),y([ue("capture","publish",{ignoreError:!0,success(){this.room.localTracks.add(this),T.emit(E.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"})},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 f(this,null,function*(){let i=this.state==="publish"?"started":"starting";r.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:i,reason:"api-call"})})}),ue([],"capture",{sync:!0})],qe.prototype,"unpublish",1);var Ws=new Map;T.on(E.SWITCH_DEVICE_SUCCESS,r=>{r.track.deviceId&&Ws.delete(r.track.deviceId)});var Oe=class extends qe{constructor(e){super(1,mo);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");this.manager=e,this.pipeline=new br(e),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}get playerMediaTrack(){return this.mediaTrack}setInputMediaStreamTrack(e){return f(this,null,function*(){yield 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:n}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:s,channelCount:n})}`),this.pipeline.source.channelCount=n||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 f(this,null,function*(){if(!!this.mediaTrack){if(this.deviceId===e)if(e===Pi){if(yield mc(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)),T.emit(E.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(t){throw this.log.error(`switch microphone failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}}})}listenDeviceChange(){ge&&!ge.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&ge.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current microphone is lost: ${JSON.stringify(e)}`),ae(this.userId,{eventId:2003,param1:6,streamType:1});let t=yield Ue();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(n){return f(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:s}){let o=!1;!g(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,o=!0),!g(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,o=!0),!g(s)&&s!==this.profile.autoGainControl&&(this.profile.autoGainControl=s,o=!0),o&&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 f(this,null,function*(){try{yield Ie(Oe.prototype,this,"recapture").call(this,e)}catch(t){let s=(yield Ue()).find(n=>n.deviceId!==e);if(s)yield Ie(Oe.prototype,this,"recapture").call(this,s.deviceId);else throw t}})}};var ji=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 o=i;o<=e;o++){let a=this.dataView.getInt8(o);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 n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=n}removePreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,t=[],s=0;for(let o=i;o<=e;o++)switch(this.dataView.getInt8(o)){case 0:s++,t.push(this.dataView.getInt8(o));break;case 3:s!==2&&t.push(this.dataView.getInt8(o)),s=0;break;default:t.push(this.dataView.getInt8(o)),s=0;break}let n=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=n}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 n=6;n<this.dataView.buffer.byteLength;n++){let o=this.dataView.getUint8(n);if(e++,o===255)i+=255;else{i+=o;break}}let t=new ArrayBuffer(i),s=new DataView(t);for(let n=0;n<t.byteLength;n++,e++)s.setInt8(n,this.dataView.getInt8(e));return s}};var To=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,n=[];n.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)n.push(255);n.push(s);let o=new DataView(i);return n.push(...new Uint8Array(o.buffer)),n.push(128),new ji(new DataView(new Uint8Array(n).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 n=0;n<i.byteLength;n++)switch(s.getUint8(n)){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),n=9-s;if(n<=0)return 0;let o=t.splice(0,n).reverse().map(this.encodeSEINalu.bind(this)),a=o.reduce((p,_)=>p+_.dataView.byteLength,0),c=new ArrayBuffer(a+i.data.byteLength),d=new DataView(c),l=new DataView(i.data),m=0;for(let p=0;p<o.length;p++)for(let _=0;_<o[p].dataView.byteLength;_++)d.setInt8(m++,o[p].dataView.getInt8(_));for(let p=0;p<i.data.byteLength;p++)d.setInt8(m++,l.getInt8(p));return i.data=c,o.length}return 0}};var le=class extends qe{constructor(e,t=4){super(t,We);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});u(this,"small");u(this,"isNeedToSetBandwidth");u(this,"muteImage");u(this,"manager");u(this,"_seiCodec",new To);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(w(v({},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(!(!Lt||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}setMute(e){return f(this,null,function*(){var t,s,n;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(n=this.manager)==null?void 0:n.deleteWatermark("mute"),this.muteImage=void 0,Ie(le.prototype,this,"setMute").call(this,e)})}capture({deviceId:e,facingMode:t,useExactDeviceId:s=!1,customSource:n}){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:n})}setProfile(e){let t=v({},e),s=t.width>t.height;t.width*t.height<=160*120&&de&&et&&(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&&Ma&&(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(w(v({},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 Lt&&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:Fa()&&this.profile.width>this.profile.height&&e.height>e.width?Math.max(e.width/this.profile.height,e.height/this.profile.width,1):Math.max(e.width/this.profile.width,e.height/this.profile.height,1)}isAllowed2k4k(e){var t;return!this.room||!this.room.scheduleResult||this.isScreen||e.height*e.width<2560*1440?!0:((t=this.room.scheduleResult.trtcAutoConf)==null?void 0:t["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return f(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e))return;let t={useExactDeviceId:!0};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),T.emit(E.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(t){throw this.log.error(`switch camera failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}})}listenDeviceChange(){ge&&!ge.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&ge.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current camera is lost: ${JSON.stringify(e)}`),ae(this.userId,{eventId:2003,param1:7,streamType:2});let t=yield je();t[0]?this.recapture(t[0].deviceId):ge.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return f(this,null,function*(){this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}encodeFrame(e,t){let s=t?8:this.mediaType;return this.pipeline.reduce((n,o)=>o?o(n,s):n,e)}get enableEncodeFrame(){return this.pipeline.some(e=>e)}play(e,t){return f(this,null,function*(){return g(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 f(this,null,function*(){try{yield Ie(le.prototype,this,"recapture").call(this,e)}catch(t){let s=(yield je()).find(n=>n.deviceId!==e);if(s)yield Ie(le.prototype,this,"recapture").call(this,s.deviceId);else throw t}})}};var al=Ns();if(navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:al,exposeOrigin:!0,permittedOrigins:["*"]})}catch(r){}var xp=function(r){return f(this,null,function*(){let i=null,e=Vp(r);S.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);r.systemAudio&&t.getAudioTracks().length===0&&(fr&&ht<74||Ve||te)&&S.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(n){S.warn(`screen applyConstraints failed: ${n}`)}r.captureElement&&(yield Pp(s,r.captureElement))}if(r.audio){let n=wp(r);S.info(`getUserMedia with constraints: ${JSON.stringify(n)}`),i=yield navigator.mediaDevices.getUserMedia(n),t.addTrack(i.getAudioTracks()[0])}return t})};function Pp(r,i){return f(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&z(r.cropTo))try{if(!(((e=r.getCaptureHandle())==null?void 0:e.handle)===al))return;let s=yield CropTarget.fromElement(i);yield r.cropTo(s)}catch(t){S.warn(`cropTo target failed ${t}`)}})}function wp(r){let i={echoCancellation:r.echoCancellation,autoGainControl:r.autoGainControl,noiseSuppression:r.noiseSuppression,sampleRate:r.sampleRate,channelCount:r.channelCount};return g(r.microphoneId)||(i.deviceId=r.microphoneId),{audio:i,video:!1}}function Vp(r){let i={preferCurrentTab:r.preferDisplaySurface==="current-tab"||!!r.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Ve?{max:r.width}:{ideal:r.width,max:r.width},height:Ve?{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:n=!1}=r;i.audio={echoCancellation:t,noiseSuppression:s,autoGainControl:n,sampleRate:48e3}}return i}var cl=xp;var Xe=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 f(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:s,noiseSuppression:n,audioTrack:o,videoTrack:a,captureElement:c,preferDisplaySurface:d}){try{let m;return a||o?(m=new MediaStream,a&&m.addTrack(a),o&&m.addTrack(o)):m=yield cl({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:s,noiseSuppression:n,captureElement:c,preferDisplaySurface:d}),yield this.setInputMediaStreamTrack(m.getVideoTracks()[0]),m}catch(m){throw this.log.error(`getDisplayMedia error observed ${m}`),m instanceof b?m:new b({code:A.INITIALIZE_FAILED,name:m.name,message:m.message})}})}switchDevice(e){return f(this,null,function*(){throw new Error("Method not implemented.")})}};var $t=class extends Oe{constructor(i){super(i),this._log.id=`s-${this._log.id}`}};var Up="registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});",_c;function dl(r){return f(this,null,function*(){let i=Je("dump");_c||(_c=Fi(i,URL.createObjectURL(new Blob([Up],{type:"application/javascript"})))),yield _c;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 So=class extends co{constructor(e){super();this.room=e;u(this,"_localAudioTrack");u(this,"_localScreenAudioTrack");u(this,"log",S.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,m;if(!this._localAudioTrack)return;let t=[],s=[];(l=this._localAudioPipline)!=null&&l.source.node&&(t.push(this._localAudioPipline.source.node),s.push("mic")),(m=this._localAudioPipline)!=null&&m.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),s.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),s.push("mix")),this.log.info(`dump audio track ${s}, duration: ${e}`);let n=new AbortController,o=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),n.abort("timeout")},e*1e3),c=()=>{for(let p=0;p<s.length;p++){let _=URL.createObjectURL(new Blob(o[p])),R=document.createElement("a");R.href=_,R.download=`${s[p]}.pcm`,R.style.display="none",document.body.appendChild(R),R.click(),URL.revokeObjectURL(_),R.remove()}clearTimeout(a),n.abort("download")},d=dl(t).then(p=>p.pipeTo(new WritableStream({write(_){_.forEach((R,C)=>o[C]=o[C]?o[C].concat(R[0]):[R[0]])}}),n).catch(_=>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 $t)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 $t?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 Io(r=30,i=2){return W((e,t)=>function(...s){return new Promise((n,o)=>{let a=setTimeout(()=>{let c=new b({code:A.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${r}s`});S.warn(c),i===2?o(c):i===1&&n()},r*1e3);e.apply(this,s).then(n,o).finally(()=>{clearTimeout(a)})})})}var Ec=class extends Ji{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);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===Ec.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=Ec;u(rt,"STATE_SUBSCRIBE","subscribe"),y([Io(5,1)],rt.prototype,"waitHasMediaTrack",1),y([ue($.INIT,rt.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),T.emit(E.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0)},ignoreError:!0})],rt.prototype,"subscribe",1),y([ue(rt.STATE_SUBSCRIBE,$.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),T.emit(E.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],rt.prototype,"unsubscribe",1);var ni=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&&_t&&Zn().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 Bp=[-1,-1,1,-1,-1,1,1,1],$p=[0,0,1,0,0,1,1,1],Qe=class extends ${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 $e){if(e.ctx&&t.create2d){let s=document.createElement("canvas"),n=typeof s.transferControlToOffscreen=="function"?s.transferControlToOffscreen():s;n.width=this.width,n.height=this.height,this.ctx2d=n.getContext("2d"),this._image=n,this._canvas=n}return}try{let s=e.ctx;this.texCoordBuffer=this.createBuffer($p),this.positionBuffer=this.createBuffer(Bp),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 $e&&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,n)=>{s&&(t.activeTexture(t.TEXTURE0+n),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,n)=>{t.enableVertexAttribArray(n),t.bindBuffer(t.ARRAY_BUFFER,s),t.vertexAttribPointer(n,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,n,o){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,t,s):this.ctx2d.drawImage(e,t,s,n,o),!0):!1}getInfo(){var m;let{totalFrames:e,x:t,y:s,width:n,height:o,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:n,height:o,timestamp:d,fps:l,name:a,cost:c},v({parent:(m=this.input)==null?void 0:m.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,s=t.createTexture();return this.useTextures(s),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),s}};y([ue($.INIT,"connected",{sync:!0})],Qe.prototype,"connect",1),y([ue("connected",$.INIT,{ignoreError:!0,sync:!0})],Qe.prototype,"disconnect",1),y([ue([],"closed",{sync:!0})],Qe.prototype,"close",1);var Fp=[0,1,1,1,0,0,1,0],Js=class extends Qe{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 $e?this.ctx2d=e.ctx:e.available&&(t==null?void 0:t.mirrorUpAndDown)&&this.setTexBuffer(Fp)}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)}},Dr=class extends Js{constructor(e,t){super(e,t);u(this,"_videoTrack");[this._videoTrack]=e._canvas.captureStream(e.frameRate).getVideoTracks();let s=n=>{var c;let o=()=>{var d;return(d=this._videoTrack)==null?void 0:d.removeEventListener(n,a)},a=()=>{o(),this.context.destroy(new Error(`video track ${n}`))};this.once("closed",o),(c=this._videoTrack)==null||c.addEventListener(n,a)};e instanceof ye&&s("mute"),s("ended")}get videoTrack(){return this._videoTrack}close(){var e;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack}},Ao=class extends Dr{render(i){var e;return!!((e=this.input)!=null&&e.requestFrame(i))}};var Co=class extends Dr{constructor(e,t){super(e,{name:"smallDestination"});this.resolution=t}resize(e,t){let s,n=e*t,o=this.resolution.width*this.resolution.height;S.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),n>o?s=n/o:(S.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${t} small: ${this.resolution.width} * ${this.resolution.height}`),s=n/(160*120)),super.resize(e/Math.sqrt(s),t/Math.sqrt(s))}};var js=class extends Qe{constructor(e,t){super(e,v({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 o,a;let{width:s,height:n}=this;if(this.image instanceof HTMLVideoElement){if(z(this.image.getVideoPlaybackQuality)&&!bt){let d=this.image.getVideoPlaybackQuality().totalVideoFrames;if(((a=(o=this.image.srcObject)==null?void 0:o.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:n}=this.image,!s||!n)return!1;this.image.width=s,this.image.height=n}else if(this.image instanceof HTMLImageElement||this.image instanceof ImageData||this.image instanceof ImageBitmap){if({width:s,height:n}=this.image,this.image!==this._lastImage)this._lastImage=this.image;else if(s===this.width&&n===this.height)return!1}else(this.image instanceof HTMLCanvasElement||this.image instanceof OffscreenCanvas)&&({width:s,height:n}=this.image,this._lastImage=this.image);if(!this._autoResize)return!0;if(this.width===s&&this.height===n&&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,n)}return!0}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},qs=class extends js{constructor(e,t,s){super(e,s);this._player=t;this.name="videoPlayerSource"}get image(){return this._player.element}},Or=class extends qs{constructor(i,e,t){super(i,new We({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 Hp=`
|
|
// \u9876\u70B9\u7740\u8272\u5668
|
|
attribute vec4 a_position;
|
|
attribute vec2 a_texCoord;
|
|
varying vec2 v_texCoord;
|
|
|
|
void main() {
|
|
gl_Position = a_position;
|
|
v_texCoord = a_texCoord;
|
|
}
|
|
`,Gp=`
|
|
// \u7247\u5143\u7740\u8272\u5668
|
|
precision mediump float;
|
|
varying vec2 v_texCoord;
|
|
uniform sampler2D u_texture;
|
|
|
|
void main() {
|
|
gl_FragColor = texture2D(u_texture, v_texCoord);
|
|
} `,Ro=class extends ${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 Or(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new Dr(this,e)}createVideoImageSource(e,t){return new js(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new qs(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}},Wp={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},ye=class extends Ro{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.ctx=this._canvas.getContext("webgl2",Wp),!this.ctx)throw new Error("webgl2 not supported");this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,Hp),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,Gp),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,n=s.createShader(e);return s.shaderSource(n,t),s.compileShader(n),n}createProgram(e,t){let s=this.ctx,n=s.createProgram();return s.attachShader(n,e),s.attachShader(n,t),s.linkProgram(n),s.getProgramParameter(n,s.LINK_STATUS)||this.log.error(s.getProgramInfoLog(n)),n}};y([ue($.INIT,"created",{sync:!0})],ye.prototype,"create",1),y([ue("created",$.INIT,{ignoreError:!0,sync:!0,success(r){r&&this.emit("unavailable",r),this.removeAllListeners()}})],ye.prototype,"destroy",1);var $e=class extends Ro{constructor(){super(...arguments);u(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),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($.INIT,"created",{sync:!0})],$e.prototype,"create",1),y([ue("created",$.INIT,{ignoreError:!0,sync:!0})],$e.prototype,"destroy",1);function Jp(r){return[15,30,45,60].reduce((e,t)=>Math.abs(t-r)<Math.abs(e-r)?t:e)}var gt=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(_s===17||(t==null?void 0:t.canvasRender))&&!this.source&&this.useCanvasPlayer(),super.play(e,t)}useCanvasPlayer(){if(this.log.info(`useCanvasPlayer(), ${!!this.player.element}`),!this.player.element)return;let e=new $e({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=e.createVideoPlayerSource(this.player);this.source=t;let s=new Js(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=Jp(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 o;let{msg_video_status:e}=((o=this.room.heartbeatReport)==null?void 0:o.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)}},Mr=class extends gt{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 jp=r=>r();function Tc(){this.dispose()}var qp=()=>typeof __FASTRX_DEVTOOLS__!="undefined",Xp=1,oi=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new gc(i,this,this.streamId++);return Tt.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},Xs=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 oi?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(jp),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}},F=class extends Xs{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 ul(r,...i){return i.reduce((e,t)=>t(e),r)}function ai(r,i,e){if(qp()){let t=Object.defineProperties(Object.setPrototypeOf(r,oi.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}});Tt.create(t);for(let s=0;s<e.length;s++){let n=e[s];typeof n=="function"&&n instanceof oi&&Tt.addSource(t,n)}return t}return r}function J(r,i){return function(...e){return t=>{if(t instanceof oi){let s=ai(n=>{let o=new r(n,...e);o.sourceId=s.id,o.subscribe(t)},i,arguments);return s.source=t,Tt.pipe(s),s}else return s=>t(new r(s,...e))}}}function Ni(r,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:r,payload:i}})}var gc=class extends F{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{Tt.defer(this.source,this.id)})}next(i){Tt.next(this.source,this.id,i),this.sink.next(i)}complete(){Tt.complete(this.source,this.id),this.sink.complete()}error(i){Tt.complete(this.source,this.id,i),this.sink.error(i)}},Tt={addSource(r,i){Ni("addSource",{id:r.id,name:r.toString(),source:{id:i.id,name:i.toString()}})},next(r,i,e){Ni("next",{id:r.id,streamId:i,data:e&&e.toString()})},subscribe({id:r,end:i},e){Ni("subscribe",{id:r,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(r,i,e){Ni("complete",{id:r.id,streamId:i,err:e?e.toString():null})},defer(r,i){Ni("defer",{id:r.id,streamId:i})},pipe(r){Ni("pipe",{name:r.toString(),id:r.id,source:{id:r.source.id,name:r.source.toString()}})},update(r){Ni("update",{id:r.id,name:r.toString()})},create(r){r.id||(r.id=Xp++),Ni("create",{name:r.toString(),id:r.id})}},bo=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var Sc=class extends Xs{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 No(){return r=>{let i=new Sc(r);if(r instanceof oi){let e=ai(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=r,Tt.pipe(e),e}return ai(i.add.bind(i),"share",arguments)}}function Qp(...r){return ai(i=>{let e=r.length,t=e,s=e,n=new Array(e),o=()=>{--s===0&&i.complete()},a=(c,d)=>{let l=new F(i);l.next=m=>{--t===0?(l.next=p=>{n[d]=p,i.next(n)},l.next(m)):n[d]=m},l.complete=o,l.subscribe(c)};r.forEach(a)},"combineLatest",arguments)}var Ic=class extends F{constructor(i,...e){super(i);let t=new F(this.sink);t.next=s=>this.buffer=s,t.complete=Te,t.subscribe(Qp(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},OA=J(Ic,"withLatestFrom"),Ac=class extends F{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()}},MA=J(Ac,"bufferCount"),Cc=class extends F{constructor(i,e){super(i),this.buffer=[];let t=new F(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()}},kA=J(Cc,"buffer");function Rc(r){let i=arguments,e=No()(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 ll(r){return ai(i=>{let e=0,t=setInterval(()=>i.next(e++),r);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}var yc=class extends F{constructor(i,e,t){super(i),this.f=e;let s=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=n=>{this.acc=n,this.complete=s,this.resetNext()}:(this.acc=t,this.complete=s)}next(i){this.acc=this.f(this.acc,i)}},zp=J(yc,"reduce");var bc=class extends F{constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},Yp=J(bc,"filter"),Nc=class extends F{next(i){}},GA=J(Nc,"ignoreElements"),vc=class extends F{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&this.complete()}},Kp=J(vc,"take"),Dc=class extends F{constructor(i,e){super(i);let t=new F(i);t.next=()=>i.complete(),t.complete=Tc,t.subscribe(e)}},WA=J(Dc,"takeUntil"),Oc=class extends F{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):this.complete()}},Zp=J(Oc,"takeWhile");var Mc=class extends F{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},JA=J(Mc,"skip"),kc=class extends F{constructor(i,e){super(i),i.next=Te;let t=new F(i);t.next=()=>{t.dispose(),i.resetNext()},t.complete=Tc,t.subscribe(e)}},jA=J(kc,"skipUntil"),Lc=class extends F{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},ef=J(Lc,"skipWhile"),tf={leading:!0,trailing:!1},xc=class extends F{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)}},Pc=class extends F{constructor(i,e,t=tf){super(i),this.durationSelector=e,this.config=t,this._throttle=new xc(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()}},qA=J(Pc,"throttle");var wc=class extends F{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Vc=class extends F{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new wc(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()}},XA=J(Vc,"debounce");var Uc=class extends F{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()}},QA=J(Uc,"elementAt");var Bc=class extends F{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}},zA=J(Bc,"findIndex"),$c=class extends F{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()}},YA=J($c,"first"),Fc=class extends F{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()}},KA=J(Fc,"last"),Hc=class extends F{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()}},ZA=J(Hc,"every");var Gc=class extends F{constructor(i,e,t){super(i),this.f=e,typeof t=="undefined"?this.next=s=>{this.acc=s,this.resetNext(),this.sink.next(this.acc)}:this.acc=t}next(i){this.sink.next(this.acc=this.f(this.acc,i))}},rC=J(Gc,"scan"),Wc=class extends F{constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},sC=J(Wc,"pairwise"),Jc=class extends F{constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},hl=J(Jc,"map");var kr=class extends F{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()}},Lr=class extends F{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()}},vo=class extends kr{},Do=class extends Lr{next(i){this.subInner(i,vo),this.next=e=>{this.currentSink.dispose(),this.subInner(e,vo)}}},rf=J(Do,"switchMap");function Lo(r){return(i,e)=>r(()=>i,e)}var nC=Lo(J(Do,"switchMapTo")),jc=class extends kr{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},Oo=class extends Lr{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(),jc),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},oC=J(Oo,"concatMap"),aC=Lo(J(Oo,"concatMapTo")),qc=class extends kr{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Mo=class extends Lr{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,qc),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},cC=J(Mo,"mergeMap"),dC=Lo(J(Mo,"mergeMapTo")),Xc=class extends kr{dispose(){this.context.resetNext(),super.dispose()}},ko=class extends Lr{next(i){this.next=Te,this.subInner(i,Xc)}},uC=J(ko,"exhaustMap"),lC=Lo(J(ko,"exhaustMapTo")),Qc=class extends F{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=Rc(),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)}},hC=J(Qc,"groupBy"),zc=class extends F{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(zc,"timeInterval"),Yc=class extends F{constructor(i,e){super(i),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(i){this.buffer.push(i)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},pC=J(Yc,"bufferTime"),Kc=class extends F{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)}},fC=J(Kc,"delay"),Zc=class extends F{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},_C=J(Zc,"catchError");var ed=class extends F{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)}))}},SC=J(ed,"tap"),td=class extends F{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new bo(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},IC=J(td,"timeout");var UC=ul(ll(250),hl(()=>performance.now()),No());var xr=new Map;T.on(E.JOIN_SUCCESS,({room:r})=>{ae(r.userId,{eventId:32788})});T.on(E.LEAVE_START,({room:r})=>{ae(r.userId,{eventId:32789})});T.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})}});T.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})}});T.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}))});T.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}))});T.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}))});T.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}))});T.on(E.SWITCH_DEVICE_SUCCESS,({track:r})=>{r.room&&ae(r.room.userId,{eventId:r.kind===h.VIDEO?32780:32781})});T.on(E.LOCAL_TRACK_REPLACED,({track:r})=>{r.room&&ae(r.room.userId,{eventId:r.kind===h.VIDEO?32782:32783})});T.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})});T.on(E.PEER_CONNECTION_STATE_CHANGED,({room:r,prevState:i,state:e,remoteUserId:t})=>{let s=!!t,n;switch(e){case"CONNECTED":i==="RECONNECTING"?n=s?32801:32798:n=s?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(n=s?32802:32799);break;case"RECONNECTING":n=s?32800:32797;break}n&&ae(r.userId,{eventId:n,remoteUserId:t})});T.on(E.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({userId:r,remoteUserId:i,codec:e,isHWCodec:t,prevImplementation:s,streamType:n})=>{let o=t?1:0;s||(o=t?3:2);let a=e==="h264"?0:2,c={eventId:4004,param1:o,param2:a,streamType:n||2};i&&(c.remoteUserId=i,c.eventId=4005),ae(r,c),D.addEnum({key:i?514701:513701,value:o}),D.addEnum({key:i?514700:513700,value:a})});T.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=w(v({},i),{timestamp:zr()});xr.has(r)?xr.get(r).push(e):xr.set(r,[e])}function ml(r){if(xr.has(r)){let i=xr.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 xr.delete(r),i}return[]}var pl=Se(Ne(),1);var xo=class extends pl.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:n,role:o}=e;if(this.userMap.has(t))return;let a={userId:s,tinyId:n,role:o===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 n=`peer leave [${e}]`;g(t)||(n+=`:${Sa[t]}`),this._log.info(n);let o=this.remotePublishedUserMap.get(e);if(o){let a=o.muteState;o.flag=0,this.emit("5",o.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:o.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(n=>n[this.key]===t[this.key])<0){this._log.info(`remote [${s}] unpublish`);let n=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(s),this.emit("6",{prevMuteState:n,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var l;let s=t[this.key];if(s===this.mySelfId)return;let{flag:n,userId:o,tinyId:a}=t,c=Ai(n,o),d=(l=this.remotePublishedUserMap.get(s))==null?void 0:l.muteState;if(d){let m=this.remotePublishedUserMap.get(s);m&&m.flag!==n&&(m.flag=n,this._log.info(`remote publish updated: ${JSON.stringify(m.muteState)}`),this.emit("6",{prevMuteState:d,muteState:c,flag:n}))}else this._log.info(`remote publish. state: ${JSON.stringify(c)}`),this.addUser({userId:o,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:Ai(0,o),muteState:c,flag:n})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function id({timesInSecond:r,maxSizeInSecond:i,getSize:e}){return W((t,s)=>{let n=new Map;return T.on(E.ROOM_DESTROY,({room:o})=>n.delete(o)),function(...o){let a=n.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},n.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(...o)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=r||a.totalSizeInSecond>i))throw new b({code:A.INVALID_OPERATION,message:k({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,...o)}})}var fl=!0,_l=function(){var r;fl&&(fl=!1,S.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${At}/en/index.html`),console.info(`* Changelog: ${At}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),S.info("TRTC Web SDK Version:",Re),S.info("UA:",navigator.userAgent),S.info(`URL: ${location.href}${((r=self.frameElement)==null?void 0:r.tagName)==="IFRAME"?" in iframe":""}`),Es().then(i=>{i&&S.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 rd=(i=>(i.Debug="Debug",i))(rd||{});var P={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},Ft=(I=>(I[I.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",I[I.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",I[I.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",I[I.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",I[I.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",I[I.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",I[I.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",I[I.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",I[I.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",I[I.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",I[I.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",I[I.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",I[I.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",I[I.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",I[I.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",I[I.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",I[I.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",I[I.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",I[I.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",I[I.INVALID_OPERATION=5100]="INVALID_OPERATION",I[I.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",I[I.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",I[I.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",I[I.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",I[I.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",I[I.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",I[I.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",I[I.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",I[I.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",I[I.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",I[I.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",I[I.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",I[I.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",I[I.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",I[I.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",I[I.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",I[I.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",I[I.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",I[I.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",I[I.DEVICE_ERROR=5300]="DEVICE_ERROR",I[I.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",I[I.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",I[I.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",I[I.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",I[I.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",I[I.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",I[I.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",I[I.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",I[I.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",I[I.SERVER_ERROR=5400]="SERVER_ERROR",I[I.NEED_TO_BUY=5401]="NEED_TO_BUY",I[I.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",I[I.OPERATION_FAILED=5500]="OPERATION_FAILED",I[I.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",I[I.REJOIN_FAILED=5502]="REJOIN_FAILED",I[I.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",I[I.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",I[I.OPERATION_ABORT=5998]="OPERATION_ABORT",I[I.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",I))(Ft||{});function gl({code:r,params:i,enableDocLink:e=!1}){let t="",s,n=Ft[r];try{s=El[n]}catch(o){s=El.UNKNOWN_ERROR}return z(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 El=w(v({},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}`,n="";return Array.isArray(i.type)?n=i.type.join("|"):n=i.type,`'${s}' must be type of ${n} when calling ${e}(), received type: ${_e(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}`,n=`${i.instanceOf.name||i.instanceOf}`;return`'${s}' must be instanceof ${n} when calling ${e}(), received type: ${_e(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 Xi=class extends Error{constructor({code:e,extraCode:t,message:s="",messageParams:n,fnName:o="",originError:a}){var d;let c;s?c=s:c=gl({code:t||e,params:v({fnName:o,error:a},n)});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=Ft[e],this.code=e,this.extraCode=t,this.functionName=o,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"},m={startLocalVideo:"webcam",startLocalAudio:"microphone"},p=document.createElement("a");Ei?p.href=`ms-settings:privacy-${m[this.functionName]}`:yt&&(p.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${l[this.functionName]}`),p.href.length>0&&p.click()})}static convertFrom(e,t,s){let n=e;if(e instanceof b){let{stack:o}=e,a={code:P.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case A.INVALID_PARAMETER:a.code=P.INVALID_PARAMETER,a.message=e.message;break;case A.INVALID_OPERATION:a.code=P.INVALID_OPERATION;break;case A.NOT_SUPPORTED:case A.NOT_SUPPORTED_H264:a.code=P.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=P.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case A.API_CALL_ABORTED:a.code=P.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=sf(e.name));break;case A.UNKNOWN:break;default:a.code=P.OPERATION_FAILED}n=new Xi(a),o&&(n.stack+=o.substr(o.indexOf(`
|
|
`)))}else{if(e instanceof Xi)return e;n=new Xi({code:P.UNKNOWN_ERROR,fnName:t,originError:e})}return n}};function sf(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 L=Xi;var Tl={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}}},Sl={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}}},Pr={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(r,i,e){if(Y(r)&&!document.getElementById(r))throw new L({code:P.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},Il={name:"userId",required:!0,type:"string"},Al={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 zs(r,i){if(!r)throw new L({code:P.INVALID_OPERATION,extraCode:5101,fnName:i})}function Cl(r,i,e){if(!r)throw new L({code:P.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}var My={type:"number",notLessThanZero:!0},nf={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 L({code:P.INVALID_OPERATION,extraCode:5104,fnName:e});if(r.roomId){if(Y(r.roomId))throw new L({code:P.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});if(!(/^[1-9]\d*$/.test(String(r.roomId))&&r.roomId<4294967295))throw new L({code:P.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 L({code:P.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:i}})}else throw new L({code:P.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:Pr,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:Tl},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.videoTrack)&&ti())throw new L({code:P.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:w(v({},Pr),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:Tl}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:Al},validate(r){var i;if(!((i=r==null?void 0:r.option)!=null&&i.audioTrack)&&ti())throw new L({code:P.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:Al}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:Pr,publish:{type:"boolean"},option:Sl},validate(r,i,e,t,s){var n;if(!((n=r==null?void 0:r.option)!=null&&n.videoTrack)&&ti())throw new L({code:P.ENV_NOT_SUPPORTED,extraCode:5201});if(!Ds())throw new L({code:P.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:Pr,publish:{type:"boolean"},option:Sl}},muteRemoteAudio:[Il,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[Il,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:Pr,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){zs(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(Cl(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new L({code:P.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:r}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:w(v({},Pr),{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){zs(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(r.userId);if(Cl(!!t,e,r),t&&(r.streamType==="main"&&!t.muteState.videoAvailable||r.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new L({code:P.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:r}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(r,i,e){if(r.userId!=="*"&&g(r.streamType))throw new L({code:P.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(r,i,e){zs(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(!_t)throw new L({code:P.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new L({code:P.INVALID_OPERATION,fnName:e,extraCode:5108});if(r.byteLength>1e3)throw new L({code:P.INVALID_PARAMETER,extraCode:5018,fnName:e});if(r.byteLength===0)throw new L({code:P.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});zs(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 L({code:P.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 L({code:P.INVALID_PARAMETER,extraCode:5018,fnName:e});if(r.byteLength===0)throw new L({code:P.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(r,i,e){if(zs(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new L({code:P.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}}},Ce={TRTC:nf};var Me=class extends Error{};function of(r,i){let e=Sr(r);for(let t=0;t<i.length;t++)Yt(e[t],i[t]);return e}function af(r){this._resolve=Promise.resolve(r)}function cf(r){this._reject=Promise.reject(r)}var Qi=class{constructor(i,e){this.instance=i;this.group=e;this.started=!1;this.ops=[];this.startSame=()=>!0;this.mergeUpdate=of;let t=Qi.instances.get(i);t?t.set(e,this):Qi.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=Qi.instances.get(i);return t&&t.get(e)||new Qi(i,e)}static gets(i,e){let t=Qi.instances.get(i),s=[];return t&&t.forEach((n,o)=>{e.test(o)&&s.push(n)}),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},n=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},o={type:i,action:()=>e(...o.args).then(s,n),args:t,resolve:af,reject:cf};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(o)}}catch(a){return Promise.reject(a)}return this.ops.push(o),o.promise=e(...o.args).then(s,n)}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=Qi;Ht.instances=new WeakMap;var wo=new WeakMap,Vo=(r,i)=>{if(i instanceof Me){let{stack:e}=i;i=new L({code:P.OPERATION_ABORT,message:`${r} abort: ${i.message}`,fnName:r}),e&&(i.stack+=e.substr(e.indexOf(`
|
|
`)))}throw i};function vi(r,i){return W((e,t)=>function(...s){let n=Ht.get(this,typeof r=="string"?r:r.call(this,...s));return n?(i&&(n.startSame=i.bind(this)),n.action(0,e.bind(this),s).catch(Vo.bind(null,t))):e.apply(this,s)})}function zi(r,i){let{merge:e,debounce:t}=i||{};return W((s,n)=>function(...o){let a=Ht.get(this,typeof r=="string"?r:r.call(this,...o));if(!a)return s.apply(this,o);if(e&&(a.mergeUpdate=e.bind(this)),t&&t.isNeedToDebounce.apply(this,o)){let{delay:c,getKey:d}=t;return new Promise((l,m)=>{var R,C;let p=(R=wo.get(this))==null?void 0:R.get(d(...o));if(p){let{timeoutId:N,resolve:U}=p;clearTimeout(N),U()}let _=setTimeout(()=>{if(a.state===3||a.state===4)return l();a.action(2,s.bind(this),o).catch(Vo.bind(null,n)).then(l,m)},c);wo.has(this)?(C=wo.get(this))==null||C.set(d(...o),{timeoutId:_,resolve:l}):wo.set(this,new Map([[d(...o),{timeoutId:_,resolve:l}]]))})}return a.action(2,s.bind(this),o).catch(Vo.bind(null,n))})}function Di(r){return W((i,e)=>function(...t){let s=typeof r=="function"?r.call(this,...t):r;if(s instanceof RegExp)return Promise.all(Ht.gets(this,s).map(o=>o.action(3,()=>Promise.resolve(),t))).then(()=>i.call(this,...t));let n=Ht.get(this,s);return n?n.action(3,i.bind(this),t).catch(Vo.bind(null,e)):i.apply(this,t)})}var H={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",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 Uo(r){return r==="sub"?"auxiliary":r==="auxiliary"?"sub":"main"}function Yi(r){return r===st.QOS_PREFERENCE_CLEAR?"detail":r===st.QOS_PREFERENCE_SMOOTH?"motion":""}var df=r=>r.startsWith("data:application/octet-stream;base64,"),uf=r=>r.startsWith("file://"),Bo=class{constructor(){u(this,"_log");this._log=S.createLogger({id:"fd"})}download(i,e){return f(this,null,function*(){let{type:t="blob"}=e||{};try{let s=x(),n;if(z(fetch)?n=yield this.downloadWithFetch(i,t):n=yield this.downloadWithXHR(i,t),!n||!n.data)throw new Error("data is empty");let o=x()-s;return this._log.info(`downloaded: ${i}, return type: ${t}, cost: ${o}ms`),D.addSuccessEvent({key:522700,cost:x()-s}),n.data}catch(s){throw this._log.error(`failed to download: ${i}, error: ${s}`),D.addFailedEvent({key:522700,error:s}),s}})}downloadWithFetch(i,e){return f(this,null,function*(){this._log.info(`download with fetch: ${i}, return type: ${e}`);try{let t=yield fetch(i);if(!t.ok)throw new Error("network response was not ok");let s;return e==="arraybuffer"?s=yield t.arrayBuffer():s=yield t.blob(),{data:s}}catch(t){throw t}})}downloadWithXHR(i,e){return this._log.info(`download with xhr: ${i}, return type: ${e}`),new Promise((t,s)=>{let n=new XMLHttpRequest;n.open("GET",i,!0),n.responseType=e,n.onload=()=>{n.status===200||n.status===0&&n.response?t({data:n.response}):s(new Error("XHR failed"))},n.onerror=s,n.send(null)})}loadWasm(i,e){return f(this,null,function*(){this._log.info(`loadWasm ${i}, importObject: ${JSON.stringify(e)}`);let t=x(),s=null,n=null;if(z(WebAssembly.instantiateStreaming)&&!df(i)&&!uf(i)&&z(fetch))try{let o=fetch(i);s=(yield WebAssembly.instantiateStreaming(o,e)).instance}catch(o){n=o}if(!s)try{let o=yield this.download(i,{type:"arraybuffer"});s=(yield WebAssembly.instantiate(o,e)).instance}catch(o){n=o}if(s){let o=x()-t;return this._log.info(`loadedWasm ${i}, cost: ${o}ms`),D.addSuccessEvent({key:522701,cost:o}),s}throw this._log.error(`failed to loadWasm ${i}, error: ${n}`),D.addFailedEvent({key:522701,error:n}),n})}};y([it({settings:{timeout:0,retries:3},onRetrying(r){this._log.warn(`download retrying: ${r}`)}})],Bo.prototype,"download",1);var Rl=new Bo;function yl({TRTC:r,room:i,errorModule:e,assetsPath:t}){return{TRTC:r,room:i,assetsPath:t,fileDownloader:Rl,innerEmitter:T,constants:Ia,environment:Er,utils:Pe,eventLogger:Z,log:this.room.getLogger(),loggerManager:S,errorModule:e,kvStatManager:D,trtc:this,clearStarted:(s,n)=>{let o=s.getAlias(),a=Ht.instances.get(this);if(!!a)if(n){let c=a.get(o+n);if(!c)return;c.started=!1}else a.forEach((c,d)=>{d.startsWith(o)&&(c.started=!1)})}}}var bl=(r,i)=>{let{emit:e}=r;return r.emit=(...t)=>{try{return e.apply(r,t)}catch(s){let n=k({key:M.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return S.warn(`${n}
|
|
|
|
${s.stack}`),!1}},r};var $o=new WeakMap;function Nl(r,i){return W((e,t)=>function(...s){var a,c;let n=(a=$o.get(this))==null?void 0:a.get(i(...s));n&&n>0&&clearTimeout(n);let o=window.setTimeout(()=>{e.apply(this,s)},r);$o.has(this)?(c=$o.get(this))==null||c.set(i(...s),o):$o.set(this,new Map([[i(...s),o]]))})}var vl="5.8.0";function ke(...r){return W((i,e)=>function(...t){try{Ho.call(this,r,t,e,this._name)}catch(s){return Promise.reject(s)}return i.apply(this,t)})}function od(...r){return W((i,e)=>function(...t){try{Ho.call(this,r,t,e,this._name)}catch(s){throw s}return i.apply(this,t)})}function Ho(r,i,e,t){if(he(r))for(let s=0;s<r.length;s++)Fo.call(this,{rule:r[s],value:i[s],key:r[s].name,fnName:e,className:t});else Fo.call(this,{rule:r,value:i[0],key:r.name,fnName:e,className:t})}function Fo({rule:r,value:i,key:e,fnName:t,className:s}){function n(c){return{code:P.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:r,value:i}}}if(g(i)){if(r.required)throw new L(n(5001));if(g(r.defaultValue)){z(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),z(r.type[d])&&i instanceof r.type[d]&&(c=!0),Y(r.type[d])&&_e(i)===r.type[d].toLowerCase()&&(c=!0);if(!c)throw new L({code:P.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:r.type.map(d=>Cs(d)?Wn(d):Y(d)?d:_e(d))},value:i}})}else if(!g(r.type)&&_e(i)!==r.type)throw new L(n(5002));if(r.allowEmpty===!1){let c=ee(i)&&(i===0||Number.isNaN(i)),d=Y(i)&&i.trim()==="";if(c||d)throw new L(n(5003))}if(r.notLessThanZero&&ee(i)&&i<0)throw new L(n(5006));if(!g(r.min)&&ee(i)&&i<r.min)throw new L(n(5007));if(!g(r.max)&&ee(i)&&i>r.max)throw new L(n(5008));if(Y(r.instanceOf)){if(!i||i._name!==r.instanceOf)throw new L(n(5004))}else if(z(r.instanceOf)&&!(i instanceof r.instanceOf))throw new L(n(5004));if(Array.isArray(r.values)&&!r.values.includes(i))throw new L(n(5005));let{properties:o}=r;Ge(o)&&mt(i)&&Object.keys(o).forEach(c=>{Fo.call(this,{rule:o[c],value:i&&i[c],key:`${c}`,fnName:t,className:s})});let{arrayItem:a}=r;Ge(a)&&he(i)&&i.forEach((c,d)=>{Fo.call(this,{rule:a,value:c,key:`${e}[${d}]`,fnName:t,className:s})}),z(r.validate)&&r.validate.call(this,i,e,t,s,this)}function ne(r={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t}=r;return W((s,n)=>function(...o){function a(l,m,p){if(p&&p.includes(l))return"hided";if(e){let _=e(...o);if(o[_.argIndex]===m)return _.value}if(m===o||l in o)return m;try{return m instanceof HTMLElement?`id: ${m.id} type:${_e(m)}`:(JSON.stringify(m),m)}catch(_){return`type:${_e(m)}`}}let c=this._log||S;o.length>0?c.info(`${n}() ${JSON.stringify(o,(l,m)=>a(l,m,["userSig","privateMapKey"]))}`):c.info(`${n}()`);let d=t?t(...o):ro[n];try{let l=s.apply(this,o),m=x();return As(l)?l.then(p=>(c.info(`${n}() success ${i.call(this,...o)}`),D.addSuccessEvent({key:d,cost:x()-m}),p)).catch(p=>{throw p=L.convertFrom.call(this,p,n,o.length===1?o[0]:o),c.error(`${n}() failed ${i.call(this,...o)} ${p} params: ${JSON.stringify(o,a)}`),D.addFailedEvent({key:d,error:p}),p}):(D.addSuccessEvent({key:d}),l)}catch(l){throw l=L.convertFrom.call(this,l,n),c.error(`${n}() failed ${l} params: ${JSON.stringify(o,a)}`),D.addFailedEvent({key:d,error:l}),l}})}var Go=r=>W((i,e)=>function(t,s){return f(this,null,function*(){let n=this._plugins.get(t);if(!n)throw this._log.error(`plugin ${String(t)} is not found`),new L({code:P.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});return Ho.call(this,n.getValidateRule(r),[s],e,"TRTC"),i.call(this,n,s)})});var Wo=0,ad=class{constructor(i,e){u(this,"player");u(this,"publisher");u(this,"mixInput");this.mixInput=new br(e),i.url?(this.player=new Audio(i.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(i.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(i.track),this.mixInput.connect()}updateSettings(i){!this.player||(g(i.volume)||(this.volume=i.volume),g(i.loop)||(this.loop=i.loop),g(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(!!this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(i){!this.player||i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i)}play(){var i,e;return(i=this.publisher)==null||i.play(),(e=this.player)==null?void 0:e.play()}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function wr(r,i){if(i&&typeof i!="function")throw new L({code:P.INVALID_PARAMETER,message:`start audioMixer plugin: param ${r} should be a function.`})}var Vr=class{constructor(i){this.core=i;u(this,"log");u(this,"mixedMusicMap",new Map);u(this,"cacheMusicMap",new Map);Wo=Wo+1,this.log=i.log.createChild({id:`${this.getAlias()}${Wo}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Wo}`),this.core=i}getName(){return Vr.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return Vr.startValidateRule;case"update":return Vr.updateValidateRule;case"stop":return Vr.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${i.id} url: ${i.url}, track: ${i.track}`);let{id:t,url:s}=i;if(this.mixedMusicMap.has(t))return;let n=this.cacheMusicMap.get(t);n?i.url?n.reset():(n.mixInput.replaceSource(i.track),n.mixInput.connect()):(n=new ad(i,e.audioManager),this.cacheMusicMap.set(t,n)),n.updateListener(i),n.updateSettings(i),yield n.play(),this.mixedMusicMap.set(t,n),this.log.info(`start mix audio track ${t} success.`),D.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return f(this,null,function*(){let{id:e,operation:t,seekFrom:s,playbackRate:n}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let o=this.mixedMusicMap.get(e);if(!o){this.log.warn(`update music source failed, music id: ${e} not found.`);return}o.updateSettings(i),o.updateListener(i),g(t)||o.setOperation(t),g(s)||o.seek(s),this.kvUpload(i)})}stop(e){return f(this,arguments,function*({id:i}){var t;this.mixedMusicMap.has(i)&&(this.log.info(`remove music source, music id: ${i}`),(t=this.mixedMusicMap.get(i))==null||t.stop(),this.mixedMusicMap.delete(i)),i==="*"&&this.destroyAllMusic()})}kvUpload(i){let{track:e,loop:t,volume:s,playbackRate:n,operation:o,seekFrom:a,onTimeUpdate:c,onDurationChange:d,onEnded:l}=i;e&&D.addCount({key:502711}),t&&D.addCount({key:502703}),s&&D.addCount({key:502704}),n&&D.addCount({key:502705}),o&&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()}},Oi=Vr;u(Oi,"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],n=["mp3","ogg","wav","flac"],o=s.split(".").pop(),a=n.indexOf(o)>=0,c=s.startsWith("blob"),d=s.startsWith("data");if(!(a||c||d))throw new L({code:P.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new L({code:P.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)}}),u(Oi,"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)}}),u(Oi,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),u(Oi,"Name","AudioMixer");var Dl=r=>(r=Number(r),r>0&&r<14e8);var Jo=0,cd,Ur=class{constructor(i){this.core=i;u(this,"log");u(this,"audioContext",Je("denoiser"));u(this,"workletNode");Jo=Jo+1,this.log=i.log.createChild({id:`${this.getAlias()}${Jo}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${Jo}`),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,n){if(!i.room.audioManager.hasAudioTrack)throw new L({code:P.INVALID_OPERATION,extraCode:5106,fnName:s})}}}preload(i){return cd||(cd=this.doPreload(i)),cd}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Fi(this.audioContext,t)}finally{URL.revokeObjectURL(t)}})}getName(){return Ur.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return Ur.startValidateRule(this.core);case"update":return Ur.updateValidateRule;case"stop":return Ur.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;if(yield this.preload(`${i.assetsPath}/denoiser-wasm.js`),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:o,message:a}=yield mf(w(v({},i),{timestamp:t}));if(!s)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${s}. Message: ${a}`),new L({code:P.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:n,status:o}}),this.workletNode.port.onmessage=c=>{let{data:d}=c;d.type==="cost"&&this.log.debug(`[RTCAIDenoiser] ${d.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return f(this,null,function*(){})}stop(){return f(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}destroy(){}},Ki=Ur;u(Ki,"updateValidateRule",{type:"object"}),u(Ki,"stopValidateRule",{type:"object"}),u(Ki,"Name","AIDenoiser");var Ol={MAIN:"schedule.cloud-rtc.com",MAIN_OVERSEA:"schedule.rtc.tencentcloud.com"};function hf(r){let i;return Dl(r)?i=Ol.MAIN_OVERSEA:i=Ol.MAIN,i}function mf(s){return f(this,arguments,function*({sdkAppId:r,userId:i,userSig:e,timestamp:t}){let o=`https://${hf(r)}/api/v1/audioAiAuth?sdkAppId=${r}&userId=${i}&userSig=${e}×tamp=${t}`,a=yield fetch(o),{data:{errCode:c,errMsg:d,sign:l,status:m}}=yield a.json();if(m==="1")return{auth:!0,sign:l,status:m,message:d};let p="Init RTCAIDenoiser failed.",_="";switch(c){case 1:_="Please check your params.";break;case 2:_="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:_="Server is invalid. Please contact our engineer. ";break;case 4:_="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:_="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:_="Your version is not supported.";break}return{auth:!1,status:m,message:d?`${p} Reason: ${d}. ${_}`:`${p}, ${_}`}})}var Ml=Se(Ne(),1);var dd=class extends Ml.EventEmitter{constructor(){super();this.state="nominal";this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return f(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!de&&(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)&&S.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})}}},pf=new dd,ud=pf;var ld=0,hd=class{constructor(i){this.core=i;u(this,"log");u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(this,"_subStreamSeiMessageList",[]);ld++,this.log=i.log.createChild({id:`${this.getAlias()}${ld}`}),this.log.info(`[sei] created id=${this.getAlias()}${ld}`),this.core=i}hasSEI(i){return i.getInt32(0)===1&&i.getInt8(4)===6}encodeSEINalu([i,e]){let t=e.byteLength,s=parseInt(String(t/255),10),n=t%255,o=[];o.push(0,0,0,1,6,i);for(let c=0;c<s;c++)o.push(255);o.push(n);let a=new DataView(e);return o.push(...new Uint8Array(a.buffer)),o.push(128),new ji(new DataView(new Uint8Array(o).buffer),!0)}getNaluCount(i){let e=0,t=0,s=new DataView(i);for(let n=0;n<i.byteLength;n++)switch(s.getUint8(n)){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===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList;if(t.length>0&&i.data.byteLength>0){let s=this.getNaluCount(i.data),n=9-s;if(n<=0)return 0;let o=t.splice(0,n).reverse().map(this.encodeSEINalu.bind(this)),a=o.reduce((p,_)=>p+_.dataView.byteLength,0),c=new ArrayBuffer(a+i.data.byteLength),d=new DataView(c),l=new DataView(i.data),m=0;for(let p=0;p<o.length;p++)for(let _=0;_<o[p].dataView.byteLength;_++)d.setInt8(m++,o[p].dataView.getInt8(_));for(let p=0;p<i.data.byteLength;p++)d.setInt8(m++,l.getInt8(p));return i.data=c,o.length}return 0}destroy(){}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}decode(i,e){try{if(i.type==="empty"||i.data.byteLength===0)return i;let t=new DataView(i.data);if(!this.hasSEI(t))return i;let s=[],n=0,o=-1,a=-1;for(let c=0;c<i.data.byteLength;c++){let d=t.getUint8(c);if(d===0)n++;else if(d===1){if(n===2||n===3){let l=c-n;if(o===-1?o=l:a===-1&&(a=l,s.push(new ji(new DataView(t.buffer.slice(o,a)))),o=l,a=-1),!(t.getUint8(c+1)===6)){i.data=t.buffer.slice(l);break}}n=0}else n=0}this.log.debug(`${s.length} sei received`),s.reverse().forEach(c=>{this.core.trtc.emit(H.SEI_MESSAGE,{seiPayloadType:c.seiPayloadType,data:c.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}catch(t){this.log.warn(t)}return i}start(i){this.core.room.videoManager.enableSEI((e,t)=>{try{let s=this.encode(e,t);s&&this.log.debug(`${s} sei sent`)}catch(s){this.log.warn(s)}return e},(e,t)=>this.decode(e,t))}stop(i){this.core.room.videoManager.disableSEI()}update(i){(i.options.toSubStream?this._subStreamSeiMessageList:this._seiMessageList).push([i.options.seiPayloadType,i.buffer])}getName(){return hd.Name}getAlias(){return"sei"}getGroup(){return"sei"}},Ys=hd;u(Ys,"Name","SEI");var kl=0,jo=new Set,Le=null;da(vl);var ff={RtcError:L,ErrorCode:P,ErrorCodeDictionary:Ft},Br=class extends Ll.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",S.createLogger({id:`t${++kl}`}));u(this,"_plugins",new Map);u(this,"_networkQuality",null);u(this,"_speakerId");this._room=new e(v({logger:this._log,frameWorkType:Br.frameWorkType},t)),this._log.debug(JSON.stringify(t)),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(Oi,t.assetsPath),this._use(Ki,t.assetsPath),t.enableSEI&&_t&&(this._use(Ys),this.startPlugin("SEI")),this._room.on("audio-volume",s=>{!s.find(n=>n.userId==="")&&this._localAudioTrack&&s.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),this.emit(H.AUDIO_VOLUME,{result:s.sort((n,o)=>o.volume-n.volume)})}),this._room.videoManager.on("error",({reason:s,error:n})=>{this._log.error(new L({code:P.OPERATION_FAILED,extraCode:5504,messageParams:{reason:s,error:n}}))}),this._listenEvents(),this._initActiveSpeaker(),bl(this,"trtc")}static create(e){}static _create(e,t){_l();let s=new Br(e,t||{});return jo.add(s),s}get room(){return this._room}_listenEvents(){De(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(H.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit(H.REMOTE_USER_EXIT,{userId:e})}).add("banned",e=>{this._exitRoom().then(()=>{this.emit(H.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().then(()=>{this.emit(H.ERROR,L.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(H.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e,this.emit(H.NETWORK_QUALITY,e)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(s=>{De(s,s).add("player-state-changed",n=>{let o=w(v({},n),{userId:e.userId});s.kind===h.VIDEO&&(o.streamType=Uo(s.streamType)),this.emit(s.kind===h.AUDIO?H.AUDIO_PLAY_STATE_CHANGED:H.VIDEO_PLAY_STATE_CHANGED,o)}).add("error",n=>{n.getCode()===A.PLAY_NOT_ALLOWED&&this.emit(H.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,n=e.audioAvailable,o=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"}`),n!==a&&(this.emit(a?H.REMOTE_AUDIO_AVAILABLE:H.REMOTE_AUDIO_UNAVAILABLE,{userId:s}),a?this._onAudioAvailable({userId:s}):this._onAudioUnavailable({userId:s,muteState:t})),o!==c&&(this.emit(c?H.REMOTE_VIDEO_AVAILABLE:H.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?H.REMOTE_VIDEO_AVAILABLE:H.REMOTE_VIDEO_UNAVAILABLE,{userId:s,streamType:"sub"}),t.hasAuxiliary?this._onVideoAvailable({userId:s,streamType:"sub"}):this._onVideoUnavailable({userId:s,streamType:"sub"}))}).add("firewall-restriction",()=>{this.emit(H.ERROR,new L({code:P.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var n,o,a,c,d,l,m;let t={2:"big",3:"small",7:"sub"},s={rtt:e.msg_up_stream_info.msg_network_status.uint32_rtt||((n=e.msg_down_stream_info[0])==null?void 0:n.msg_network_status.uint32_rtt)||((o=this._networkQuality)==null?void 0:o.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:(((m=e.msg_up_stream_info.msg_audio_status)==null?void 0:m.uint32_audio_level)||0)/ct},video:e.msg_up_stream_info.msg_video_status.filter(p=>t[p.uint32_video_stream_type]).map(p=>({bitrate:(p.uint32_video_codec_bitrate||0)/1e3,width:p.uint32_video_width,height:p.uint32_video_height,frameRate:p.uint32_video_enc_fps,videoType:t[p.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(p=>({userId:p.msg_user_info.str_identifier,audio:{bitrate:(p.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(p.msg_audio_status.uint32_audio_level||0)/ct},video:p.msg_video_status.map(_=>({bitrate:(_.uint32_video_codec_bitrate||0)/1e3,width:_.uint32_video_width,height:_.uint32_video_height,frameRate:_.uint32_video_dec_fps,videoType:t[_.uint32_video_stream_type]}))}))};this.emit(H.STATISTICS,s)}).add("custom-message",e=>{this.emit(H.CUSTOM_MESSAGE,e)}),De(this,ge).add("audioInputAdded",e=>{this.emit(H.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(H.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(H.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(H.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>f(this,null,function*(){if(this.emit(H.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Le&&Le.deviceId===rs){let t=(yield Wi()).find(s=>s.deviceId===rs);t&&Le.groupId!==t.groupId&&(Le=t,this.emit(H.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>f(this,null,function*(){this.emit(H.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield Wi())[0];t&&Le&&(Le.deviceId===e.deviceId||Le.deviceId===rs&&Le.groupId!==t.groupId)&&(Le=t,this.emit(H.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 n=new e(yl.call(this,{TRTC:Br,room:this._room,errorModule:ff,assetsPath:t}));this._plugins.set(e.Name,n),Object.values(rd).includes(n.getName())&&(this.startPlugin(n.getName()),this._log.info("auto start plugin",e.Name))}enterRoom(e){return f(this,null,function*(){var c,d;let{scene:t="rtc",enableAutoPlayDialog:s=!0,autoReceiveAudio:n=!0,autoReceiveVideo:o=!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=n,this._room.autoReceiveVideo=o,pe(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,Br.frameWorkType),this._checkTrackToPublish(),ud.start()})}exitRoom(){return f(this,null,function*(){return yield this._exitRoom()})}switchRole(e,t){return f(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),t!=null&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){me(this),this.removeAllListeners(),this._room.destroy(),jo.delete(this),jo.size===0&&ud.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>{var t;return(t=e.destroy)==null?void 0:t.call(e)})}startLocalAudio(){return f(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,mute:s,option:n}=e,o=new Oe(this._room.audioManager),a={},c={muted:!0};n&&(g(n.microphoneId)?g(n.audioTrack)||(a.customSource=n.audioTrack):a.deviceId=n.microphoneId,n&&ee(n.captureVolume)&&o.setCaptureVolume(n.captureVolume),g(n.profile)||(Y(n.profile)?gn[n.profile]&&o.setProfile(gn[n.profile]):o.setProfile(n.profile)),ee(n.earMonitorVolume)&&(c.muted=!(n.earMonitorVolume>0),c.volume=n.earMonitorVolume),g(n.echoCancellation)||(o.profile.echoCancellation=n.echoCancellation),g(n.noiseSuppression)||(o.profile.noiseSuppression=n.noiseSuppression),g(n.autoGainControl)||(o.profile.autoGainControl=n.autoGainControl)),o.on("5",d=>{this.emit(H.ERROR,new L({code:P.DEVICE_ERROR,extraCode:5309,messageParams:{error:d}}))}),o.on("2",d=>{this.emit(H.DEVICE_CHANGED,{type:"microphone",action:"active",device:d})}),o.on("4",d=>{let l;d.error&&(l=L.convertFrom(d.error)),this.emit(H.PUBLISH_STATE_CHANGED,w(v({},d),{error:l}))}),this._listenOutputTrackChanged(o),this._speakerId&&o.setAudioOutput(this._speakerId),yield o.capture(a),g(s)||o.setMute(s),De(o,o).add("player-state-changed",d=>{this.emit(H.AUDIO_PLAY_STATE_CHANGED,w(v({},d),{userId:""}))}),t&&this._room.isJoined&&this._room.publish(o).catch(()=>{}),this._localAudioTrack=o,this._localAudioConfig=w(v({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:o})})}updateLocalAudio(e){return f(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:s,option:n}=e,o={};n&&(n.microphoneId?yield this._localAudioTrack.switchDevice(n.microphoneId):g(n.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(n.audioTrack)),g(n.captureVolume)||this._localAudioTrack.setCaptureVolume(n.captureVolume),g(n.earMonitorVolume)||(o.muted=!(n.earMonitorVolume>0),o.volume=n.earMonitorVolume),yield this._localAudioTrack.update3A(n)),this._room.isJoined&&!g(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),g(s)||this._localAudioTrack.setMute(s),yield this._updateAudioPlayOption({playOption:o,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Yt(this._localAudioConfig,e)})}stopLocalAudio(){return f(this,null,function*(){!this._localAudioTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),me(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return f(this,arguments,function*(e={publish:!0,view:null}){if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:t,publish:s=!0,mute:n,option:o}=e,a=new le(this._room.videoManager),c={},d={};if(o&&(o.cameraId?c.deviceId=o.cameraId:g(o.useFrontCamera)?g(o.videoTrack)||(c.customSource=o.videoTrack):c.facingMode=o.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT,g(o.profile)||(Y(o.profile)?Ke[o.profile]&&a.setProfile(Ke[o.profile]):a.setProfile(o.profile)),g(o.fillMode)||(d.objectFit=o.fillMode),g(o.mirror)||(d.mirror=o.mirror),g(o.small)||(Os()?Y(o.small)?a.small=Ke[o.small]:o.small===!0?a.small=Ke["120p"]:a.small=o.small:this._log.warn("small stream is not supported"))),a.on("5",l=>{this.emit(H.ERROR,new L({code:P.DEVICE_ERROR,extraCode:5308,messageParams:{error:l}}))}),a.on("2",l=>{this.emit(H.DEVICE_CHANGED,{type:"camera",action:"active",device:l})}),a.on("4",l=>{let m;l.error&&(m=L.convertFrom(l.error)),this.emit(H.PUBLISH_STATE_CHANGED,w(v({},l),{error:m}))}),this._listenOutputTrackChanged(a),yield a.capture(c),g(n)||(yield a.setMute(n)),a.mediaTrack)if(o!=null&&o.qosPreference){let l=Yi(o.qosPreference);a.mediaTrack.contentHint=l}else o!=null&&o.videoTrack||(a.mediaTrack.contentHint=Yi(st.QOS_PREFERENCE_SMOOTH));De(a,a).add("player-state-changed",l=>{this.emit(H.VIDEO_PLAY_STATE_CHANGED,w(v({},l),{userId:"",streamType:"main"}))}),s&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localVideoTrack=a,this._localVideoConfig=w(v({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:a})})}updateLocalVideo(e){return f(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:s,mute:n,option:o}=e,a={};if(o){if(g(o.profile)||(Y(o.profile)?Ke[o.profile]&&this._localVideoTrack.setProfile(Ke[o.profile]):this._localVideoTrack.setProfile(o.profile),(!o.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(o.cameraId))&&g(o.useFrontCamera)&&this._localVideoTrack.applyProfile()),o.cameraId?yield this._localVideoTrack.switchDevice(o.cameraId):g(o.useFrontCamera)?g(o.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(o.videoTrack)):yield this._localVideoTrack.switchDevice(o.useFrontCamera?h.FACING_MODE_USER:h.FACING_MODE_ENVIRONMENT),g(o.fillMode)||(a.objectFit=o.fillMode),g(o.mirror)||(a.mirror=o.mirror),o.qosPreference&&this._localVideoTrack.mediaTrack){let c=Yi(o.qosPreference);this._localVideoTrack.mediaTrack.contentHint=c}if(o.small){let c=!this._localVideoTrack.small;Os()?(o.small===!0?this._localVideoTrack.small=Ke["120p"]:Y(o.small)?this._localVideoTrack.small=Ke[o.small]:this._localVideoTrack.small=o.small,this._room.videoManager.update(),c&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else o.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1))}this._room.isJoined&&!g(s)&&(s&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!s&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),g(n)||(yield this._localVideoTrack.setMute(n)),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Yt(this._localVideoConfig,e)})}stopLocalVideo(){return f(this,null,function*(){!this._localVideoTrack||(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),me(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return f(this,arguments,function*(e={publish:!0,view:null}){if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:t=null,publish:s=!0,option:n}=e,o=new Xe(this._room.videoManager);o.on("4",m=>{let p;m.error&&(p=L.convertFrom(m.error)),this.emit(H.PUBLISH_STATE_CHANGED,w(v({},m),{error:p}))}),this._listenOutputTrackChanged(o);let a=null,c={},d={};n&&(g(n.profile)||(Y(n.profile)?Tn[n.profile]&&o.setProfile(Tn[n.profile]):o.setProfile(n.profile)),n.systemAudio&&(c.systemAudio=!0,c.echoCancellation=n.echoCancellation,c.noiseSuppression=n.noiseSuppression,c.autoGainControl=n.autoGainControl),g(n.fillMode)||(d.objectFit=n.fillMode),n.videoTrack&&(c.videoTrack=n.videoTrack),n.audioTrack&&(c.audioTrack=n.audioTrack),n.captureElement&&(c.captureElement=n.captureElement),n.preferDisplaySurface&&(c.preferDisplaySurface=n.preferDisplaySurface));let l=yield o.capture(c);if(n!=null&&n.qosPreference){let m=Yi(n.qosPreference);o.mediaTrack.contentHint=m}else n!=null&&n.videoTrack||(o.mediaTrack.contentHint=Yi(st.QOS_PREFERENCE_CLEAR));if(o.mediaTrack.addEventListener(h.ENDED,()=>{this._stopScreenShare(),this.emit(H.SCREEN_SHARE_STOPPED)}),l.getAudioTracks()[0]&&(a=new $t(this._room.audioManager),a.setInputMediaStreamTrack(l.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),De(o,o).add("player-state-changed",m=>{this.emit(H.VIDEO_PLAY_STATE_CHANGED,w(v({},m),{userId:"",streamType:"sub"}))}),s&&this._room.isJoined){let m=[o];a&&m.push(a),this._room.publish(...m).catch(()=>{})}this._localScreenTrack=o,this._localScreenAudioTrack=a,this._localScreenConfig=w(v({},e),{view:t,publish:s}),yield this._updateVideoPlayOption({view:t,playOption:d,track:o})})}updateScreenShare(e){return f(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:s,option:n}=e,o={};if(n&&(g(n.fillMode)||(o.objectFit=n.fillMode),n.qosPreference)){let a=Yi(n.qosPreference);this._localScreenTrack.mediaTrack.contentHint=a}this._room.isJoined&&!g(s)&&(s&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!s&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:t,playOption:o,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),Yt(this._localScreenConfig,e)})}stopScreenShare(){return f(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return f(this,null,function*(){let{view:t,userId:s,streamType:n,option:o}=e,a=`${s}_${n}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${s}, streamType:${n}`);return}let c=this._room.remotePublishedUserMap.get(s);if(!c)return;let d={},l=n==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;this._listenOutputTrackChanged(l),o&&(g(o.fillMode)||(d.objectFit=o.fillMode),g(o.mirror)||(d.mirror=o.mirror),d.canvasRender=o.canvasRender,n==="main"&&!g(o.small)&&(c.remoteVideoTrack.setMediaType(o.small?8:4),this._room.changeType(o.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}),o&&!g(o.receiveWhenViewVisible)&&this._observeView({remoteTrack:l,view:t,receiveWhenViewVisible:o.receiveWhenViewVisible,viewRoot:o==null?void 0:o.viewRoot})})}updateRemoteVideo(e){return f(this,null,function*(){var N,U;let{view:t,userId:s,streamType:n,option:o}=e,a=`${s}_${n}`,c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(s))return;let d={};o&&(g(o.fillMode)||(d.objectFit=o.fillMode),g(o.mirror)||(d.mirror=o.mirror));let l=null,m=this._room.remotePublishedUserMap.get(s);if(n==="main"&&(m==null?void 0:m.muteState.hasVideo)&&(l=m.remoteVideoTrack),n==="sub"&&(m==null?void 0:m.muteState.hasAuxiliary)&&(l=m.remoteAuxiliaryTrack),!l)return;let{config:p}=c;n==="main"&&o&&!g(o.small)&&this._room.changeType(o.small,l.user),yield this._updateVideoPlayOption({view:t,playOption:d,track:l,prevConfig:p}),Yt(p,e);let _=g(o==null?void 0:o.receiveWhenViewVisible)?(N=p.option)==null?void 0:N.receiveWhenViewVisible:o.receiveWhenViewVisible,R=g(t)?p.view:t,C=g(o==null?void 0:o.viewRoot)?(U=p.option)==null?void 0:U.viewRoot:o.viewRoot;this._observeView({remoteTrack:l,view:R,receiveWhenViewVisible:_,viewRoot:C})})}stopRemoteVideo(e){return f(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return f(this,null,function*(){let s=[],n=this._room.remotePublishedUserMap.get(e.userId);if(n){let{muteState:a,remoteVideoTrack:c,remoteAuxiliaryTrack:d}=n;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 o=this._remoteVideoConfigMap.get(`${e.userId}_${e.streamType}`);o&&o.observer&&o.observer.disconnect(),this._remoteVideoConfigMap.delete(`${e.userId}_${e.streamType}`)})}muteRemoteAudio(e,t){return f(this,null,function*(){if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let s=[...this._room.remotePublishedUserMap.values()];for(let n of s)n.muteState.hasAudio&&!this._remoteAudioConfigMap.has(n.userId)&&(yield this._startRemoteAudio({userId:n.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 n of s)this._updateAudioPlayOption({playOption:{volume:t},track:n.remoteAudioTrack})}else if(e){let s=this._room.remotePublishedUserMap.get(e);s&&this._updateAudioPlayOption({playOption:{volume:t},track:s.remoteAudioTrack})}}startPlugin(e,t){return f(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return f(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return f(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,s){return this.listeners(e).includes(t)?this:(this._log.debug("on",e),super.on(e,t,s),this._eventListened.add(e),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 n,o;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"?((n=this._localScreenAudioTrack)==null?void 0:n.mediaTrack)||null:((o=this._localAudioTrack)==null?void 0:o.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 n=this._room.remotePublishedUserMap.get(t);if(n)return s==="main"?n.remoteVideoTrack.mediaTrack:n.remoteAuxiliaryTrack.mediaTrack}return null}getVideoSnapshot(e={}){let{userId:t,streamType:s="main"}=e;if(t){let n=this._room.remotePublishedUserMap.get(t);if(s==="main"&&(n==null?void 0:n.muteState.hasVideo))return n.remoteVideoTrack.getVideoFrame();if(s==="sub"&&(n==null?void 0:n.muteState.hasAuxiliary))return n.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(n=>n.remoteAudioTrack.setAudioOutput(e))}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return f(this,null,function*(){let{userId:t,option:s}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let n=this._room.remotePublishedUserMap.get(t);if(!n)return;let o={};s&&(g(s.volume)||(o.volume=s.volume));let a=n.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:o,track:a})}catch(c){throw this._remoteAudioConfigMap.delete(t),c}this._emitTrackEvent(a)})}_stopRemoteAudio(e,t=!0){return f(this,null,function*(){let s=this._room.remotePublishedUserMap.get(e.userId);s&&(s.remoteAudioTrack.stop(),s.muteState.hasAudio&&t&&(yield this._room.unsubscribe(s.remoteAudioTrack)),this._mediaTrackMap.get(s.remoteAudioTrack.outMediaTrack)===e.userId&&this._mediaTrackMap.delete(s.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`)})}_updateVideoPlayOption(o){return f(this,arguments,function*({view:e,playOption:t,track:s,prevConfig:n}){if(s.setMirror(t.mirror),g(e)&&n&&n.view&&!Ba(t)){let a=ys(n.view);a.length>0&&(yield s.play(a,t))}if(!g(e)){let a=ys(e);a.length>0?yield s.play(a,t):s.stop()}})}_updateAudioPlayOption(n){return f(this,arguments,function*({playOption:e={},track:t,prevConfig:s}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(o){}g(e.muted)||t.setPlayerMute(e.muted),g(e.volume)||t.setAudioVolume(e.volume/100)})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,t=!0){let s=e.isRemote?e.userId:"";!e.outMediaTrack||t&&this._mediaTrackMap.get(e.outMediaTrack)===s||(this._mediaTrackMap.set(e.outMediaTrack,s),this.emit(H.TRACK,{userId:s,streamType:Uo(e.streamType),track:e.outMediaTrack}))}_checkTrackToPublish(){var t,s,n;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),(n=this._localScreenConfig)!=null&&n.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:n}){if(g(t))return;let o=this._remoteVideoConfigMap.get(`${e.userId}_${Uo(e.streamType)}`);if(!o)return;let a=o.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=o.visibleViewMap||new Map,l=-1;(!a||a.root!==n)&&(a==null||a.disconnect(),d.clear(),a=new IntersectionObserver(p=>{p.forEach(_=>{d.set(_.target,_.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:n}));let m=new Set(ys(t));d.forEach((p,_)=>{m.has(_)||(a.unobserve(_),d.delete(_))}),m.forEach(p=>{d.set(p,!0),a.observe(p)}),a.takeRecords().forEach(p=>{d.set(p.target,p.isIntersecting)}),o.visibleViewMap=d,o.observer=a}_exitRoom(){return f(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch()}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let t=e.includes("main")?"main":"sub",s=e.split(`_${t}`)[0];s&&this._stopRemoteVideo({userId:s,streamType:t}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._room.remotePublishedUserMap.forEach(e=>{me(e.remoteAudioTrack),me(e.remoteVideoTrack),me(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return f(this,null,function*(){var e;if(!!this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...t).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),me(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_initActiveSpeaker(){return f(this,null,function*(){if(Le&&!Nr(Le))this.emit(H.DEVICE_CHANGED,{type:"speaker",action:"active",device:Le});else{let e=yield Wi();if(e[0]&&!Nr(e[0]))Le=e[0],this.emit(H.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]});else{let t=({track:s})=>{s.kind==="audio"&&(!Le||Nr(Le))&&(this._initActiveSpeaker(),T.off("102",this._initActiveSpeaker))};T.on("102",t)}}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let s=this._room.remotePublishedUserMap.get(e);if(s){let n=t==="main"?s.remoteVideoTrack:s.remoteAuxiliaryTrack;this._room.subscribe(n).then(()=>{this._emitTrackEvent(n)}).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){let s=this._plugins.get("SEI");s&&(s.update({buffer:e,options:t||{seiPayloadType:243}}),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){S.setLogLevel(e),g(t)||(t?S.enableUploadLog():S.disableUploadLog())}static isSupported(){return Kn()}static getCameraList(e=!0){return je(e)}static getMicrophoneList(e=!0){return Ue(e)}static getSpeakerList(e=!0){return Wi(e)}static setCurrentSpeaker(e){return f(this,null,function*(){(yield Wi()).forEach(s=>{s.deviceId===e&&(jo.forEach(n=>{n.setCurrentSpeaker(e),n.emit(H.DEVICE_CHANGED,{type:"speaker",action:"active",device:s})}),Le=s)})})}static _addKVStat({type:e,key:t,value:s,base:n,useUV:o,version:a}){switch(a&&($i.version=a),e){case"count":$i.addCount({key:t,useUV:o});break;case"enum":$i.addEnum({key:t,value:s,useUV:o});break;case"number":$i.addNumber({key:t,value:s,split:n});break}}},Q=Br;u(Q,"_loggerManager",S),u(Q,"EVENT",H),u(Q,"ERROR_CODE",P),u(Q,"TYPE",st),u(Q,"frameWorkType",30),y([ne({replaceArg:r=>({argIndex:0,value:{name:"plugin"in r?r.plugin.Name:r.Name,assetsPath:"assetsPath"in r?r==null?void 0:r.assetsPath:"default"}})})],Q.prototype,"use",1),y([ke(Ce.TRTC.enterRoom),vi("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)}),ne()],Q.prototype,"enterRoom",1),y([ne()],Q.prototype,"exitRoom",1),y([ke(Ce.TRTC.switchRole),zi("room",{merge:(r,i)=>i}),ne()],Q.prototype,"switchRole",1),y([ne()],Q.prototype,"destroy",1),y([ke(Ce.TRTC.startLocalAudio),vi("audio",([r],[i])=>{var e,t;return((e=r==null?void 0:r.option)==null?void 0:e.microphoneId)===((t=i==null?void 0:i.option)==null?void 0:t.microphoneId)}),ne()],Q.prototype,"startLocalAudio",1),y([ke(Ce.TRTC.updateLocalAudio),zi("audio",{debounce:{delay:200,getKey:()=>`${kl}-localAudio`,isNeedToDebounce:r=>{var i;return!g((i=r.option)==null?void 0:i.captureVolume)}}}),ne()],Q.prototype,"updateLocalAudio",1),y([Di("audio"),ne()],Q.prototype,"stopLocalAudio",1),y([ke(Ce.TRTC.startLocalVideo),vi("video",([r],[i])=>{var e,t;return((e=r==null?void 0:r.option)==null?void 0:e.cameraId)===((t=i==null?void 0:i.option)==null?void 0:t.cameraId)}),ne()],Q.prototype,"startLocalVideo",1),y([ke(Ce.TRTC.updateLocalVideo),zi("video"),ne()],Q.prototype,"updateLocalVideo",1),y([Di("video"),ne()],Q.prototype,"stopLocalVideo",1),y([ke(Ce.TRTC.startScreenShare),vi("screen",()=>!0),ne()],Q.prototype,"startScreenShare",1),y([ke(Ce.TRTC.updateScreenShare),zi("screen"),ne()],Q.prototype,"updateScreenShare",1),y([ne()],Q.prototype,"stopScreenShare",1),y([ke(Ce.TRTC.startRemoteVideo),vi(r=>`v${r.userId}${r.streamType}`,()=>!0),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],Q.prototype,"startRemoteVideo",1),y([ke(Ce.TRTC.updateRemoteVideo),zi(r=>`v${r.userId}${r.streamType}`),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],Q.prototype,"updateRemoteVideo",1),y([ke(Ce.TRTC.stopRemoteVideo),W(r=>function(i){return f(this,null,function*(){if(i.userId==="*"){let e=[];return this._room.remotePublishedUserMap.forEach(t=>{this._remoteVideoConfigMap.has(`${t.userId}_${"main"}`)&&e.push(this.stopRemoteVideo({streamType:"main",userId:t.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${t.userId}_${"sub"}`)&&e.push(this.stopRemoteVideo({streamType:"sub",userId:t.userId}).catch(()=>{}))}),Promise.all(e)}return r.call(this,i)})}),ne({getRemoteId:r=>`${r.userId}_${r.streamType}`})],Q.prototype,"stopRemoteVideo",1),y([Di(r=>`v${r.userId}${r.streamType}`)],Q.prototype,"_stopRemoteVideo",1),y([ke(...Ce.TRTC.muteRemoteAudio),ne({getRemoteId:r=>r})],Q.prototype,"muteRemoteAudio",1),y([od(...Ce.TRTC.setRemoteAudioVolume),Nl(200,r=>r),ne({getRemoteId:r=>r})],Q.prototype,"setRemoteAudioVolume",1),y([Go("start"),yi(r=>{var i;return(i=r.afterStart)==null?void 0:i.call(r)}),vi((r,i)=>r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>tc[r.getName()]})],Q.prototype,"startPlugin",1),y([Go("update"),zi((r,i)=>r.getAlias()+r.getGroup(i)),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>ic[r.getName()]})],Q.prototype,"updatePlugin",1),y([Go("stop"),Di((r,i)=>{let e=r.getGroup(i),t=r.getAlias();return e==="*"?new RegExp(`${t}.*`):t+e}),ne({replaceArg:r=>({argIndex:0,value:r.getName()}),getKVReportKey:r=>rc[r.getName()]})],Q.prototype,"stopPlugin",1),y([od(...Ce.TRTC.enableAudioVolumeEvaluation)],Q.prototype,"enableAudioVolumeEvaluation",1),y([ne()],Q.prototype,"getVideoSnapshot",1),y([ne()],Q.prototype,"setCurrentSpeaker",1),y([vi(r=>`a${r.userId}`,()=>!0)],Q.prototype,"_startRemoteAudio",1),y([W(r=>function(i){return f(this,null,function*(){return i.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(e=>this._stopRemoteAudio(w(v({},i),{userId:e.userId})).catch(()=>{}))):r.call(this,i)})}),Di(r=>`a${r.userId}`)],Q.prototype,"_stopRemoteAudio",1),y([Di("room")],Q.prototype,"_exitRoom",1),y([Di("screen")],Q.prototype,"_stopScreenShare",1),y([ke(...Ce.TRTC.sendSEIMessage),id({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...r)=>r[0].byteLength})],Q.prototype,"sendSEIMessage",1),y([ke(Ce.TRTC.sendCustomMessage),id({timesInSecond:30,maxSizeInSecond:8e3,getSize:r=>r.data.byteLength})],Q.prototype,"sendCustomMessage",1),y([ke(Ce.TRTC.create)],Q,"_create",1);var Ks=Q;var md=class{constructor(){this._set=new Set;T.on(E.LEAVE_SUCCESS,this.delete,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,s){return`${t}_${e}_${i}_${s}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:s}){return s.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,s.useStringRoomId))}};function _f(){return f(this,null,function*(){let r,i;try{let m=yield Ue();r=m&&m.length}catch(m){}try{let m=yield je();i=m&&m.length}catch(m){}let e={microphone:r,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:s,isH264DecodeSupported:n,isVp8DecodeSupported:o}=this.checkSystemResult.detail,a=ii.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:t,h264Decode:n,vp8Encode:s,vp8Decode:o},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 xl(){return W(r=>{let i=new md;return function(e,t,s){return f(this,null,function*(){let n=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:k({key:M.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:n,sdkAppId:this.sdkAppId,room:this}))throw new b({code:A.INVALID_OPERATION,message:k({key:M.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:n}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${n} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),T.emit(E.JOIN_START,{room:this,roomId:n,params:e}),this.checkSystemResult=yield ii.checkSystemRequirementsInternal(),this.checkDestroy();let o=Pe.getEnv();o||(o=Jt.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Sn.OLD_CLOUD_LADDER)?o=Jt.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Sn.WEBRTC)&&(o=Jt.WEBRTC))),Z.setConfig({env:o,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:n}),_f.call(this);let{isH264EncodeSupported:a,isVp8EncodeSupported:c}=this.checkSystemResult.detail;if(!ii.isWebRTCSupported()||!a&&!c)throw new b({code:A.NOT_SUPPORTED,message:k({key:M.NOT_SUPPORTED_WEBRTC})});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Pe.getEnv()&&(yield this.schedule(e,s));let d=yield r.call(this,e,t,s);return this.roomId=n,this._joinedTimestamp=Pe.performanceNow(),T.emit(E.JOIN_SUCCESS,{room:this}),s===30&&!e.component&&Z.uploadEvent({log:`stat-conv-${Number(Xt)}-${location.hostname}`,userId:this.userId}),d}catch(d){throw i.delete({room:this,roomId:n}),T.emit(E.JOIN_FAILED,{room:this,error:d}),d}})}})}var Pl=()=>W(r=>function(...i){return f(this,null,function*(){T.emit(E.LEAVE_START,{room:this}),yield r.call(this),T.emit(E.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function wl(){return W(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var Ul=Se(Ne());var fe={SETUP_SUCCESS:"1",SETUP_FAILED:"5",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",DISCONNECTED:"5",RECONNECT_FAILED:"4"};var St={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},Vl=[St.UPDATE_REMOTE_MUTE_STAT,St.UPLINK_NETWORK_STATS,St.USER_LIST_RES,St.MUTE_RESULT,St.SERVER_FIRST_PACKAGE_RECEIVED,St.RECEIVE_CUSTOM_MSG],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 qo=new Set;function Bl(r){let i=[...qo.values()].find(e=>e.room.userId===r&&!e.room.isJoined);return i||null}var $r=class extends Ul.default{constructor(e){var s,n;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=g(e.race)?!0:e.race,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy,(((n=(s=this.room.scheduleResult)==null?void 0:s.config)==null?void 0:n.keepAliveClient)||0)-qo.size>0&&this.room.enableSPC&&(this.keepAlive=!0,qo.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=S.createLogger({id:"ws",userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;return this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`),this.race?`${e}&race=1`:e}get _urlWithParam(){return`${this.url}${this.race?"/v2/ws":""}${this.urlParam}`}get _backupUrlWithParam(){return`${this.backupUrl}${this.race?"/v2/ws":""}${this.urlParam}`}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get sdkAppId(){return this.room.sdkAppId}get userId(){return this.room.userId}get userSig(){return this.room.userSig}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return f(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}]${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connnectStartTime=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 Ss(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?h.BACKUP:h.MAIN),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:s}){let n=new WebSocket(e);this.bindSocket(n),s?this._socket=n:this._backupSocket=n;let o=-1;return new Promise((a,c)=>{n.onclose=c,n.onerror=c,n.onopen=()=>a(n),t&&(o=setTimeout(()=>{this.unbindAndCloseSocket(s?h.MAIN:h.BACKUP),c(new b({code:A.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{n.onclose=null,n.onerror=null,n.onopen=null,clearTimeout(o)})}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+=Jn(e.data);let t=JSON.parse(e.data),{cmd:s,data:n}=t,o=Object.values(St),c=Object.keys(St)[o.indexOf(s)],d=V[c]||s;switch(Vl.includes(s)||(this._log.debug(`received ${s} msg: ${e.data}`),d&&this._log.info(`Received event: [ ${d} ]`)),s){case St.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=n.clientIp,this._signalInfo.signalIp=n.signalInnerIp,n.svrTime&&Jd(n.svrTime),this._log.info("ChannelSetup Success"),D.addSuccessEvent({key:521701,cost:x()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(fe.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let l=new b({code:A.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:k({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(fe.SETUP_FAILED,l)}break}case St.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=n.relayOuterIp,this._signalInfo.relayInnerIp=n.relayInnerIp,this._signalInfo.relayPort=n.relayPort,this._signalInfo.tinyId=t.tinyId,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(d,{data:t});break}default:this.emit(String(d),{data:t});break}}reGetSignalChannelUrl(){return f(this,null,function*(){try{if(!this.room.joinParams)return;Ot(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}reconnect(){return f(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive){this.close();return}this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:s,relayInnerIp:n,relayPort:o}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:j.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:n,relayOuterIp:s,relayPort:o},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},n=JSON.stringify(s);return this._socketInUse.send(n),this.bytesSent+=Jn(n),s.seq}}sendWaitForResponse({command:e,data:t,timeout:s=5e3,responseCommand:n,commandDesc:o,enableLog:a=!0}){return new Promise((c,d)=>{let l=setTimeout(()=>{this.off(n,m);let _=new b({code:A.API_CALL_TIMEOUT,message:k({key:M.API_CALL_TIMEOUT,data:{commandDesc:o,command:e}})});a&&this._log.warn(_),d(_)},s),m=_=>{_.data.seq===p&&(clearTimeout(l),this.off(n,m),c(_))};this.on(n,m);let p=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:s,retries:n=0,retryTimeout:o=0}=e;return vt({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${s} when connected`),this.once(fe.CONNECTED,a))},onRetrying:a=>{this._log.warn(`${t||s} timeout observed, retrying [${a}/${n}]`)},settings:{retries:n,timeout:o},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),qo.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=n=>{n.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(fe.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(fe.CONNECTED):e==="DISCONNECTED"&&this.emit(fe.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())}})],$r.prototype,"connect",1);var $l=Se(Ne());var pd=0,fd=!1,Qo=new Set,gf=r=>pd>2&&!fd&&Qo.size===0&&r,_d=!1,ze=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 $l.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,"_enableSEI");u(this,"_sei");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=S.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel,this._enableSEI=i.enableSEI}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={encodedInsertableStreams:this._enableSEI&&_t,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(),this._sei&&(this._sei.destroy(),this._sei=null),Qo.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 ot;let i=null;if(this._isUplink){if(!Ri()||this._peerConnection.getSenders().length===0)return ot;i=this._peerConnection.getSenders()[0].transport}else{if(!Bi()||this._peerConnection.getReceivers().length===0)return ot;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:ot}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}`,n=new b({message:s,code:A.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",n)}(i.target.connectionState===se.CONNECTED||i.target.connectionState===se.COMPLETED)&&(this.logSelectedCandidate(),Z.logSuccessEvent({userId:this._room.userId,eventType:we.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(pd=0,fd=!1,_d=!0,Qo.add(this)):Qo.delete(this),T.emit(E.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:i,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:i}),this._currentState=i,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return f(this,null,function*(){if(!this._peerConnection)return;let i=yield this._peerConnection.getStats();for(let[,e]of i)if(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(o),n(),i())},s=({room:a})=>{a===this._room&&(clearTimeout(o),n(),e(new b({code:A.API_CALL_ABORTED,message:k({key:M.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{T.off(E.LEAVE_SUCCESS,s,this),this._emitter.off("connection-state-changed",t,this)},o=setTimeout(()=>{n();let a=new b({code:A.API_CALL_TIMEOUT,message:"connection timeout"});pd+=1,gf(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),fd=!0,this._emitter.emit("firewall-restriction")),e(a)},is);T.on(E.LEAVE_SUCCESS,s,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(fe.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=jt()){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:k({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(fe.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 Sd=Se(Td());var ce=function(r){return Sd.default.parse(r)},Ye=function(r){return Sd.default.write(r)},Xl=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"})}),Ye(i)};function Ql(r){let i=ce(r);return i.media.forEach(e=>{var t,s;if(e.type===h.VIDEO){let n=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&n.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let d=c.match(/apt=(\d+)/);d&&d[1]&&n.has(Number(d[1]))&&n.add(a)});let o=({payload:a})=>!n.has(a);e.rtp=e.rtp.filter(o),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(o),e.fmtp=e.fmtp.filter(o),e.payloads=(s=e.payloads)==null?void 0:s.split(" ").filter(a=>!n.has(Number(a))).join(" ")}}),Ye(i)}function zo(r){return Object.keys(r).filter(i=>r[i])}var Ad=class extends ze{constructor(e){super(w(v({},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 ni(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new gt(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Mr(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,n;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.onFlagChanged(),(n=this.remoteAuxiliaryTrack)==null||n.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 n,o;let t=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&t!==e&&((n=this.remoteVideoTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e}),(o=this.remoteAuxiliaryTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e})),s}onTrack(e){let t=e.streams[0],{track:s}=e,n=t.id===ts?h.MAIN:h.AUXILIARY;this._log.debug(`ontrack ${n} ${s.kind}`);let o=h.AUDIO;s.kind===h.VIDEO&&(o=n===h.MAIN?h.VIDEO:h.AUXILIARY);let a=this.remoteAudioTrack;o===h.VIDEO?a=this.remoteVideoTrack:o===h.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(s)}addRRTRLine(e){let t=e.split(`\r
|
|
`),s=new Map;t.forEach((o,a)=>{/^a=rtcp-fb:/.test(o)&&t[a+1]&&!/^a=rtcp-fb:/.test(t[a+1])&&s.set(a+1,`${o.match(/^a=rtcp-fb:\d+/)[0]} rrtr`)});let n=[...s];for(let o=0;o<n.length;o++){let[a,c]=n[o];t.splice(a+o,0,c)}return t.join(`\r
|
|
`)}addSPSDescription(e){let t=ce(e);return t.media.forEach(s=>{s.type===h.VIDEO&&s.fmtp.forEach(n=>{n.config+=";sps-pps-idr-in-keyframe=1"})}),Ye(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(n=>{!n.ext||(n.ext=n.ext.filter(o=>!t.includes(o.uri)))}),Ye(s)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return f(this,null,function*(){var s,n;try{if((((s=this._peerConnection)==null?void 0:s.connectionState)===se.NEW||((n=this._peerConnection)==null?void 0:n.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 o="subscribe_change";Object.values(e).find(a=>a===!0)||(o="unsubscribe"),yield this.sendSubscription(o,e)}else this.initialize(),yield this.connect(e)}catch(o){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${o.message} ${JSON.stringify(this.muteState)}`),new b({code:A.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):o}})}unsubscribe(s){return f(this,arguments,function*({remoteTracks:e,streamType:t}){if(this._currentState==="CONNECTED"&&(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed)){this._log.info(`${t} stream already unsubscribed`);return}let n=v({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:n.audio=!1;break;case 4:n.video=!1;break;case 8:n.smallVideo=!1;break;case 2:n.auxiliary=!1;break;default:break}});let o="subscribe_change";Object.values(n).find(a=>a===!0)||(o="unsubscribe"),this._log.info(`${o==="unsubscribe"?o:"subscribe"} ${t} [${zo(n)}]`),yield this.sendSubscription(o,n),o==="unsubscribe"&&(this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,t=this.subscribeState){let s={srcTinyId:this.tinyId,srcUserId:this.userId},n=j.UNSUBSCRIBE,o=V.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(s={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},n=j.SUBSCRIBE_CHANGE,o=V.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:n,data:s,responseCommand:o,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new b({code:a.code,message:k({key:M.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(c),c}})}connect(){return f(this,arguments,function*(e=this.subscribeState){try{yield this.exchangeSDP(e),yield this.waitForPeerConnectionConnected()}catch(t){throw this.closePeerConnection(!0),t}})}exchangeSDP(e){return f(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:s}=this._peerConnection.localDescription,n={type:t,sdp:s,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},o=yield this._signalChannel.sendWaitForResponse({command:j.SUBSCRIBE,commandDesc:"exchange sdp",data:n,responseCommand:V.SUBSCRIBE_RESULT,timeout:ga});if(!this._peerConnection){let a=new b({code:A.INVALID_OPERATION,message:k({key:M.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(o),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return f(this,null,function*(){let e={voiceActivityDetection:!1};tt()&&this._sdpSemantics===pi?(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 Yn();s||(this._log.warn("remove h264 desc from sdp"),t.sdp=Ql(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=Xl(t.sdp),this._sdpSemantics===pi&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this._peerConnection.setLocalDescription(t)})}onSubscribeResult(e){return f(this,null,function*(){let{code:t,message:s=""}=e&&e.data||{},{type:n,sdp:o}=e&&e.data&&e.data.data||{};if(t===xi)throw new b({code:A.NOT_SUPPORTED_H264,message:k({key:M.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new b({code:t,message:k({key:M.EXCHANGE_SDP_FAILED,data:{errMsg:s}})});this._log.debug(`accept remote answer: ${o}`),yield this._peerConnection.setRemoteDescription({type:n,sdp:o}),this._sei&&(this._sei.handleEncodedStreams(),this._sei.onSEIMessage=a=>{this._emitter.emit("sei-message",w(v({},a),{userId:this.userId}))}),this.updateSSRC(o)}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 n=s.ssrcs.find(o=>{var a;return(a=o.value)==null?void 0:a.includes(ts)});n&&(this.ssrc.audio=Number(n.id))}else{let n=s.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(ts)}),o=s.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(ma)});n&&(this.ssrc.video=Number(n.id)),o&&(this.ssrc.auxiliary=Number(o.id))}})}catch(t){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return f(this,null,function*(){if(!(Ie(Ad.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=Mt(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}},en=Ad;y([W(r=>function(...i){return new Promise((e,t)=>{let s=n=>{this._emitter.off("closed",s),t(new b({code:A.API_CALL_ABORTED,message:k({key:M.CONNECTION_ABORTED,data:n})}))};this._emitter.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this._emitter.off("closed",s)})})})],en.prototype,"subscribe",1),y([yi(ze.prototype.afterConnect),fo(ze.prototype.beforeConnect)],en.prototype,"connect",1);var Id=en;var Yl={voiceActivityDetection:!1},Cd=class extends ze{constructor(e){super(w(v({},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,n,o;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(kt()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((s=a[1])!=null&&s.track),e.smallVideo=!!((n=a[2])!=null&&n.track),e.auxVideo=!!((o=a[3])!=null&&o.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 o,a,c;let s=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):((o=this.localMainVideoTrack)==null||o.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}))),n}publish(n){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:s}){var a;this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),t&&(this._publishingLocalVideoTrack=t),this._isPublishingAux=s;let o;t&&!s&&t.small&&(o=this._room.videoManager.smallTrack),this.sendMediaSettings(),tt()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:o,isAuxiliary:s}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:o}),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)),(a=this._sei)==null||a.handleEncodedStreams(),this.installTrackMuteEvents(e,t),this.sendMutedFlag()})}publishByTransceiver(o){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:s,isAuxiliary:n}){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:q.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(n?h.VIDEO:c||h.VIDEO,{direction:q.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(s||h.VIDEO,{direction:q.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(n?c||h.VIDEO:h.VIDEO,{direction:q.SENDONLY,streams:[a]}),yield this.connect();else{let m=[];if(d&&(l[0].sender.track||m.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 p=n?3:1;yield l[p].sender.replaceTrack(c),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:h.VIDEO,videoType:n?h.AUXILIARY:h.BIG}),m.push(p),s&&(yield l[2].sender.replaceTrack(s),yield this.setBandwidth({bandwidth:t.small.bitrate,type:h.VIDEO,videoType:h.SMALL}),m.push(2))}yield this.setTransceiverDirection(q.SENDONLY,m),yield this.doPublishChange(),t==null||t.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),t==null||t.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}})}publishByAddTrack(n){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:s}){this._log.info("publish by addtrack");let o=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)),o&&(yield this.addTrack(t));return}let c=new MediaStream;if(a&&c.addTrack(a),o&&c.addTrack(o),a&&this._peerConnection.addTrack(a,c),o&&(this._peerConnection.addTrack(o,c),s)){let d=new MediaStream;d.addTrack(s),this._peerConnection.addTrack(s,d)}yield this.connect()})}enableSmall(e){return f(this,null,function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(q.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(q.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(s){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!kt()){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 n=t&&t===this.localAuxVideoTrack,o=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(yield a[0].replaceTrack(null),c.push(0),n?this.localAuxAudioTrack=null:this.localMainAudioTrack=null),o&&(n?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=w(v({},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=w(v({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(q.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return f(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},s=yield this._signalChannel.sendWaitForResponse({command: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:n,localAuxVideoTrack:o}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?o=this._publishingLocalVideoTrack:n=this._publishingLocalVideoTrack),Lt){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(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=n.profile.bitrate*1e3,n.small&&(this._mediaSettings.smallVideoWidth=n.small.width,this._mediaSettings.smallVideoHeight=n.small.height,this._mediaSettings.smallVideoFps=n.small.frameRate,this._mediaSettings.smallVideoBps=n.small.bitrate*1e3)}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=o.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),n&&n.outMediaTrack&&(this._mediaSettings.videoWidth=n.profile.width,this._mediaSettings.videoHeight=n.profile.height,this._mediaSettings.videoFps=n.profile.frameRate,this._mediaSettings.videoBps=n.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 f(this,null,function*(){var s;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`),(s=this._sei)==null||s.handleEncodedStreams(),tt()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return f(this,null,function*(){var n;if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(e.outMediaTrack);else{let o=t?3:1;yield s[o].sender.replaceTrack(e.outMediaTrack),o===1&&((n=this.localMainVideoTrack)==null?void 0:n.small)&&(yield s[2].sender.replaceTrack(this._room.videoManager.smallTrack)),s[o].direction===q.INACTIVE&&(yield this.setTransceiverDirection(q.SENDONLY,[o]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return f(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;kt()&&this._peerConnection.getTransceivers().findIndex(n=>n.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let s=this._peerConnection.getSenders().find(n=>n.track&&n.track.kind===t.kind);if(s&&s.track){this._log.warn("sender already exists, remove sender first");let n=s.track;this.removeSender(s),yield this.updateOffer("remove",n)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===h.VIDEO&&e instanceof le&&e.small){let n=new MediaStream,{smallTrack:o}=this._room.videoManager;n.addTrack(o),this._peerConnection.addTrack(o,n)}yield this.updateOffer("add",t)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===nr||!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;kt()&&(t=this._peerConnection.getTransceivers().find(s=>s.sender&&s.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&z(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?h.AUXILIARY:h.MAIN} stream`),tt()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return f(this,null,function*(){if(!e.outMediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(null);else{let n=t?3:1;yield s[n].sender.replaceTrack(null),n===1&&e.small&&(yield s[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(q.INACTIVE,[n])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return f(this,null,function*(){if(!te)return;let s=!1,n=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let o=this._peerConnection.getTransceivers();if(t.forEach(d=>{o[d].direction!==e&&(o[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
|
|
`).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 n=!0,`a=${e}`;if(e===q.SENDONLY&&d.includes(`a=${q.INACTIVE}`))return n=!0,`a=${q.RECVONLY}`}return d}).join(`\r
|
|
`);n&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:c}))})}removeTrackBySender(e){return f(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 f(this,null,function*(){var o;let t=(o=this._peerConnection)==null?void 0:o.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 n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${e.kind} track on ${n?h.AUXILIARY:h.MAIN} stream`),e.kind===h.AUDIO?yield s.replaceTrack(e.outMediaTrack):e.kind===h.VIDEO&&(n?t[3]&&(yield t[3].replaceTrack(e.outMediaTrack)):yield s.replaceTrack(e.outMediaTrack)),!0})}updateOffer(e,t){return f(this,null,function*(){try{let s=yield this._peerConnection.createOffer(Yl);te&&s.sdp&&(s.sdp=this.setSDPDirection(s.sdp,"sendrecv")),yield this._peerConnection.setLocalDescription(s);let n=this.updateMediaSettings(),o={action:e,trackId:t.id,kind:t.kind===h.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:n,state:this.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug(`updatedOffer: ${o.sdp}`);let a=yield this._signalChannel.sendWaitForResponse({command:j.PUBLISH_CHANGE,data:o,responseCommand:V.UPDATE_OFFER_RESULT,timeout:Ea,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(o){return f(this,arguments,function*({bandwidth:e,type:t,videoType:s,sdp:n}){if(!Ms())return n?t===h.VIDEO?this.updateVideoBandwidthRestriction(n,e,s):this.updateAudioBandwidthRestriction(n,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`),n}catch(l){if(this._log.info(`failed to set bandwidth by setting maxBitrate: ${l}`),n)return t===h.VIDEO?this.updateVideoBandwidthRestriction(n,e,s):this.updateAudioBandwidthRestriction(n,e)}}return n})}updateVideoBandwidthRestriction(e,t,s){let n="AS";te&&(n="TIAS",t=t*1e3);let o=0,a=-1;return s===h.SMALL?o=1:s===h.AUXILIARY&&(o=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,c=>(a+=1,a===o?`${c}b=${n}:${t}\r
|
|
`:c)),e}updateAudioBandwidthRestriction(e,t){let s="AS";return te&&(s="TIAS",t=t*1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,`m=audio $1\r
|
|
c=IN $2\r
|
|
b=${s}:${t}\r
|
|
`),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 f(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(e){throw this.closePeerConnection(!0),this.uninstallEvents(),e}})}exchangeSDP(){return f(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 f(this,null,function*(){try{let e=yield this._peerConnection.createOffer(Yl);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 Xe||this.localAuxVideoTrack instanceof Xe,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:n,data:o}=t.data;return s===0?this.acceptAnswer(o):this.checkPublishResultCode(s,n)})}setSDPDirection(e,t,s="all"){let n=ce(e);return n.media.forEach(o=>{(s==="all"||o.type===s)&&(o.direction=t)}),Ye(n)}acceptAnswer(e){return f(this,null,function*(){var t,s,n,o,a;try{let c;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let m=((t=this._publishingLocalVideoTrack)==null?void 0:t.profile.bitrate)||((s=this.localMainVideoTrack)==null?void 0:s.profile.bitrate),p=((n=this._publishingLocalAudioTrack)==null?void 0:n.profile.bitrate)||((o=this.localMainAudioTrack)==null?void 0:o.profile.bitrate);if(m){let _=this._isPublishingAux?h.AUXILIARY:h.BIG;c=yield this.setBandwidth({bandwidth:m,type:h.VIDEO,sdp:c,videoType:_})}p&&(c=yield this.setBandwidth({bandwidth:p,type:h.AUDIO,sdp:c}))}if(c=this.removeVideoOrientation(e.sdp),(a=this._publishingLocalVideoTrack)!=null&&a.small){let{smallStreamConfig:m}=this._room;c=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||m.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 n,o,a;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let s={audio:!!((n=this.localMainAudioTrack)!=null&&n.muted),bigVideo:!!((o=this.localMainVideoTrack)!=null&&o.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 f(this,null,function*(){if(!(Ie(Cd.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=Mt(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)&&T.emit(E.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{ce(e).media.forEach((s,n)=>{if(s.type===h.AUDIO){let o=s.ssrcs&&s.ssrcs[0];o&&(this.ssrc.audio=Number(o.id))}else{if(this._sdpSemantics===nr&&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 o=s.ssrcs&&s.ssrcs[0];if(!o)return;switch(n){case 1:this.ssrc.video=Number(o.id);break;case 2:this.ssrc.small=Number(o.id);break;case 3:this.ssrc.auxiliary=Number(o.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===xi?(this._log.error(Ae.NOT_SUPPORTED_H264ENCODE),new b({code:A.NOT_SUPPORTED_H264,message:k({key:M.NOT_SUPPORTED_H264ENCODE})})):new b({code:A.UNKNOWN,message:k({key:M.SIGNAL_RESPONSE_FAILED,data:{signalResponse:V.PUBLISH_RESULT,code:e,message:t}})})}sendSEI(e,t){var s;(s=this._sei)==null||s.push(e,t)}},tn=Cd;y([W(r=>function(...i){return new Promise((e,t)=>{let s=n=>{this._emitter.off("closed",s),t(new b({code:A.API_CALL_ABORTED,message:k({key:M.CONNECTION_ABORTED,data:n})}))};this._emitter.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this._emitter.off("closed",s)})})})],tn.prototype,"publish",1),y([yi(ze.prototype.afterConnect),fo(ze.prototype.beforeConnect)],tn.prototype,"connect",1);var rn=tn;var sn=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 f(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(o=>{var a,c,d;if(o.type==="outbound-rtp")if((o.mediaType||o.kind)===h.VIDEO){let m,p;if(o.ssrc===s.video?(m=h.VIDEO,p=i.localMainVideoTrack):o.ssrc===s.small?m=h.SMALL:o.ssrc===s.auxiliary&&(p=i.localAuxVideoTrack,m=h.AUXILIARY),!m)return;if(e[m].bytesSent=o.bytesSent,e[m].packetsSent=o.packetsSent,e[m].framesEncoded=o.framesEncoded,g(o.keyFramesEncoded)||(e[m].keyFramesEncoded=o.keyFramesEncoded),g(o.nackCount)||(e[m].nackCount=o.nackCount),g(o.pliCount)||(e[m].pliCount=o.pliCount),g(o.retransmittedPacketsSent)||(e[m].retransmittedPacketsSent=o.retransmittedPacketsSent),g(o.totalEncodeTime)||(e[m].totalEncodeTime=o.totalEncodeTime),g(o.totalPacketSendDelay)||(e[m].totalPacketSendDelay=o.totalPacketSendDelay),!g(o.encoderImplementation)&&(m===h.VIDEO&&this._prevEncoderImplementation!==o.encoderImplementation||m===h.AUXILIARY&&this._prevAuxEncoderImpl!==o.encoderImplementation)){let _=2,R=this._prevEncoderImplementation;m===h.AUXILIARY&&(_=7,R=this._prevAuxEncoderImpl),T.emit("262",{userId:i.userId,streamType:_,prevImplementation:R,implementation:o.encoderImplementation,codec:i.videoCodec,isHWCodec:o.powerEfficientEncoder}),this[m===h.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=o.encoderImplementation,this._log.info(`${m===h.AUXILIARY?"aux ":""}encoderImplementation change to ${o.encoderImplementation}(${i.videoCodec}) HWEncoder: ${o.powerEfficientEncoder}`)}if(o.ssrc===s.video?!g(o.qualityLimitationReason)&&o.bytesSent!==0&&this._prevQualityLimitationReason!==o.qualityLimitationReason&&(this._log.info(`qualityLimitationReason change to ${o.qualityLimitationReason}`),T.emit("263",{userId:i.userId,reason:o.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:(a=i.localMainVideoTrack)==null?void 0:a.isQosClearFirst}),this._prevQualityLimitationReason=o.qualityLimitationReason):o.ssrc===s.auxiliary&&!g(o.qualityLimitationReason)&&o.bytesSent!==0&&this._prevAuxQualityLimitationReason!==o.qualityLimitationReason&&(this._log.info(`aux qualityLimitationReason change to ${o.qualityLimitationReason}`),T.emit("263",{userId:i.userId,reason:o.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:(c=i.localAuxVideoTrack)==null?void 0:c.isQosClearFirst}),this._prevAuxQualityLimitationReason=o.qualityLimitationReason),p)for(let _ of Object.keys(p.stat))e[m][_]&&(p.stat[_]=e[m][_])}else e.audio.bytesSent=o.bytesSent,e.audio.packetsSent=o.packetsSent;else o.type==="candidate-pair"?Ci(o)&&ee(o.currentRoundTripTime)&&(e.rtt=Math.floor(o.currentRoundTripTime*1e3),this.totalBytesSent=o.bytesSent):o.type==="media-source"&&(o.kind===h.AUDIO?(e.audio.audioLevel=o.audioLevel||0,e.audio.totalAudioEnergy=o.totalAudioEnergy||0,o.echoReturnLoss,o.totalSamplesDuration&&(e.audio.totalSamplesDuration=o.totalSamplesDuration)):o.kind===h.VIDEO&&(o.trackIdentifier===i.getVideoTrackId(h.VIDEO)?e.video.fpsCapture=o.framesPerSecond:o.trackIdentifier===i.getVideoTrackId(h.AUXILIARY)?e.auxiliary.fpsCapture=o.framesPerSecond:e.small.fpsCapture=o.framesPerSecond));if(!g(o.audioLevel)&&((d=i.localMainAudioTrack)==null?void 0:d.mediaTrack)&&o.trackIdentifier===i.localMainAudioTrack.mediaTrack.id&&(e.audio.audioLevel=o.audioLevel||0),!g(o.frameWidth)){let l=h.SMALL;o.trackIdentifier===i.getVideoTrackId(h.VIDEO)||o.ssrc===s.video?l=h.VIDEO:(o.trackIdentifier===i.getVideoTrackId(h.AUXILIARY)||o.ssrc===s.auxiliary)&&(l=h.AUXILIARY),e[l].frameWidth=o.frameWidth,e[l].frameHeight=o.frameHeight,e[l].framesSent=o.framesSent}}),i.localMainAudioTrack){let o=i.localMainAudioTrack.getInternalAudioLevel();e.audio.micAudioLevel=o,e.audio.audioLevel===0&&(e.audio.audioLevel=o)}this.totalBytesSent||(this.totalBytesSent+=e.audio.bytesSent+e.video.bytesSent+e.auxiliary.bytesSent)}catch(n){this._log.warn(`failed to getStats on sender connection ${n}`)}return e})}getReceiverStats(i){return f(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:n,subscribeState:o}=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||!n.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(te&&c.bytesReceived===0)return;let l;c.ssrc===s.video&&n.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,n.hasSmall&&o.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}`),T.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&&n.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&&n.hasVideo?(e.video.totalJitter=c.jitterBufferDelay,e.video.totalJitterCount=c.jitterBufferEmittedCount):c.ssrc===s.auxiliary&&n.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);g(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)),!g(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 f(this,null,function*(){let t={},s=[];if(this.room.singlePC){let n=this.room.singlePC.getPeerConnection();if(!n)return{senderStats:t,receiverStats:s};let o=x(),a=yield n.getStats(),c=x();c-o>2e3&&this._log.warn(`getStats cost ${c-o}ms`);let d=[],l=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);a.forEach(m=>l.has(m.type)&&d.push(m)),this._spcStats=d}i&&(t=yield this.getSenderStats(i));for(let[n,o]of e){let a=yield this.getReceiverStats(o);s.push(a)}return{senderStats:t,receiverStats:s}})}getDifferenceValue(i,e){if(Ut(i))return e;let t=e-i;return t<0?0:t}prepareReport({stats:i,report:e,freezeMap:t}){var m;if(!Ut(i.senderStats)){let p={uint32_audio_level:i.senderStats.audio.audioLevel*ct,uint32_audio_energy:i.senderStats.audio.totalAudioEnergy*1e6,uint32_audio_codec_bitrate:i.senderStats.audio.bytesSent};i.senderStats.audio.micAudioLevel&&(p.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 _=[];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};_.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};_.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};_.push(C)}let R={uint32_bitrate:0,uint32_lost:0,uint32_rtt:i.senderStats.rtt};e.msg_up_stream_info={msg_audio_status:p,msg_video_status:_,msg_network_status:R}}let{statInterval:s}=this;e.msg_down_stream_info=[],i.receiverStats.forEach(p=>{let _={msg_user_info:{str_identifier:p.userId,uint64_tinyid:p.tinyId},msg_network_status:{uint32_rtt:p.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(p.hasAudio){let R={uint32_audio_p2p_delay:p.audio.p2pDelay,uint32_audio_cache_ms:p.audio.totalJitter,uint32_audio_cache_ms_count:p.audio.totalJitterCount,uint32_audio_codec_bitrate:p.audio.bytesReceived,uint32_audio_total_bitrate:p.audio.bytesReceived,uint32_audio_level:p.audio.audioLevel*1e8,uint32_audio_energy:p.audio.totalAudioEnergy*1e6,uint32_audio_receive:p.audio.packetsReceived,uint32_audio_origin_lost:p.audio.packetsLost};_.msg_audio_status=R}if(p.hasVideo){let R=t.get(`${p.userId}_${pa}`),C=R?R.duration:0,N={uint32_video_stream_type:p.isSmallSubscribed?3:2,uint32_video_receive_fps:p.video.framesReceived,uint32_video_width:p.video.frameWidth,uint32_video_height:p.video.frameHeight,uint32_video_codec_bitrate:p.video.bytesReceived,uint32_video_receive:p.video.packetsReceived,uint32_video_origin_lost:p.video.packetsLost,uint32_video_block_time:C,uint32_video_dec_fps:p.video.framesDecoded,uint32_video_cache_ms:p.video.totalJitter,uint32_video_cache_ms_count:p.video.totalJitterCount};_.msg_video_status.push(N)}if(p.hasAuxiliary){let R=t.get(`${p.userId}_${fa}`),C=R?R.duration:0,N={uint32_video_stream_type:7,uint32_video_receive_fps:p.auxiliary.framesReceived,uint32_video_width:p.auxiliary.frameWidth,uint32_video_height:p.auxiliary.frameHeight,uint32_video_codec_bitrate:p.auxiliary.bytesReceived,uint32_video_receive:p.auxiliary.packetsReceived+p.auxiliary.packetsLost,uint32_video_origin_lost:p.auxiliary.packetsLost,uint32_video_block_time:C,uint32_video_dec_fps:p.auxiliary.framesDecoded,uint32_video_cache_ms:p.auxiliary.totalJitter,uint32_video_cache_ms_count:p.auxiliary.totalJitterCount};_.msg_video_status.push(N)}e.msg_down_stream_info.push(_)});let n=this._prevReport,o=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&&n.msg_up_stream_info.msg_audio_status){let p=n.msg_up_stream_info.msg_audio_status,_=e.msg_up_stream_info.msg_audio_status;if(p.uint32_audio_codec_bitrate===0)_.uint32_audio_codec_bitrate=0;else{let R=this.getDifferenceValue(p.uint32_audio_codec_bitrate,_.uint32_audio_codec_bitrate);_.uint32_audio_codec_bitrate=Math.round(R*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=_.uint32_audio_codec_bitrate}(m=n.msg_device_info)!=null&&m.uint32_audio_capture_cost?e.msg_device_info.uint32_audio_capture_cost=2*Math.floor(this.getDifferenceValue(n.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=n.msg_up_stream_info.msg_video_status;e.msg_up_stream_info.msg_video_status.forEach(p=>{let _=a.find(Fe=>Fe.uint32_video_stream_type===p.uint32_video_stream_type);if(!_||_.uint32_video_codec_bitrate===0){p.uint32_video_codec_bitrate=0,p.uint32_video_enc_fps=0,p.uint32_video_codec_fps=0;return}let R=0,C=0,N=0;_&&p.uint32_video_codec_bitrate>=_.uint32_video_codec_bitrate&&(R=_.uint32_video_codec_bitrate,C=_.uint32_video_enc_fps,N=_.uint32_video_codec_fps);let U=this.getDifferenceValue(R,p.uint32_video_codec_bitrate);p.uint32_video_codec_bitrate=Math.round(U*8/s),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=p.uint32_video_codec_bitrate,p.uint32_video_enc_fps=Math.round(this.getDifferenceValue(C,p.uint32_video_enc_fps)/s),p.uint32_video_codec_fps=Math.round(this.getDifferenceValue(N,p.uint32_video_codec_fps)/s),Ei&&gi()===115&&_.uint32_video_width===0&&_.uint32_video_height===0&&_.uint32_video_codec_fps===0&&(p.uint32_video_codec_fps=p.uint32_video_enc_fps),g(_.uint32_key_frame_count)||(p.uint32_key_frame_count=Math.round(this.getDifferenceValue(_.uint32_key_frame_count,p.uint32_key_frame_count))),g(_.uint32_nack_count)||(p.uint32_nack_count=Math.round(this.getDifferenceValue(_.uint32_nack_count,p.uint32_nack_count))),g(_.uint32_pli_count)||(p.uint32_pli_count=Math.round(this.getDifferenceValue(_.uint32_pli_count,p.uint32_pli_count))),g(_.uint32_video_arq_packets)||(p.uint32_video_arq_packets=Math.round(this.getDifferenceValue(_.uint32_video_arq_packets,p.uint32_video_arq_packets))),g(_.uint32_encode_cost)||(p.uint32_encode_cost=Math.round(this.getDifferenceValue(_.uint32_encode_cost,p.uint32_encode_cost)/s)),g(_.uint32_send_packet_cost)||(p.uint32_send_packet_cost=Math.round(this.getDifferenceValue(_.uint32_send_packet_cost,p.uint32_send_packet_cost)/s))});let d=n.msg_down_stream_info;e.msg_down_stream_info=e.msg_down_stream_info.filter(p=>d.find(_=>_.msg_user_info.uint64_tinyid===p.msg_user_info.uint64_tinyid));let l=e.msg_down_stream_info;return l.forEach(p=>{let _=d.find(R=>R.msg_user_info.uint64_tinyid===p.msg_user_info.uint64_tinyid);if(!Ut(p.msg_audio_status)&&!Ut(_.msg_audio_status)){let R=p.msg_audio_status,C=_.msg_audio_status,N=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)/N)||0;let U=this.room.remotePublishedUserMap.get(p.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 Fe=this.getDifferenceValue(C.uint32_audio_codec_bitrate,R.uint32_audio_codec_bitrate);R.uint32_audio_codec_bitrate=Math.round(Fe*8/s),R.uint32_audio_total_bitrate=Math.round(Fe*8/s)}else p.msg_audio_status={};if(p.msg_video_status&&_.msg_video_status){let R=_.msg_video_status;p.msg_video_status=p.msg_video_status.filter(N=>R.find(U=>U.uint32_video_stream_type===N.uint32_video_stream_type)),p.msg_video_status.forEach(N=>{let U=R.find(vh=>vh.uint32_video_stream_type===N.uint32_video_stream_type),Fe=U.uint32_video_receive,hn=U.uint32_video_origin_lost,Ch=U.uint32_video_codec_bitrate,G=U.uint32_video_receive_fps,Rh=U.uint32_video_dec_fps;N.uint32_video_origin_lost=this.getDifferenceValue(hn,N.uint32_video_origin_lost),N.uint32_video_receive=this.getDifferenceValue(Fe,N.uint32_video_receive)+N.uint32_video_origin_lost;let yh=this.getDifferenceValue(Ch,N.uint32_video_codec_bitrate);N.uint32_video_codec_bitrate=Math.round(yh*8/s);let bh=this.getDifferenceValue(G,N.uint32_video_receive_fps);N.uint32_video_receive_fps=Math.round(bh/s),N.uint32_video_dec_fps=Math.round(this.getDifferenceValue(Rh,N.uint32_video_dec_fps)/s);let Nh=this.getDifferenceValue(U.uint32_video_cache_ms_count,N.uint32_video_cache_ms_count);delete N.uint32_video_cache_ms_count,N.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(U.uint32_video_cache_ms,N.uint32_video_cache_ms)/Nh)||0})}}),o&&i.receiverStats.forEach(p=>{if(p.audio.concealedSamples&&p.audio.totalSamplesReceived){let _=o.receiverStats.find(R=>R.userId===p.userId);if(_&&_.audio.concealedSamples&&_.audio.totalSamplesReceived){let R=p.audio.concealedSamples-_.audio.concealedSamples,C=p.audio.totalSamplesReceived-_.audio.totalSamplesReceived,N=Math.floor(R/C*1e3*s);if(N>s/5){let U=l.find(Fe=>Fe.msg_user_info.str_identifier===p.userId);U&&(U.msg_audio_status.uint32_audio_block_time=N)}}}}),e}getStatsReport(s){return f(this,arguments,function*({uplinkConnection:i,downlinkConnections:e,freezeMap:t}){let n={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}}]},o=yield this.getStats(i,e);return JSON.stringify(this._prevReport)==="{}"&&(this._prevReport=JSON.parse(JSON.stringify(n))),this.prepareReport({stats:o,report:n,freezeMap:t}),this._prevReportTime=Date.now(),n})}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}};var Kl=Se(Ne());var Rd=class extends Kl.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=S.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(fe.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 n=t.expectAudPkg+t.expectVidPkg,o=t.recvAudPkg+t.recvVidPkg,a=n-o;n===0&&o===0||(a<=0?this._uplinkLoss=0:this._uplinkLoss=Math.round(a/n*100),this._uplinkRTT=t.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this._uplinkLoss,this._uplinkRTT))}handleDownlinkNetworkQuality(){return f(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:m}=yield this.getStat(c);if(!this._downlinkPrevStatMap.has(c)){this._downlinkPrevStatMap.set(c,{totalPacketsLost:l,totalPacketsReceived:m});continue}let p=0,_=this._downlinkPrevStatMap.get(c),R=l-_.totalPacketsLost,C=m-_.totalPacketsReceived;R<=0||C<0?p=0:p=Math.round(R/(R+C)*100),this._downlinkPrevStatMap.set(c,{totalPacketsLost:l,totalPacketsReceived:m}),this._downlinkLossAndRTTMap.set(c,{rtt:d,loss:p,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:n,loss:o}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._downlinkRTT=n,this._downlinkLoss=o,this.downlinkNetworkQuality=this.getNetworkQuality(o,n)})}getStat(e){return f(this,null,function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!Bi())return t;let s=e.getReceivers();try{for(let n=0;n<s.length;n++)(yield s[n].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(n){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(fi,()=>{this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];T.emit(E.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this._uplinkRTT,loss:this._uplinkLoss},downlinks:e}),this.emit(Rd.EVENT_NETWORK_QUALITY,{uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this._uplinkRTT,uplinkLoss:this._uplinkLoss,downlinkRTT:this._downlinkRTT,downlinkLoss:this._downlinkLoss,downlinkInfo:e})},{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:n,audioDelay:o})=>{let a=t.get(s);if(a){let c=this._room.remotePublishedUserMap.get(a);c==null||c.setDelay({videoDelay:n,audioDelay:o})}})}},er=Rd;u(er,"EVENT_NETWORK_QUALITY","0");function vf({fn:r,context:i}){return function(...e){try{let t=r.apply(i,e);return As(t)?t.catch(s=>S.error(`${r.name}() error observed ${s}`)):t}catch(t){S.error(`${r.name}() error observed ${t}`)}}}var Yo=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=S.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&z(this[e])&&(this[e]=vf({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,Es().then(i=>{this._basicInfo.string_os_version=gs(),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),T.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,n=e.hasAuxiliary,o=t.hasAudio||t.hasVideo||t.hasSmall,a=t.hasAuxiliary;!s&&o&&this.handleRemoteStreamAdded(t.userId,"main"),!n&&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)=>T.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&&(g(i.params.frameWorkType)||(this._frameWorkType=i.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),g(i.params.component)||(this._component=i.params.component,this._basicInfo.uint32_component=this._component),g(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:n,tcp:o,tls:a,request:c,response:d}=e;this._pathJoinRoom.int32_schedule_cost=t,this._pathJoinRoom.int32_schedule_local=s,this._pathJoinRoom.int32_schedule_dns=n,this._pathJoinRoom.int32_schedule_tcp=o,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 n={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:w(v({},Df),{msg_user_info:new nn({userId:i,tinyId:(s=this._room.remotePublishedUserMap.get(i))==null?void 0:s.tinyId,role:20})})};n.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(t,n)}}handleSubscribeStart({room:i,remotePublishedUser:e,streamType:t,subscribeState:s}){if(!this.hitTest(i))return;let{userId:n,tinyId:o,role:a}=e,c=new nn({userId:n,tinyId:o,role:a==="anchor"?20:21}),d=Date.now(),l=`${n}_${t}`,m=this._remoteStreamStatMap.get(l);m&&m.subscribeStartTime===0&&(m.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:n,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:n,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}`,n=this._remoteStreamStatMap.get(s);n&&n.subscribedTime===0&&(n.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),n=this._remoteStreamStatMap.get(e);if(s&&(s.statsToReport.uint64_render_first_frame_time===0&&(s.statsToReport.uint64_render_first_frame_time=t),n)){let{statsToReport:a,playStreamTime:c,subscribedTime:d}=n;a.uint32_video_render_first===0&&c-d<=100&&(a.uint32_video_render_first=t-s.sendSubscribeCMDTime)}let o=this._pathAuxiliaryMap.get(e);if(o&&n){let{statsToReport:a,playStreamTime:c,subscribedTime:d}=n;a.uint32_video_render_first===0&&c-d<=100&&(a.uint32_video_render_first=t-o.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:n,audioDelay:o})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(s);if(a)a.totalRTT+=e,a.totalLoss+=t,n&&(a.totalVideoDelay=(a.totalVideoDelay||0)+n,a.videoDelayCount=(a.videoDelayCount||0)+1),o&&(a.totalAudioDelay=(a.totalAudioDelay||0)+o,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let c,d,l,m;n&&(d=n,l=1),o&&(c=o,m=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(s,{totalRTT:e,totalLoss:t,count:1,totalAudioDelay:c,totalVideoDelay:d,audioDelayCount:m,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:n,uint32_video_enc_fps:o,uint32_video_width:a,uint32_video_height:c}=t.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=n,this._localStreamStat.totalVideoFPS+=o,this._localStreamStat.totalVideoWidth+=a,this._localStreamStat.totalVideoHeight+=c,this._localStreamStat.videoCount++}if(t.msg_audio_status){let{uint32_audio_level:n}=t.msg_audio_status;Math.floor(n/ct*100)>0&&(this._localStreamStat.totalAudioLevel+=n/ct,this._localStreamStat.audioLevelCount++)}s.forEach(n=>{let{msg_user_info:o,msg_audio_status:a,msg_video_status:c}=n,d=o.str_identifier,l=this._room.remotePublishedUserMap.get(d);if(c.forEach(m=>{let p=m.uint32_video_stream_type===2,_=m.uint32_video_stream_type===7,R=`${d}_${p?"main":"auxiliary"}`,C=this._remoteStreamStatMap.get(R);if(!!C&&(p&&(l==null?void 0:l.remoteVideoTrack.isSubscribed)||_&&(l==null?void 0:l.remoteAuxiliaryTrack))){C.totalVideoFPS+=m.uint32_video_receive_fps,C.totalVideoBitrate+=m.uint32_video_codec_bitrate,C.videoCount++,C.statsToReport.uint32_video_width===0&&(C.statsToReport.uint32_video_width=m.uint32_video_width),C.statsToReport.uint32_video_height===0&&(C.statsToReport.uint32_video_height=m.uint32_video_height);let N=p?l.remoteVideoTrack:l.remoteAuxiliaryTrack;N.stat.jitterBufferDelay&&(C.videoJitterBufferDelay=N.stat.jitterBufferDelay),N.stat.framesReceived&&(C.statsToReport.uint32_video_consume_render_rate=Math.floor(N.stat.framesDecoded/N.stat.framesReceived*qr(10,6)))}}),a){let m=`${d}_${"main"}`,p=this._remoteStreamStatMap.get(m);this._remoteStreamStatMap.has(m)&&p&&(l==null?void 0:l.remoteAudioTrack.isSubscribed)&&(p.totalAudioBitrate+=a.uint32_audio_codec_bitrate,p.audioCount++,l.remoteAudioTrack.stat.jitterBufferDelay&&(p.audioJitterBufferDelay=l.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(a.uint32_audio_level/ct*100)>0&&(p.totalAudioLevel+=a.uint32_audio_level/ct,p.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&Li)>=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:m,audioDelayCount:p,videoDelayCount:_,totalAudioDelay:R,totalVideoDelay:C}=s;i.statsToReport.uint32_avg_down_loss=Math.floor(l/m),p&&R&&(i.statsToReport.uint32_audio_network_p2p_delay=Math.floor(R/p),i.audioJitterBufferDelay&&(i.statsToReport.uint32_p2p_delay=Math.floor(i.statsToReport.uint32_audio_network_p2p_delay+i.audioJitterBufferDelay))),_&&C&&(i.statsToReport.uint32_video_network_p2p_delay=Math.floor(C/_))}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:n}=this._room;n&&(i.statsToReport.uint32_audio_play_time=n.getDuration(e,h.AUDIO),i.statsToReport.uint32_video_play_time=n.getDuration(e,h.VIDEO)),i.statsToReport.uint32_video_render_first=Math.min(i.statsToReport.uint32_video_render_first,tr);let{badCaseDetector:o}=this._room,{dataFreeze:a,count:c}=o.getDataFreezeDuration(e),{renderFreeze:d}=o.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),o.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>tr&&(i.statsToReport.uint64_play_first_frame_time=i.statsToReport.uint64_start_enter_time+tr)}),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>tr&&(i.statsToReport.uint64_render_first_frame_time=i.statsToReport.uint64_start_enter_time+tr)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>tr&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+tr)}getReportData(){this._basicInfo.uint32_networkType=Ir();let i={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new nn({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Rs(this._signalInfo.relayIp),uint32_client_ip:Rs(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*qr(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:Rs(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport};return jn(i),i}report(){return f(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 f(this,null,function*(){if(i.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),t=yield Aa(i),s=t instanceof ArrayBuffer,n=`${Si(e,li.KEY_POINT)}&gzip=${+s}`,o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(n,t)),o||qt({url:n,body:t}),this.uploadKVStat(D),this.uploadKVStat($i)})}setConnectionType(i){this.connectionType=i,this._basicInfo.uint32_connection_type=i}uploadKVStat(i){return f(this,null,function*(){let e=i.getReportData();if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=w(v({},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 Aa(e),s=`${Si(+this._room.sdkAppId,li.KV_STAT)}&gzip=${+(t instanceof ArrayBuffer)}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,t)),n||qt({url:s,body:t})})}};y([it({settings:{timeout:500,retries:3}})],Yo.prototype,"upload",1);var tr=5e3,Df={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},nn=class{constructor(i){this.str_identifier=String(i.userId),this.str_tinyid=String(i.tinyId||0),this.uint32_role=i.role}},Zl=Yo;var yd=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}},Hr=yd;var bd=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 o;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 n=(o=this._room)==null?void 0:o.remotePublishedUserMap.get(s);!n||(!e.hasAudio&&t.hasAudio&&n.remoteAudioTrack.isSubscribed&&this.addDuractionItem(s,h.AUDIO,"main"),!e.hasVideo&&t.hasVideo&&n.remoteVideoTrack.isSubscribed&&this.addDuractionItem(s,h.VIDEO,"main"),!e.hasAuxiliary&&t.hasAuxiliary&&n.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(s,h.VIDEO,"auxiliary"))}),this._eventMap.forEach((i,e)=>T.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>T.off(e,i,this)),this._eventMap.clear()}handleSubscribed({room:i,streamType:e,remotePublishedUser:t}){if(!this.hitTest(i))return;let{userId:s}=t,n=`${s}_${e}`;if(t.muteState.hasAudio&&e==="main")if(t.remoteAudioTrack.isSubscribed){let o=new Hr,a=this._durationMap.get(n);a?this.isRecording(a.audio)||a.audio.push(o):this._durationMap.set(n,{userId:s,type:e,audio:[o],video:[]})}else this.stopDurationItem(n,h.AUDIO);if(t.muteState.hasVideo||t.muteState.hasAuxiliary)if(t.remoteVideoTrack.isSubscribed||t.remoteAuxiliaryTrack.isSubscribed){let o=new Hr,a=this._durationMap.get(n);a?this.isRecording(a.video)||a.video.push(o):this._durationMap.set(n,{userId:s,type:e,audio:[],video:[o]})}else this.stopDurationItem(n,h.VIDEO)}handleStreamStopped({room:i,streamType:e,remotePublishedUser:t}){if(!this.hitTest(i))return;let{userId:s}=t,n=`${s}_${e}`;this.stopDurationItem(n,h.AUDIO),this.stopDurationItem(n,h.VIDEO)}isRecording(i){return i.findIndex(e=>e.endTime===0)>=0}addDuractionItem(i,e,t){let s=`${i}_${t}`,n=new Hr,o=this._durationMap.get(s);o?this.isRecording(o[e])||o[e].push(n):this._durationMap.set(s,{userId:i,type:t,audio:e===h.AUDIO?[n]:[],video:e===h.AUDIO?[]:[n]})}stopDurationItem(i,e){if(this._durationMap.has(i)){let s=this._durationMap.get(i)[e].find(n=>n.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,n)=>s+n.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},eh=bd;var Nd=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,n=`${s}_${e}`;this.stopDataFreeze({key:n,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 n="main",o=`${t.userId}_${n}`;this.stopDataFreeze({key:o,userId:s,type:n})}if(e.hasAuxiliary&&!t.hasAuxiliary){let n="auxiliary",o=`${t.userId}_${n}`;this.stopDataFreeze({key:o,userId:s,type:n})}}).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 n=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.set(n,!0)}t===h.MUTE?this.onVideoTrackMuted(i):t===h.UNMUTE&&this.onVideoTrackUnmuted(i)}}).set(E.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((i,e)=>T.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>T.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}`,n=this._dataFreezeMap.get(s),o=new Hr;n?n.durationItemList.push(o):this._dataFreezeMap.set(s,{userId:e,type:t,durationItemList:[o],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:n,muteState:o}=s;t.msg_video_status.forEach(a=>{a.uint32_video_stream_type===2&&o.hasVideo&&!o.videoMuted&&s.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:n,fps:a.uint32_video_dec_fps,type:"main"}),a.uint32_video_stream_type===7&&o.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:n,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 n=s.durationItemList[s.durationItemList.length-1];n.stop();let o=n.getDuration();o>Cn?this._monitorFreezeData.set(i,{userId:e,type:t,duration:o}):s.durationItemList.pop()}getTotalDuration(i){return i.reduce((e,t)=>{let s=t.getDuration();return e+Math.min(s,5e3)},0)}handleRenderFreeze(s){return f(this,arguments,function*({userId:i,fps:e,type:t}){let n=`${i}_${t}`,o=this._renderFreezeMap.get(n);if(e<=2){let a=x();o&&!o.isFreeze&&(o.freezeTimeline.push({startTime:a,endTime:0}),o.isFreeze=!0),o||this._renderFreezeMap.set(n,{userId:i,type:t,isFreeze:!0,freezeTimeline:[{startTime:a,endTime:0}],renderFreezeTotal:0})}else if(o&&o.isFreeze){o.isFreeze=!1;let a=o.freezeTimeline.pop();if(a){a.endTime=x();let c=a.endTime-a.startTime;o.freezeTimeline.push(a),o.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()<Cn&&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 n=x(),o=e.freezeTimeline[e.freezeTimeline.length-1],a=n-o.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()}},th=Nd;var ih=Se(Ne(),1);var Of=[1,0,0,0,1,1,0,1],Ko=class extends Qe{constructor(i){if(super(i,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror"}),i instanceof ye)try{this.setTexBuffer(Of)}catch(e){i.destroy(e)}}draw2d(i,e,t,s,n){if(this.ctx2d){this.ctx2d.save(),this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0);let o=super.draw2d(i,e,t,s,n);return this.ctx2d.restore(),o}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 vd=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}},Zo=class extends Qe{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 vd(e,t);this.inputs[t.zIndex]=s}resize(e,t){let s=this.inputs.reduce((n,o)=>o?Object.assign(n,{width:Math.max(n.width,o.right),height:Math.max(n.height,o.bottom)}):n,{width:0,height:0});super.resize(s.width,s.height),this.context instanceof ye&&this.inputs.forEach(n=>{if(n){let o=this.layout2texCoords(n);n.positionBuffer?this.changeBufferData(n.positionBuffer,o):n.positionBuffer=this.createBuffer(o)}})}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((n,o)=>(!o||!o.node.requestFrame(e))&&n,!0)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let n=0;n<this.inputs.length;n++){let o=this.inputs[n];o&&(o.node.useTexture(),this.draw(o.positionBuffer))}return!0}return!1}render2d(e){if(!this.inputs.reduce((s,n)=>(!n||!n.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 n=this.inputs[s];n&&this.draw2d(n.node.image,n.x,n.y,n.width,n.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:t,y:s,width:n,height:o,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:n,height:o,timestamp:c,fps:d,name:a},v({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(n){}})}};var Mf=`#version 300 es
|
|
in vec2 a_position;
|
|
in vec2 a_texCoord;
|
|
out vec2 v_texCoord;
|
|
void main() {
|
|
gl_Position = vec4(a_position.x, a_position.y, 0, 1);
|
|
v_texCoord = a_texCoord;
|
|
}`,kf=`#version 300 es
|
|
precision highp float;
|
|
uniform sampler2D u_texture;
|
|
uniform sampler2D mask;
|
|
|
|
in vec2 v_texCoord;
|
|
out vec4 outColor;
|
|
void main() {
|
|
outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a);
|
|
}`,ea=class extends Or{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 f(this,null,function*(){var n,o;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,(n=this.context._canvas)==null?void 0:n.width,(o=this.context._canvas)==null?void 0:o.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,kf),c=this.context.createShader(s.VERTEX_SHADER,Mf);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(typeof this.image.getVideoPlaybackQuality=="function"&&!bt){let m=this.image.getVideoPlaybackQuality().totalVideoFrames;if(this._totalFrames===m)return!1;this._totalFrames=m,this.dropFrames=this._totalFrames-this.totalFrames}let{videoWidth:s,videoHeight:n}=this.image;this.image.width=s,this.image.height=n;let o=!1;if(this.totalFrames)this._weixin?this.useTexture():this==null||this._selfieSegmentation.bindTexture(),o=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(this.program)this.useTexture();else return!1;o=this._textureValid,this._textureValid=!0}return this.width!==s||this.height!==n||!o?(this.resize(s,n),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,n):t.copyTexImage2D(t.TEXTURE_2D,0,t.RGBA,0,0,s,n,0)),(d=this._selfieSegmentation)==null||d.send(s,n)),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 ta=class extends ih.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",S.createLogger({id:"vm"}));u(this,"_checkId",0);u(this,"_use2d",!1);u(this,"_autoSwitchRenderMode",!0);u(this,"_selfieSegmentation");u(this,"_seiEncodeProcessor");u(this,"_seiDecodeProcessor");e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new $e({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 $e({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(wi,()=>{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(bt||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:n,settings:o,player:a}=s;n?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new Co(this.smallVideoContext,n)),this.smallVideoContext.frameRate=n.frameRate,this.smallDestination.resolution=n,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=o.width,this.smallTrackSource.height=o.height,this.smallTrackSource.connect(this.smallDestination)))):this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource),bt&&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 f(this,null,function*(){var s,n;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 Ao(this.videoContext,{name:"mainDestination",logger:this.log})),this.cameraNode=new ea(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 o=this.cameraNode;o.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new Ko(this.videoContext)),o=o.connect(this.mirrorNode),o.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new Zo(this.videoContext),o.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")),(n=this.screenNode)==null||n.connect(this.mixNode,{zIndex:0}),o=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)),o.connect(this.destination)}return this.log.info(`update ${this._use2d?"2d":"webgl"}`),this._setMainOutput(this.videoContext._canvas)})}changeInput(e){var t,s,n,o;if(e instanceof Xe)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 gt){this.log.info("change remote input",(n=e.mediaTrack)==null?void 0:n.label);let a=e.mediaTrack;return this._seiDecodeProcessor&&(e.pipeline[1]=this._seiDecodeProcessor),e.setOutputMediaStreamTrack(a)}this.log.warn("change unknown input",(o=e.mediaTrack)==null?void 0:o.label)}configPipeline(e){e instanceof gt&&this._seiDecodeProcessor&&(e.pipeline[1]=this._seiDecodeProcessor)}removeInput(e){var t;e instanceof Xe?((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 gt&&e.source&&e.source.context.destroy()}setCameraTrack(e){return f(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 f(this,null,function*(){let s=document.createElement("canvas");t&&e&&(s.height=t,s.width=e);let n=s.getContext("2d");if(!n)throw new b({code:A.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((o,a)=>o.zIndex-a.zIndex),this.watermarkImageList.forEach(({image:o,x:a,y:c,width:d,height:l})=>{n.drawImage(o,a,c,d,l)}),bs(s.toDataURL())})}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some(n=>n.imageUrl===e.imageUrl&&n.height===e.height&&n.width===e.width&&n.x===e.x&&n.y===e.y&&n.type===e.type&&n.zIndex===e.zIndex)||((t==="mute"||t==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(n=>n.type!==t)),this.watermarkImageList.push(e))}setBeautyParams(e){return f(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return f(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return f(this,null,function*(){let t;try{t=yield bs((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:n=0,width:o=t.width,height:a=t.height,type:c="watermark",zIndex:d=2}=e;this.pushWaterMarkImageList({x:s,y:n,width:o,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 f(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 f(this,null,function*(){var t,s,n;(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,(n=this.cameraTrack)==null?void 0:n.settings.height);this._waterMarkOption={x:0,y:0,width:e.width,height:e.height,image:e},this.update()})}setVirtualBackground(e){return f(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 bs(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 f(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(e,t){this._seiEncodeProcessor=e,this._seiDecodeProcessor=t,this.cameraTrack&&(this.cameraTrack.pipeline[0]=this._seiEncodeProcessor),this.screenTrack&&(this.screenTrack.pipeline[0]=this._seiEncodeProcessor)}disableSEI(){delete this._seiEncodeProcessor,delete this._seiDecodeProcessor,this.cameraTrack&&(this.cameraTrack.pipeline[0]=void 0),this.screenTrack&&(this.screenTrack.pipeline[0]=void 0)}};var Lf=0;var ia=class extends ${constructor(e){super("room");this.seq=++Lf;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=S.createLogger({id:`r${this.seq}`});this._joinedTimestamp=0;this.isDestroyed=!1;this.useStringRoomId=!!e.useStringRoomId,pe(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),pe(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),pe(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new Zl({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new eh({room:this}),this.badCaseDetector=new th({room:this}),this.audioManager=new So(this),this.videoManager=new ta(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 f(this,null,function*(){return this.publish(e)})}removeTrack(e){return f(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return f(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(Ge(e)){let{websocketProxy:t,webtransportProxy:s,loggerProxy:n,scheduleProxy:o,unifiedProxy:a}=e;this.proxy_ws=t,this.proxy_wt=s,this.proxy_unified=a,a?(Va([a,a]),ki(`https://${a}`)):(n&&ki(n),o&&Va(o))}T.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 f(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(t=>{e[t.userId]=t.remoteAudioTrack.stat}),e})}getTransportStats(){return f(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 f(this,arguments,function*(e="main"){let t={};return this.remotePublishedUserMap.forEach(s=>{let n=e==="auxiliary"?s.remoteAuxiliaryTrack:s.remoteVideoTrack;t[s.userId]=n.stat}),t})}checkDestroy(){if(this.isDestroyed)throw new b({code:A.INVALID_OPERATION,message:k({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:k({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,T.emit(E.ROOM_DESTROY,{room:this})}schedule(e,t){return f(this,null,function*(){var n,o;let s=x();try{let{isCached:a,result:c,detailCost:d}=yield ou({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&&T.once(E.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=v(v({},this.scheduleResult),c),ee((n=c.config)==null?void 0:n.retryCount)&&_a(c.config.retryCount),Y((o=c.config)==null?void 0:o.loggerDomain)&&ki(c.config.loggerDomain),T.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 sh=Se(Ne(),1);var rh=Symbol("instance"),rL=Symbol("abortCtrl"),Dd=Symbol("cacheResult"),on=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,dn.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},an=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function xf(r){return typeof r=="object"&&r&&"then"in r}var cn=new Map;function Od(r,i,e={}){return(t,s,n)=>{let o=e.action||s;if(!e.context){let c=cn.get(t)||[];cn.has(t)||cn.set(t,c),c.push({from:r,to:i,action:o})}let a=n.value;n.value=function(...c){let d=this;if(e.context&&(d=oe.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),d.state===i)return d[Dd];d.state instanceof on&&d.state.action==e.abortAction&&d.state.abort(d);let l=null;if(Array.isArray(r)?r.length==0?d.state instanceof on&&d.state.abort(d):(typeof d.state!="string"||!r.includes(d.state))&&(l=new an(d._state,`${d.name} ${o} to ${i} failed: current state ${d._state} not in from config`)):r!==d.state&&(l=new an(d._state,`${d.name} ${o} 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 m=d.state,p=new on(m,i,o);dn.call(d,p);let _=C=>{var N;return d[Dd]=C,p.aborted||(dn.call(d,i),(N=e.success)===null||N===void 0||N.call(this,d[Dd])),C},R=C=>{let N=C instanceof Error?C.message:String(C);if(dn.call(d,m,C),e.fail)e.fail.call(this,new an(d._state,`action '${o}' failed :${N}`,C instanceof Error?C:new Error(N)));else{if(e.ignoreError)return C;throw C}};try{let C=a.apply(this,c);return xf(C)?C.then(_).catch(R):_(C)}catch(C){R(C)}}}}var Pf=(()=>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 dn(r,i){let e=this._state;this._state=r;let t=r.toString();r&&this.emit(t,e),this.emit(oe.STATECHANGED,r,e,i),this.updateDevTools({value:r,old:e,err:i instanceof Error?i.message:String(i)})}var oe=class extends sh.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=oe.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[rh];s?this.name=s.name+"-"+s.count++:t[rh]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=cn.get(i)||[],t=new Set,s=[],n=[],o=new Set,a=Object.getPrototypeOf(i);cn.has(a)&&(a.stateDiagram.forEach(d=>t.add(d)),a.allStates.forEach(d=>o.add(d))),e.forEach(({from:d,to:l,action:m})=>{typeof d=="string"?s.push({from:d,to:l,action:m}):d.length?d.forEach(p=>{s.push({from:p,to:l,action:m})}):n.push({to:l,action:m})}),s.forEach(({from:d,to:l,action:m})=>{o.add(d),o.add(l),o.add(m+"ing"),t.add(`${d} --> ${m}ing : ${m}`),t.add(`${m}ing --> ${l} : ${m} \u{1F7E2}`),t.add(`${m}ing --> ${d} : ${m} \u{1F534}`)}),n.forEach(({to:d,action:l})=>{t.add(`${l}ing --> ${d} : ${l} \u{1F7E2}`),o.forEach(m=>{m!==d&&t.add(`${m} --> ${l}ing : ${l}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:o}}),c}static get(i){let e;return typeof i=="string"?(e=oe.instances.get(i),e||oe.instances.set(i,e=new oe(i,void 0,Object.create(oe.prototype)))):(e=oe.instances2.get(i),e||oe.instances2.set(i,e=new oe(i.constructor.name,void 0,Object.create(oe.prototype)))),e}static getState(i){var e;return(e=oe.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){Pf(oe.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){dn.call(this,i)}};oe.STATECHANGED="stateChanged";oe.UPDATEAFSM="updateAFSM";oe.INIT="[*]";oe.ON="on";oe.OFF="off";oe.instances=new Map;oe.instances2=new WeakMap;var mh=Se(Ne());var Md=Se(Td());var nh=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 n;if(t.ssrcs&&!g(t.ssrcs[0].id)){let o=Number(t.ssrcs[0].id),a=Number((n=t.ssrcs.filter(c=>c.attribute==="cname")[1])==null?void 0:n.id);switch(s){case 0:e.audioSsrc=o;break;case 1:e.bigVideoSsrc=o,e.bigVideoRtxSsrc=a;break;case 2:e.smallVideoSsrc=o,e.smallVideoRtxSsrc=a;break;case 3:e.auxVideoSsrc=o,e.auxVideoRtxSsrc=a;break}}}),e};function oh(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(n=>n.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(n=>n.payload===r.rtp[t].payload).map(({type:n,subtype:o})=>({id:n,params:o?[o]:[]}))})}return i}function wf(){return f(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=oh(e.media[0]);return r.close(),t})}var ah=(r,i)=>f(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],n=e.media[1];s.ext&&(t.audio.extensions=s.ext.map(d=>({id:d.value,uri:d.uri}))),n.ext&&(t.video.extensions=n.ext.map(d=>({id:d.value,uri:d.uri})));let o={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:m})=>{if(d===o.payload){let p={id:l,params:[]};m&&p.params.push(m),o.rtcpFb.push(p)}}),t.audio.codecs.push(o);let a=["h264","vp8"];return i&&a.shift(),t.video.codecs=[...oh(n)].filter(d=>a.includes(d.codec.toLocaleLowerCase())),t.video.decoders=(yield wf()).filter(d=>["h264","vp8"].includes(d.codec.toLocaleLowerCase())),t}),ch=({serverAbility:r,clientAbility:i,offerSDP:e,enableCustomMessage:t})=>{let s=ce(e),n={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},o={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 n.media.push(o),[1,2,3].forEach(a=>{n.media.push(kd({mid:a,serverAbility:r,clientAbility:i,parsedOffer:s}))}),t&&n.media.push(s.media.find(a=>a.mid==="dc")),Ye(n)},kd=({mid:r,serverAbility:i,clientAbility:e,parsedOffer:t,isDownlink:s=!1})=>{let n={candidates:i.candidates.map(o=>({component:1,foundation:"1",generation:0,ip:o.ip,port:o.port,priority:o.priority,transport:o.foundation,type:o.type})),connection:{version:4,ip:"0.0.0.0"},direction:h.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map(o=>({value:o.id,uri:o.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(o=>{Gr(n,o)});else{let o=i.video.codecs.findIndex(c=>c.codec.toLowerCase()===(i.useVp8?"vp8":"h264")),a=i.video.codecs[o]||e.video.codecs[0];Gr(n,a)}return n},Gr=(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 Vf(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 Uf(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 Bf(r){r.type===h.VIDEO&&r.fmtp&&r.fmtp.forEach(i=>{i.config.includes("apt")||(i.config+=";sps-pps-idr-in-keyframe=1")})}function $f(r){r.type===h.AUDIO&&r.fmtp&&r.fmtp.forEach(i=>{i.config+=";sprop-stereo=1;stereo=1"})}var dh=(r,i,e)=>{let t=Md.default.parse(r);return t.media.forEach((s,n)=>{var o;(s.type===h.AUDIO||s.type===h.VIDEO)&&(Uf(s),Bf(s),$f(s),Vf(s),s.type===h.VIDEO&&(n<4?(s.payloads="",s.fmtp=[],s.rtp=[],s.rtcpFb=[],i.video.codecs.forEach(a=>Gr(s,a))):e&&(s.payloads="",s.fmtp=[],s.rtp=[],s.rtcpFb=[],(e.video.decoders||e.video.codecs).forEach(a=>Gr(s,a))))),((o=s.payloads)==null?void 0:o.includes("datachannel"))&&t.groups&&s.mid&&(t.groups[0].mids=t.groups[0].mids.replace(s.mid,"dc"),s.mid="dc")}),Md.default.write(t)};var uh=Se(Ne());var ra=class extends uh.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");!de&&et&&T.on("262",this.onVideoCodecChanged,this),this.log=e.getLogger().createChild({id:"h-d"})}onVideoCodecChanged({remoteUserId:e,streamType:t,isHWCodec:s,codec:n}){if(!(e||t===7||n!=="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(){T.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};u(ra,"EVENT_BAD_HEALTH","bad_health");var lh=ra;var Gt=(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))(Gt||{}),ph=0,fh=!1,Ff=new Set,Hf=r=>ph>2&&!fh&&Ff.size===0&&r,Gf=1,ui=class extends mh.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,"abortMap",new Map);u(this,"enableInsertableStreams",!1);this._room=t,this._enableCustomMessage=s,this._signalChannel=e,this._log=S.createLogger({id:`spc${Gf++}`,userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableSEI&&_t&&(this.enableInsertableStreams=!0),this._room.healthDetector.on("1",({isAux:n})=>{this.useHWEncoder(!1,n?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.abortMap.get(e))==null||s.abort("destory"),this.abortMap.set(e,t)}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.useVp8),e}get videoCodec(){var e;return(e=this._serverAbility)!=null&&e.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?nh(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 f(this,null,function*(){var t;let e;try{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 n=this._peerConnection.iceConnectionState;this._log.debug(`ice state: ${n}`),n==="checking"&&this.stat.iceStartTime===0?this.stat.iceStartTime=Date.now():n==="connected"&&this.stat.iceEndTime===0&&(this.stat.iceEndTime=Date.now())},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=n=>this.emit("track",n),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=n=>{let o=new xd(n.data);this.emit("data_channel_msg",{data:o})},this._datachannel.onerror=n=>{this._log.warn("datachannel error",n)}),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();let s=!this.isH264EncodeSupported;return g((t=this._room.scheduleResult.config)==null?void 0:t.remove264FromSDP)||(s=s&&this._room.scheduleResult.config.remove264FromSDP),this.clientAbility=yield ah(e.sdp,s),yield this.setOffer(e),this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:n}=this;!n||(this._log.debug(`dtls state: ${n.state}`),n.state==="connecting"&&this.stat.dtlsStartTime===0?this.stat.dtlsStartTime=Date.now():n.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}
|
|
offer: ${e==null?void 0:e.sdp}`),s}})}connect(e,t=!1){return f(this,null,function*(){try{if(this.currentState==="CONNECTED")return;let s=x(),n={type:"answer",sdp:ch({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(n),yield this.waitForPeerConnectionConnected(),t||D.addSuccessEvent({key:521703,cost:x()-s})}catch(s){let n=s instanceof b&&s.code===A.API_CALL_ABORTED;throw n||this._log.error(`connect failed: ${s}`,e),this.reset(),!n&&!this.isReconnecting&&(D.addFailedEvent({key:521703,error:s}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),s}})}reconnect(){return f(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(fe.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(),T.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=Mt(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>=jt()&&this._log.warn(`SDK has tried reconnect for ${jt()} times, but all failed, please check your network`),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}})}getPeerConnection(){return this._peerConnection}startReconnection(){return f(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(fe.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()),T.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 ot;let e=null;return!Ri()||this._peerConnection.getSenders().length===0?ot:(e=this._peerConnection.getSenders()[0].transport,!Bi()||this._peerConnection.getReceivers().length===0?ot:e?e.state:ot)}emitConnectionStateChangedEvent(e){e!==this.currentState&&(this.currentState==="RECONNECTING"&&e==="CONNECTING"||(this.emit(Gt.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return f(this,null,function*(){if(!this._peerConnection)return;let e=yield this._peerConnection.getStats();for(let[t,s]of e)if(Ci(s)){let n=e.get(s.localCandidateId),o=e.get(s.remoteCandidateId);n&&(this._log.info(`local candidate: ${n.candidateType} ${n.protocol}:${n.ip||n.address}:${n.port} ${n.networkType||""} ${n.candidateType==="relay"?`relayProtocol:${n.relayProtocol}`:""}`),n.networkType&&Ua(n.networkType)),o&&this._log.info(`remote candidate: ${o.candidateType} ${o.protocol}:${o.ip||o.address}:${o.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),o(),e())},n=({room:c})=>{c===this._room&&(clearTimeout(a),o(),t(new b({code:A.API_CALL_ABORTED,message:k({key:M.CONNECTION_ABORTED,data:"leave room"})})))},o=()=>{T.off(E.LEAVE_SUCCESS,n,this),this.off(Gt.CONNECTION_STATE_CHANGED,s,this)},a=setTimeout(()=>{o();let c=new b({code:A.API_CALL_TIMEOUT,message:"connection timeout"});ph+=1,Hf(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),fh=!0,this.emit(Gt.FIREWALL_RESTRICTION)),t(c)},is);T.on(E.LEAVE_SUCCESS,n,this),this.on(Gt.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 f(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 n=this._peerConnection.getTransceivers().filter(p=>p.direction==="inactive").slice(0,3).map(p=>(p.direction=h.TRANSCEIVER_DIRECTION_RECVONLY,Number(p.mid)));this._parsedAnswer||(this._parsedAnswer=ce(this._peerConnection.remoteDescription.sdp));let o=this._parsedAnswer.media.filter(p=>{var _;return(_=p.ssrcs)==null?void 0:_.find(R=>{var C;return(C=R.value)==null?void 0:C.includes(s)})}),a,c,d;if(o.length===3)a=o[0],c=o[1],d=o[2];else if(n.length===3)a=this._parsedAnswer.media.find(p=>Number(p.mid)===Number(n[0])),c=this._parsedAnswer.media.find(p=>Number(p.mid)===Number(n[1])),d=this._parsedAnswer.media.find(p=>Number(p.mid)===Number(n[2]));else if(n.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 p=kd({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:ce(this._peerConnection.localDescription.sdp),isDownlink:!0});c=JSON.parse(JSON.stringify(p)),d=JSON.parse(JSON.stringify(p)),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 m=`${l}-aux`;d.ssrcs=[{id:e.auxiliary,attribute:"cname",value:m},{id:e.auxiliary,attribute:"msid",value:`${m} ${l}-aux${h.VIDEO}`},{id:e.auxiliaryRtx,attribute:"cname",value:`${m} ${l}-aux${h.VIDEO}`},{id:e.auxiliaryRtx,attribute:"msid",value:`${m} ${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(p=>p.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 f(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(n=>{t!=null&&t.includes(Number(n.mid))&&(s=!0,n.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=ce(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(n=>{t!=null&&t.includes(Number(n.mid))&&(s=!0,n.direction="inactive",n.ssrcs=[],n.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&s&&(yield this.updateSDP()),this._downlinkMIDMap.delete(e),t==null||t.forEach(n=>this._downlinkMIDUserIDMap.delete(n)),this._log.info(`removeDownlink(${e}) done`)})}setBandwidth(e){return f(this,null,function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:s,smallVideo:n,auxVideo:o}=e;try{if(Ms()){let a=this._peerConnection.getSenders().slice(0,4);for(let d=0;d<a.length;d++){let l=a[d],m;d===0&&t?m=t:d===1&&s?m=s:d===2&&n?m=n:d===3&&o&&(m=o),m&&(yield this.setSenderMaxBitrate(l,m))}let c=!1;s&&a[1].track&&(c=this.setStartBitrate(1,s)),o&&a[3].track&&(c=this.setStartBitrate(3,o)||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,n;return(s=this._peerConnection)!=null&&s.remoteDescription&&(this._parsedAnswer||(this._parsedAnswer=ce(this._peerConnection.remoteDescription.sdp)),(n=this._parsedAnswer.media[e])!=null&&n.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:n}){if(!this._peerConnection||!this._peerConnection.localDescription)return;let o=ce(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=ce(this._peerConnection.remoteDescription.sdp));let a=te?"TIAS":"AS";e&&(o.media[0].bandwidth=[{type:a,limit:te?e*1e3:e}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:te?e*1e3:e}]),t&&(o.media[1].bandwidth=[{type:a,limit:te?t*1e3:t}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:te?t*1e3:t}]),s&&(o.media[2].bandwidth=[{type:a,limit:te?s*1e3:s}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:te?s*1e3:s}]),n&&(o.media[3].bandwidth=[{type:a,limit:te?n*1e3:n}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:te?n*1e3:n}]);let c={type:"offer",sdp:Ye(o)};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=Ye(this._parsedAnswer);return this._updateSDPPromise=new Promise((s,n)=>f(this,null,function*(){var o,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((o=this._peerConnection.localDescription)==null?void 0:o.sdp)}
|
|
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)}
|
|
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:m,stopped:p})=>({mid:d,currentDirection:l,direction:m,stopped:p})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._isSDPLogged=!0),this._updateSDPPromise=null,n(c)}})),this._updateSDPPromise}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:dh(e.sdp,this.clientAbility,this._serverAbility)})}setAnswer(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._peerConnection.setRemoteDescription(e)}useHWEncoder(e=!0,t){return f(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let s=!1,n=[];g(t)?n=this._parsedAnswer.media.slice(1,4):t===2?n.push(this._parsedAnswer.media[1]):t===3?n.push(this._parsedAnswer.media[2]):t===7&&n.push(this._parsedAnswer.media[3]),n.forEach(o=>{var a;if(o.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=o.payloads)!=null&&a.includes(String(c.payload)))&&(o.fmtp=[],o.payloads="",o.rtp=[],o.rtcpFb=[],Gr(o,c),s=!0)}}),s&&(this._log.warn(`use ${e?"hw":"sw"} encoder`),yield this.setOffer(this._peerConnection.localDescription),yield this.setAnswer({type:"answer",sdp:Ye(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.abortMap.forEach(e=>fu(e.abort)&&e.abort("destroy")),this.abortMap.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([go("reconnect")],ui.prototype,"startReconnection",1),y([si(r=>r.userId)],ui.prototype,"addDownlink",1),y([si(r=>r)],ui.prototype,"removeDownlink",1),y([Bt(!0)],ui.prototype,"updateSDP",1);var Ld=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}},xd=class{constructor(i){u(this,"tinyId");u(this,"data");let e=new DataView(i),t=0,s=[];for(;t<e.byteLength;){let n=e.getUint16(t+2),o=new Ld(new Uint8Array(i).slice(t,t+2+2+n).buffer);s.push(o),t+=2+2+n}s.forEach(n=>{n.tag===1?this.tinyId=new TextDecoder().decode(n.data):n.tag===2&&(this.data=n.data)})}},hh=new Set;function ir(){let r=Math.floor(Math.random()*4294967296);return hh.has(r)?ir():(hh.add(r),r)}var _h=Se(Ne());var rr=class extends _h.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=S.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:(T.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 Pd=class extends rr{constructor(e){super(w(v({},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:n,smallVideoRtxSsrc:o,auxVideoSsrc:a,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:s||0,small:n||0,smallRtx:o||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,n=Object.keys(t).find(o=>t[o]!==s[o]);if(n)if(e)this._log.warn(`publish state not matched, ${n} local:${t[n]} server:${s[n]} ${gs()} ${ka()}`),D.addCount({key:521e3});else{this._checkPublishStateTimeoutId=re.run(_i,()=>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,n,o;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(kt()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((s=a[1])!=null&&s.track),e.smallVideo=!!((n=a[2])!=null&&n.track),e.auxVideo=!!((o=a[3])!=null&&o.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&es),auxVideo:!!(this.flag&Li)}}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 n of t)n.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)}uninstallEvents(){var e;this.off("connection-state-changed",this.handleConnectionStateChange,this),(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this)}emitConnectionStateChangedEvent(e,t){var o,a,c;let s=this._currentState,n=super.emitConnectionStateChangedEvent(e);return n&&s!==e&&(t?t.emit("connection-state-changed",{prevState:s,state:e}):((o=this.localMainVideoTrack)==null||o.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}))),n}publish(n){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:s}){var d,l,m,p,_,R,C;if(!this.singlePC)return;yield this.singlePC.waitForPeerConnectionConnected();let{publishState:o,muteState:a}=this;if(e&&(this._publishingLocalAudioTrack=e,o.audio=!0,a.audio=e.muted),t){if(!this.singlePC.isH264EncodeSupported&&!this.singlePC.isVP8EncodeSupported)throw new b({code:A.NOT_SUPPORTED_H264,message:k({key:M.NOT_SUPPORTED_H264ENCODE})});de&&gi()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn("fallback video to 480p"),t.setProfile(Ke["480p_2"]),yield t.applyProfile()),this._publishingLocalVideoTrack=t,s?(o.auxVideo=!0,a.auxVideo=t.muted):(o.bigVideo=!0,a.bigVideo=t.muted)}this._isPublishingAux=s;let c;if(t&&!s&&t.small&&(c=this._room.videoManager.smallTrack,o.smallVideo=!0),yield this._signalChannel.sendWaitForResponseWithRetry({command:j.SPC_PUBLISH,responseCommand:V.SPC_PUBLISH_RESULT,data:w(v({},this.singlePC.uplinkSSRC),{state:o,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:N}=t;N>1&&(this._log.warn(`setScaleResolutionDownBy ${t.streamType} ${N}`),yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[s?3:1],N))}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:(m=this.localMainVideoTrack)==null?void 0:m.profile.bitrate,smallVideo:(_=(p=this.localMainVideoTrack)==null?void 0:p.small)==null?void 0:_.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:n}){if(!tt())return;this._log.info("publish by transceiver");let o=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack,c=this._peerConnection.getTransceivers(),d=[],l=[],m=(_,R,C)=>{var U;let N=c[R].sender.replaceTrack(C);l.push(R),(U=this.singlePC)!=null&&U.enableInsertableStreams&&N.then(()=>this.createEncodedStreams(c[R].sender,_)),d.push(N)};a&&m(e.mediaType,0,a),o&&m(t.mediaType,n?3:1,o),s&&m(8,2,s);let p=this.setTransceiverDirection(q.SENDONLY,l);return d.push(p),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:throw new Error("mediaType error")}}createEncodedStreams(e,t){var a,c;if(this.singlePC.abortMap.has(e))return;let s=e.createEncodedStreams(),n=new AbortController;(a=this.singlePC)==null||a.addAbortController(e,n),((c=this.getTrackByMediaType(t))!=null&&c.enableEncodeFrame?s.readable.pipeThrough(new TransformStream({transform:(d,l)=>{var m;return l.enqueue((m=this.singlePC)!=null&&m.isUsingH264?this.getTrackByMediaType(t).encodeFrame(d,t===8):d)}}),n):s.readable).pipeTo(s.writable,n).catch(d=>{this._log.debug("encoded stream error",d),d!=="destory"&&this._log.warn(d)})}enableSmall(e){return f(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.setTransceiverDirection(q.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(q.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(s){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){let n=t&&t===this.localAuxVideoTrack,o=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(yield a[0].replaceTrack(null),c.push(0),n?this.localAuxAudioTrack=null:this.localMainAudioTrack=null),o&&(n?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=w(v({},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=w(v({},this._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),c.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(q.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return f(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},s=yield this._signalChannel.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:n,localAuxVideoTrack:o}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?o=this._publishingLocalVideoTrack:n=this._publishingLocalVideoTrack),Lt){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(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=n.profile.bitrate*1e3,n.small&&(this._mediaSettings.smallVideoWidth=n.small.width,this._mediaSettings.smallVideoHeight=n.small.height,this._mediaSettings.smallVideoFps=n.small.frameRate,this._mediaSettings.smallVideoBps=n.small.bitrate*1e3)}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=o.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),n&&n.outMediaTrack&&(this._mediaSettings.videoWidth=n.profile.width,this._mediaSettings.videoHeight=n.profile.height,this._mediaSettings.videoFps=n.profile.frameRate,this._mediaSettings.videoBps=n.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 f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?h.AUXILIARY:h.MAIN} stream`),kt()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return f(this,null,function*(){var n;if(!e.mediaTrack)return;let s=this._peerConnection.getTransceivers();if(e.kind===h.AUDIO)yield s[0].sender.replaceTrack(e.outMediaTrack);else{let o=t?3:1;yield s[o].sender.replaceTrack(e.outMediaTrack),o===1&&((n=this.localMainVideoTrack)==null?void 0:n.small)&&(yield s[2].sender.replaceTrack(this._room.videoManager.smallTrack)),s[o].direction===q.INACTIVE&&(yield this.setTransceiverDirection(q.SENDONLY,[o]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(e){return f(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?h.AUXILIARY:h.MAIN} stream`),kt()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return f(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 n=t?3:1;yield s[n].sender.replaceTrack(null),n===1&&this._room.videoManager.hasSmall&&(yield s[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(q.INACTIVE,[n])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return f(this,null,function*(){if(!te)return;let s=!1,n=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let o=this._peerConnection.getTransceivers();if(t.forEach(d=>{o[d].direction!==e&&(o[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
|
|
`).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 n=!0,`a=${e}`;if(e===q.SENDONLY&&d.includes(`a=${q.INACTIVE}`))return n=!0,`a=${q.RECVONLY}`}return d}).join(`\r
|
|
`);n&&(this._log.info("updating answer"),yield this._peerConnection.setRemoteDescription({type:"answer",sdp:c}))})}replaceTrack(e){return f(this,null,function*(){var o;let t=(o=this._peerConnection)==null?void 0:o.getSenders(),s=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!s||t.find(a=>a.track===s))return!1;let n=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${s.kind} track ${s.id} on ${n?h.AUXILIARY:h.MAIN} stream`),s.kind===h.AUDIO&&t[0]&&(yield t[0].replaceTrack(s)),s.kind===h.VIDEO&&(!n&&t[1]&&(yield t[1].replaceTrack(s)),n&&t[3]&&(yield t[3].replaceTrack(s))),!0})}setBandwidth(n){return f(this,arguments,function*({bandwidth:e,type:t,videoType:s}){if(this.singlePC){let o={};t===h.AUDIO?o.audio=e:s==="big"?o.bigVideo=e:s==="small"?o.smallVideo=e:o.auxVideo=e,yield this.singlePC.setBandwidth(o)}})}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)&&T.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===xi?(this._log.error(Ae.NOT_SUPPORTED_H264ENCODE),new b({code:A.NOT_SUPPORTED_H264,message:k({key:M.NOT_SUPPORTED_H264ENCODE})})):new b({code:A.UNKNOWN,message:k({key:M.SIGNAL_RESPONSE_FAILED,data:{signalResponse:V.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return f(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}))})}},wd=Pd;function Eh(r){return Object.keys(r).filter(i=>r[i])}var Wr=class extends rr{constructor(e){super(w(v({},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 ni(this._room,this),this.remoteVideoTrack=new gt(this._room,this),this.remoteAuxiliaryTrack=new Mr(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,n;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(s=this.remoteVideoTrack)==null||s.onFlagChanged(),(n=this.remoteAuxiliaryTrack)==null||n.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 n,o;let t=this._currentState,s=super.emitConnectionStateChangedEvent(e);return s&&t!==e&&((n=this.remoteVideoTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e}),(o=this.remoteAuxiliaryTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e})),s}onTrack(e){let t=e.streams[0],{track:s,receiver:n}=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.singlePC.enableInsertableStreams&&this.createEncodedStreams(d,n),d.setInputMediaStreamTrack(s)}createEncodedStreams(e,t){if(!this.singlePC.abortMap.has(t)){let s=t.createEncodedStreams(),n=new AbortController,o={abortController:n,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(o.enqueue(c))})):s.readable).pipeTo(s.writable,n).catch(c=>{c!=="destory"&&this._log.warn(c)}),this.singlePC.addAbortController(t,n)}}subscribe(e,t){return f(this,null,function*(){try{if(this._log.info(`subscribe ${t} ${Eh(e)}`),this.hasSSRC){let s="subscribe_change";Object.values(e).find(n=>n===!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,n;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&&((n=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:n.readState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),et&&ht<92)return;this.singlePC.startReconnection()}}unsubscribe(s){return f(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 n=v({},this.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:n.audio=!1;break;case 4:n.video=!1;break;case 8:n.smallVideo=!1;break;case 2:n.auxiliary=!1;break;default:break}});let o="subscribe_change";Object.values(n).find(c=>c===!0)||(o="unsubscribe"),this._log.info(`${o==="unsubscribe"?o:"subscribe"} ${t} [${Eh(n)}]`),o==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(o,n),o==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,t=this.subscribeState){let s={srcTinyId:this.tinyId,srcUserId:this.userId},n=j.UNSUBSCRIBE,o=V.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(s={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},n=j.SUBSCRIBE_CHANGE,o=V.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:n,data:s,responseCommand:o,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let c=new b({code:a.code,message:k({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 f(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:ir(),bigVideoSsrc:ir(),bigVideoRtxSsrc:ir(),auxVideoSsrc:ir(),auxVideoRtxSsrc:ir()},{audioSsrc:n,bigVideoSsrc:o,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:d}=s;this.ssrc={audio:n,video:o,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: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(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 f(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||Kt(e)&&Kt(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,Kt(e)&&(this.remoteAudioTrack.jitterBufferDelay=t)),new Promise(n=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:s,resolve:n})})}doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:s,resolve:n}){let o=-1;try{if(e===0&&t===0)return s.forEach(c=>c.jitterBufferTarget=0),n();if(s.forEach(c=>{var p;let d=c.track===this.remoteAuxiliaryTrack.outMediaTrack||Kt(e)&&c.track===this.remoteAudioTrack.outMediaTrack;if(d&&Kt(t)||!d&&Kt(e))return;let l=d?t||0:e,m=(c.jitterBufferTarget||0)+100;m>l||(c.jitterBufferTarget=m,this._log.debug(`set ${d?"aux ":""}${(p=c==null?void 0:c.track)==null?void 0:p.kind} jitterBuffer delay ${m} -> ${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`),n();o=setTimeout(()=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:s,resolve:n})},1e3)}catch(a){this._log.warn(`set jitterBuffer delay error: ${a}`),clearTimeout(o),n()}}};y([Bt(),W(r=>function(...i){return new Promise((e,t)=>{let s=n=>{this.off("closed",s),t(new b({code:A.API_CALL_ABORTED,message:k({key:M.CONNECTION_ABORTED,data:n})}))};this.on("closed",s),r.apply(this,i).then(e,t).finally(()=>{this.off("closed",s)})})})],Wr.prototype,"subscribe",1),y([Bt()],Wr.prototype,"unsubscribe",1),y([si(()=>"jitter")],Wr.prototype,"setJitterBufferDelay",1);var gh=Wr;function Th(){return W(r=>function(...i){return f(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(t=>t.outMediaTrack&&t.state==="capture"),!i.length))return;T.emit("61",{room:this});let e=r.apply(this,i);return i.forEach(t=>t.publish(this,e)),e})})}function Sh(){return W(r=>function(...i){let e=r.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var Ih=Se(Ne());function Wf(){return Math.floor(Math.random()*16383)}var Vd=class extends Ih.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=S.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)||Wf(),n={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,n)}onReceiveMsg(e){let{data:t}=e.data,s=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(s){let n={userId:s,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),o=>o.charCodeAt(0)).buffer};if(t.ordered){let o=`${s}_${n.cmdId}`,a=this.messageMap.get(o);if(!a||Math.abs(a.lastSeq-n.seq)>Vd.SEQ_INTERVAL)this.messageMap.set(o,{lastSeq:n.seq,cachedMessageMap:new Map}),this.emitMessage(n);else if(n.seq>a.lastSeq){if(n.seq===a.lastSeq+1)this.emitMessage(n);else if(!a.cachedMessageMap.has(n.seq)){let c=setTimeout(()=>this.emitMessage(n,!0),5e3);a.cachedMessageMap.set(n.seq,{message:n,timeoutId:c})}}else this.log.debug(`drop message ${n.userId}-${n.cmdId}-${n.seq}`)}else this.emit("message",n)}}emitMessage(e,t=!1){var a;let s=this.messageMap.get(`${e.userId}_${e.cmdId}`),n=e;if(s){if(t){let c=[...s.cachedMessageMap.values()].sort((d,l)=>d.message.seq-l.message.seq);c[0]&&(n=c[0].message)}n.seq-s.lastSeq>1&&this.log.debug(`msg lost userId: ${n.userId} seq: ${s.lastSeq} -> ${n.seq}`),s.lastSeq=n.seq,clearTimeout((a=s.cachedMessageMap.get(n.seq))==null?void 0:a.timeoutId),s.cachedMessageMap.delete(n.seq)}this.emit("message",n);let o=s==null?void 0:s.cachedMessageMap.get(n.seq+1);o&&this.emitMessage(o.message)}},un=Vd;u(un,"SEQ_INTERVAL",300);var{isString:Ah,isUndefined:Jr,getNetworkType:Jf,isEmpty:ln}=Pe,It=class extends ia{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=Rr;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 sn(this,this._log),this.userManager=new xo(this.userId,this._log),this._version=Re,this.sdpSemantics=nr,Jr(e.sdpSemantics)?ii.isUnifiedPlanDefault()&&(this.sdpSemantics=pi):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${Jf()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=Jr(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&Rr,!Jr(e.enableSPC)&&Rr&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new lh(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 f(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",n=>{this.emit("peer-join",n)}),this.userManager.on("2",n=>{this.closeDownLinkConnection(n,"remote user exitRoom"),this.emit("peer-leave",n)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",o=>{var n=Fd(o,[]);T.emit(E.REMOTE_PUBLISH_STATE_CHANGED,v({room:this},n)),this.emit("remote-publish-state-changed",v({},n))}),this.joinParams=e,new Promise((n,o)=>f(this,null,function*(){var a,c;this._joinReject=o;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(d){if(d instanceof b&&d.code===A.SPC_INITIALIZED_FAILED)(a=this.signalChannel)==null||a.destroy(),yield this.initialize();else return o(d)}yield this.doJoin(e,(c=this.singlePC)==null?void 0:c.clientAbility),n(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(d){o(d)}this._joinReject=null}))})}initSinglePC(){return f(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,n)=>f(this,null,function*(){var c,d,l;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(fe.SETUP_FAILED,m=>{this.clearJoinTimeout(),T.emit(E.JOIN_SIGNAL_CONNECTION_END,{room:this,error:m}),n(m)}),pe((d=(c=this.scheduleResult)==null?void 0:c.config)==null?void 0:d.singlePC)&&Rr&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2);let o={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:La(),netType:Ir(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig};this._log.debug(`join room signal data: ${JSON.stringify(o)}`);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(()=>{n(new b({code:A.JOIN_ROOM_FAILED,message:k({key:M.JOIN_ROOM_TIMEOUT})}))},a),T.emit(E.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?j.SPC_JOIN_ROOM:j.JOIN_ROOM,o),this.signalChannel.once(V.JOIN_ROOM_RESULT,m=>{this.clearJoinTimeout();let{code:p,message:_,data:R,tinyId:C}=m.data;T.emit(E.JOIN_RECEIVED_CMD_RES,{room:this,code:p}),p===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: ${p} error: ${_}`),n(new b({code:A.JOIN_ROOM_FAILED,extraCode:p,message:k({key:M.JOIN_ROOM_FAILED,data:{error:_,code:p}})})))})}))}reJoin(e=!0){return f(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(n=>(t=n,n)))),this.signalChannel&&(this.signalChannel.race=e,this.signalChannel.close(),s.push(this.signalChannel.connect())),yield Promise.all(s),yield this.doJoin(w(v({},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:we.REJOIN}),this.singlePC){let n=o=>{var a;o.state==="CONNECTED"&&((a=this.singlePC)==null||a.off(Gt.CONNECTION_STATE_CHANGED,n),this.uplinkConnection instanceof wd&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(c=>{c.installEvents(),c.onSinglePCReconnected()}))};this.singlePC.on(Gt.CONNECTION_STATE_CHANGED,n),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof rn&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(t){this._log.warn(`reJoin fail ${t}`),this.reset(),Z.logFailedEvent({userId:this.userId,eventType:we.REJOIN,error:t}),this.emit("error",new b({code:A.JOIN_ROOM_FAILED,message:k({key:M.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}})}initialize(){return f(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),s=this.signalChannel||Bl(this.userId),n=!!(s&&s.isConnected&&s.keepAlive),o;return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(o=this.scheduleResult.domains[0]),this._log.info(`${n?"reuse":"setup"} signal channel`),n?(s.url=e,s.backupUrl=t,s.room=this,this.signalChannel=s):(this.signalChannel=new $r({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?o:void 0}),this._customMessageManager=new un(this,this.signalChannel),this._customMessageManager.on("message",a=>{this.emit("custom-message",a)})),this._networkQuality||(this._networkQuality=new er({signalChannel:this.signalChannel,room:this}),this._networkQuality.on(er.EVENT_NETWORK_QUALITY,a=>{this.emit("network-quality",a)})),De(this,this.signalChannel).add(fe.CONNECTION_STATE_CHANGED,a=>{T.emit(E.SIGNAL_CONNECTION_STATE_CHANGED,v({room:this},a)),this.emit("signal-connection-state-changed",a)}).add(fe.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(fe.SETUP_SUCCESS,a=>{this.tinyId=a.signalInfo.tinyId,T.emit(E.JOIN_SIGNAL_CONNECTION_END,{room:this})}),T.emit(E.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),n&&T.emit(E.JOIN_SIGNAL_CONNECTION_END,{room:this}),n})}setSignalChannel(e){this.signalChannel=e,e||me(this)}leave(){return f(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),T.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(fi,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 f(this,null,function*(){var a;let e=this.badCaseDetector.getMonitorFreeze(),t=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});if(this.badCaseDetector.resetMonitor(),!((a=this.signalChannel)!=null&&a.isConnected))return;let s=this.signalChannel.isConnected?ml(this.userId):[],n=w(v({str_sdk_version:Yr,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:v({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:Ir()},t.msg_device_info)});this.heartbeatReport=n,T.emit(E.HEARTBEAT_REPORT,{room:this,report:n}),this.signalChannel.send(j.ON_QUALITY_REPORT,n),this.emit("heartbeat-report",w(v({},n),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}));let o=Date.now();this._lastHeartBeatTime>0&&o-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${o-this._lastHeartBeatTime}`),this.signalChannel.isConnected&&(this._lastHeartBeatTime=o),!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.map(({userId:s,srcTinyId:n,flag:o})=>{s===this.userId&&this.uplinkConnection&&(this.uplinkConnection.flag=o);let a=this.remotePublishedUserMap.get(s);return a&&this.checkSubscribeBigSmallVideo(a),{userId:s,tinyId:n,flag:o}});T.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 rn&&(this.uplinkConnection=null)),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:t,flag:s}){let n=new(this.singlePC?gh:Id)({userId:e,tinyId:t,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:s});this.userManager.addRemotePublishedUser(n),this.installDownlinkEvents(n,e),this.emit("remote-published",n)}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 n=s.getCode();n!==A.ICE_TRANSPORT_ERROR&&(n===A.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",s))}),e.on("connection-state-changed",s=>{this.emit("media-connection-state-changed",w(v({},s),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=re.run(fi,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:n}=t;if(s===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:c,role:d})=>({userId:a,tinyId:c,role:d}));throw k({key:M.SIGNAL_RESPONSE_FAILED,data:{signalResponse:V.USER_LIST_RES,code:s,message:n}})}):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||!_d)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 ze&&!s.getIsReconnecting()){let n=s.getPeerConnection();n&&n.connectionState===se.CLOSED&&(this._log.warn(`[${s.getUserId()}] pc is closed but not reconnect`),s.startReconnection())}})}fallbackToMPC(){return f(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 rn({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 Id({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:k({key:M.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy())}switchRole(e){return f(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:n,message:o}=s.data;if(n!==0)throw new b({code:A.SWITCH_ROLE_FAILED,message:k({key:M.SWITCH_ROLE_FAILED,data:{message:o,code:n}})});this.role=e}).catch(s=>{throw s instanceof b&&s.getCode()===A.API_CALL_TIMEOUT&&(s=new b({code:A.SWITCH_ROLE_FAILED,message:k({key:M.SWITCH_ROLE_TIMEOUT})})),this._log.error(s),s})}publish(...e){return f(this,null,function*(){let t={},s={};e.forEach(c=>{c instanceof Oe&&(c instanceof $t?s.audio=c:t.audio=c),c instanceof le&&(c instanceof Xe&&c.mediaType===2?s.video=c:t.video=c)});let n=ln(t),o=ln(s);(!n||!o)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new wd({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new rn({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",w(v({},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(",");n||(this._log.info(`publish() => main ${a}`),yield this.uplinkConnection.publish({localAudioTrack:t.audio,localVideoTrack:t.video,isAuxiliary:!1}),this._log.info("main is published")),o||(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 f(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||!this.isMainStreamPublished&&!this.isAuxStreamPublished||!this.uplinkConnection)return;let t={},s={};e.forEach(n=>{!n.mediaTrack||!n.isPublished||(n instanceof Oe&&(n instanceof $t?s.audio=n:t.audio=n),n instanceof le&&(n instanceof Xe&&n.mediaType===2?s.video=n:t.video=n))});try{let n=e.map(o=>o.kind).join(",");ln(t)||(this._log.info(`unpublish() => main ${n}`),yield this.uplinkConnection.unpublish({localAudioTrack:t.audio,localVideoTrack:t.video})),ln(s)||(this._log.info(`unpublish() => aux ${n}`),yield this.uplinkConnection.unpublish({localAudioTrack:s.audio,localVideoTrack:s.video}))}catch(n){}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||!Ya()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{t&&T.emit(E.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return f(this,null,function*(){!this.uplinkConnection||(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return f(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 f(this,null,function*(){if(e=e.filter(o=>!o.isSubscribed),e.length===0)return;let{userId:t}=e[0],s=this.remotePublishedUserMap.get(t);if(!s)return;let n=e.find(o=>o.mediaType===2)?"auxiliary":"main";try{let o=v({},s.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:o.audio=!0;break;case 4:o.video=!0;break;case 8:o.smallVideo=!0;break;case 2:o.auxiliary=!0;break}});let a=this._changeBigSmallRecords.get(t);a&&a.options.smallVideo&&s.muteState.hasSmall&&o.video&&(o.video=!1,o.smallVideo=!0),T.emit(E.SUBSCRIBE_START,{room:this,streamType:n,remotePublishedUser:s,subscribeState:o}),this._log.info(`subscribe() => ${t} ${n} [${zo(o)}] prev: [${zo(s.subscribeState)}]`),yield s.subscribe(o,n),this._log.info(`subscribe ${t} ${n} done`);for(let c of e)c.mediaTrack||(yield c.waitHasMediaTrack());T.emit(E.SUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:s})}catch(o){let a=o instanceof b?o.getCode():A.UNKNOWN,c=o;throw o instanceof b?a===A.REMOTE_STREAM_NOT_EXIST&&(c=new b({code:A.API_CALL_ABORTED,message:k({key:M.API_CALL_ABORTED,data:{message:o.message,userId:t,streamType:n}})}),this._log.warn(c)):(c=new b({code:a,message:k({key:M.SUBSCRIBE_FAILED,data:{message:o.message,userId:t,streamType:n}})}),this._log.error(c)),c}})}unsubscribe(...e){return f(this,null,function*(){let{userId:t}=e[0],s=this.remotePublishedUserMap.get(t);if(!s)return;let n=e.find(o=>o.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${t} ${n}`);try{yield s.unsubscribe({remoteTracks:e,streamType:n})}catch(o){this._log.warn(`unsubscribe() => failed ${o}`)}e.forEach(o=>{o.unsubscribe(),o.mediaType===8&&o.setMediaType(4)}),T.emit(E.UNSUBSCRIBE_SUCCESS,{room:this,streamType:n,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)),T.emit(E.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&re.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=re.run(ss,()=>{var n;let s=[];(n=this.remotePublishedUserMap)==null||n.forEach(o=>{if(o.muteState.hasAudio){let a=Math.floor(o.remoteAudioTrack.getAudioLevel()*100);s.push({userId:o.userId,volume:a})}}),this.emit("audio-volume",s)},{fps:1e3/e,backgroundTask:t})}getLocalAudioStats(){return f(this,null,function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0},this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:t.audio.bytesSent,packetsSent:t.audio.packetsSent}}return e})}getLocalVideoStats(){return f(this,null,function*(){let e={};if(e[this.userId]={bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0},this.uplinkConnection){let{video:{bytesSent:t,packetsSent:s,framesEncoded:n,framesSent:o,frameWidth:a,frameHeight:c}}=yield this._stats.getSenderStats(this.uplinkConnection);e[this.userId]={bytesSent:t,packetsSent:s,framesEncoded:n,framesSent:o,frameWidth:a,frameHeight:c}}return e})}getTransportStats(){return f(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 f(this,null,function*(){let t={};for(let[s,n]of this.remotePublishedUserMap)e==="main"&&n.muteState.hasVideo&&(t[s]=n.remoteVideoTrack.stat),e==="auxiliary"&&n.muteState.hasAuxiliary&&(t[s]=n.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return f(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(n=>s.push(Pe.getTurnServer(n))):Pe.isPlainObject(e)&&s.push(Pe.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=Pe.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 f(this,null,function*(){let{subscribeState:t,userId:s,muteState:{hasSmall:n,hasVideo:o}}=e;if(!n&&!o||!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&&n)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(!n&&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 ${or-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=or}catch(m){this._log.info(`change [${s}] to ${l.smallVideo?"small":"big"} video failed. count ${or-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(s)}})}changeType(e,t){let n={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:or};this._changeBigSmallRecords.set(t.userId,n),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(Ah(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!Jr(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new b({code:A.INVALID_PARAMETER,message:k({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(!Jr(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:k({key:M.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!Jr(e.userDefinePushArgs))if(Ah(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:k({key:M.INVALID_USER_DEFINE_PUSH_ARGS})});ln(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){if(this.singlePC&&!this.singlePC.enableInsertableStreams)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([Od(["left",oe.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"),Ot(!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))}}),xl()],It.prototype,"join",1),y([Od("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),Pl(),go("leave room"),Us({fnName:"publish",validateArgs:!1}),Us({fnName:"unsubscribe",validateArgs:!1})],It.prototype,"leave",1),y([Bt(),Th(),it({settings:{retries:jt,timeout:r=>Mt(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),T.emit(E.PUBLISH_FAILED,{room:this}))}})],It.prototype,"publish",1),y([Us({fnName:"publish"}),sl("api-call"),Bt(),Sh(),yi(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)))})],It.prototype,"unpublish",1),y([si(r=>r.userId)],It.prototype,"replaceTrack",1),y([si((...r)=>r[0].userId),Io(),wl(),it({settings:{retries:jt,timeout:r=>Mt(r)},onError(r,i,e,t){r.message.includes("timeout")?(this._log.warn("subscribe timeout"),i()):(this._log.error(`subscribe failed: ${r}`),e(r),T.emit(E.SUBSCRIBE_FAILED,{room:this,remoteTracks:t}))}})],It.prototype,"subscribe",1),y([Us({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)],It.prototype,"unsubscribe",1);Ks.create=Ks._create.bind(Ks,It);var YP=Ks;export{YP as default};
|