trtc-sdk-v5 5.9.2-beta.14 → 5.9.2-beta.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/plugins/cdn-streaming/package.json +1 -1
- package/plugins/cross-room/package.json +1 -1
- package/plugins/device-detector/package.json +1 -1
- package/plugins/video-decoder/package.json +1 -1
- package/plugins/video-effect/basic-beauty/package.json +1 -1
- package/plugins/video-effect/beauty/package.json +1 -1
- package/plugins/video-effect/virtual-background/package.json +1 -1
- package/plugins/video-effect/watermark/package.json +1 -1
- package/trtc.esm.js +11 -11
- package/trtc.js +1 -1
package/trtc.esm.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var xp=Object.create;var Us=Object.defineProperty,wp=Object.defineProperties,Su=Object.getOwnPropertyDescriptor,Up=Object.getOwnPropertyDescriptors,Vp=Object.getOwnPropertyNames,on=Object.getOwnPropertySymbols,Iu=Object.getPrototypeOf,fd=Object.prototype.hasOwnProperty,Au=Object.prototype.propertyIsEnumerable,Bp=Reflect.get;var Vs=Math.pow,pd=(s,i,e)=>i in s?Us(s,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[i]=e,v=(s,i)=>{for(var e in i||(i={}))fd.call(i,e)&&pd(s,e,i[e]);if(on)for(var e of on(i))Au.call(i,e)&&pd(s,e,i[e]);return s},k=(s,i)=>wp(s,Up(i));var Cu=(s,i)=>{var e={};for(var t in s)fd.call(s,t)&&i.indexOf(t)<0&&(e[t]=s[t]);if(s!=null&&on)for(var t of on(s))i.indexOf(t)<0&&Au.call(s,t)&&(e[t]=s[t]);return e};var di=(s,i)=>()=>(i||s((i={exports:{}}).exports,i),i.exports),ci=(s,i)=>{for(var e in i)Us(s,e,{get:i[e],enumerable:!0})},Fp=(s,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of Vp(i))!fd.call(s,r)&&r!==e&&Us(s,r,{get:()=>i[r],enumerable:!(t=Su(i,r))||t.enumerable});return s};var Pe=(s,i,e)=>(e=s!=null?xp(Iu(s)):{},Fp(i||!s||!s.__esModule?Us(e,"default",{value:s,enumerable:!0}):e,s));var y=(s,i,e,t)=>{for(var r=t>1?void 0:t?Su(i,e):i,o=s.length-1,n;o>=0;o--)(n=s[o])&&(r=(t?n(i,e,r):n(r))||r);return t&&r&&Us(i,e,r),r};var d=(s,i,e)=>pd(s,typeof i!="symbol"?i+"":i,e);var xe=(s,i,e)=>Bp(Iu(s),e,i);var f=(s,i,e)=>new Promise((t,r)=>{var o=c=>{try{a(e.next(c))}catch(l){r(l)}},n=c=>{try{a(e.throw(c))}catch(l){r(l)}},a=c=>c.done?t(c.value):Promise.resolve(c.value).then(o,n);a((e=e.apply(s,i)).next())});var je=di((WT,_d)=>{"use strict";var Hp=Object.prototype.hasOwnProperty,qe="~";function Bs(){}Object.create&&(Bs.prototype=Object.create(null),new Bs().__proto__||(qe=!1));function $p(s,i,e){this.fn=s,this.context=i,this.once=e||!1}function Ru(s,i,e,t,r){if(typeof e!="function")throw new TypeError("The listener must be a function");var o=new $p(e,t||s,r),n=qe?qe+i:i;return s._events[n]?s._events[n].fn?s._events[n]=[s._events[n],o]:s._events[n].push(o):(s._events[n]=o,s._eventsCount++),s}function nn(s,i){--s._eventsCount===0?s._events=new Bs:delete s._events[i]}function Ue(){this._events=new Bs,this._eventsCount=0}Ue.prototype.eventNames=function(){var i=[],e,t;if(this._eventsCount===0)return i;for(t in e=this._events)Hp.call(e,t)&&i.push(qe?t.slice(1):t);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i};Ue.prototype.listeners=function(i){var e=qe?qe+i:i,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,o=t.length,n=new Array(o);r<o;r++)n[r]=t[r].fn;return n};Ue.prototype.listenerCount=function(i){var e=qe?qe+i:i,t=this._events[e];return t?t.fn?1:t.length:0};Ue.prototype.emit=function(i,e,t,r,o,n){var a=qe?qe+i:i;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,h,u;if(c.fn){switch(c.once&&this.removeListener(i,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,t),!0;case 4:return c.fn.call(c.context,e,t,r),!0;case 5:return c.fn.call(c.context,e,t,r,o),!0;case 6:return c.fn.call(c.context,e,t,r,o,n),!0}for(u=1,h=new Array(l-1);u<l;u++)h[u-1]=arguments[u];c.fn.apply(c.context,h)}else{var p=c.length,_;for(u=0;u<p;u++)switch(c[u].once&&this.removeListener(i,c[u].fn,void 0,!0),l){case 1:c[u].fn.call(c[u].context);break;case 2:c[u].fn.call(c[u].context,e);break;case 3:c[u].fn.call(c[u].context,e,t);break;case 4:c[u].fn.call(c[u].context,e,t,r);break;default:if(!h)for(_=1,h=new Array(l-1);_<l;_++)h[_-1]=arguments[_];c[u].fn.apply(c[u].context,h)}}return!0};Ue.prototype.on=function(i,e,t){return Ru(this,i,e,t,!1)};Ue.prototype.once=function(i,e,t){return Ru(this,i,e,t,!0)};Ue.prototype.removeListener=function(i,e,t,r){var o=qe?qe+i:i;if(!this._events[o])return this;if(!e)return nn(this,o),this;var n=this._events[o];if(n.fn)n.fn===e&&(!r||n.once)&&(!t||n.context===t)&&nn(this,o);else{for(var a=0,c=[],l=n.length;a<l;a++)(n[a].fn!==e||r&&!n[a].once||t&&n[a].context!==t)&&c.push(n[a]);c.length?this._events[o]=c.length===1?c[0]:c:nn(this,o)}return this};Ue.prototype.removeAllListeners=function(i){var e;return i?(e=qe?qe+i:i,this._events[e]&&nn(this,e)):(this._events=new Bs,this._eventsCount=0),this};Ue.prototype.off=Ue.prototype.removeListener;Ue.prototype.addListener=Ue.prototype.on;Ue.prefixed=qe;Ue.EventEmitter=Ue;typeof _d!="undefined"&&(_d.exports=Ue)});var pc=di((jE,lh)=>{"use strict";var ch=lh.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(s){return s.encoding?"rtpmap:%d %s/%s/%s":s.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(s){return s.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(s){return s.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(s){return"extmap:%d"+(s.direction?"/%s":"%v")+(s["encrypt-uri"]?" %s":"%v")+" %s"+(s.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(s){return s.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(s){var i="candidate:%s %d %s %d %s %d typ %s";return i+=s.raddr!=null?" raddr %s rport %d":"%v%v",i+=s.tcptype!=null?" tcptype %s":"%v",s.generation!=null&&(i+=" generation %d"),i+=s["network-id"]!=null?" network-id %d":"%v",i+=s["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(s){var i="ssrc:%d";return s.attribute!=null&&(i+=" %s",s.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(s){return s.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(s){return s.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(s){return"imageattr:%s %s %s"+(s.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(s){return"simulcast:%s %s"+(s.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(s){return"ts-refclk:%s"+(s.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(s){var i="mediaclk:";return i+=s.id!=null?"id=%s %s":"%v%s",i+=s.mediaClockValue!=null?"=%s":"",i+=s.rateNumerator!=null?" rate=%s":"",i+=s.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(ch).forEach(function(s){var i=ch[s];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var mh=di(Ii=>{"use strict";var us=function(s){return String(Number(s))===s?Number(s):s},Vf=function(s,i,e,t){if(t&&!e)i[t]=us(s[1]);else for(var r=0;r<e.length;r+=1)s[r+1]!=null&&(i[e[r]]=us(s[r+1]))},Bf=function(s,i,e){var t=s.name&&s.names;s.push&&!i[s.push]?i[s.push]=[]:t&&!i[s.name]&&(i[s.name]={});var r=s.push?{}:t?i[s.name]:i;Vf(e.match(s.reg),r,s.names,s.name),s.push&&i[s.push].push(r)},uh=pc(),Ff=RegExp.prototype.test.bind(/^([a-z])=(.*)/);Ii.parse=function(s){var i={},e=[],t=i;return s.split(/(\r\n|\r|\n)/).filter(Ff).forEach(function(r){var o=r[0],n=r.slice(2);o==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(uh[o]||[]).length;a+=1){var c=uh[o][a];if(c.reg.test(n))return Bf(c,t,n)}}),i.media=e,i};var hh=function(s,i){var e=i.split(/=(.+)/,2);return e.length===2?s[e[0]]=us(e[1]):e.length===1&&i.length>1&&(s[e[0]]=void 0),s};Ii.parseParams=function(s){return s.split(/;\s?/).reduce(hh,{})};Ii.parseFmtpConfig=Ii.parseParams;Ii.parsePayloads=function(s){return s.toString().split(" ").map(Number)};Ii.parseRemoteCandidates=function(s){for(var i=[],e=s.split(" ").map(us),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};Ii.parseImageAttributes=function(s){return s.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(hh,{})})};Ii.parseSimulcastStreamList=function(s){return s.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=us(e):(t=us(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var fh=di((QE,ph)=>{"use strict";var fc=pc(),Hf=/%[sdv%]/g,$f=function(s){var i=1,e=arguments,t=e.length;return s.replace(Hf,function(r){if(i>=t)return r;var o=e[i];switch(i+=1,r){case"%%":return"%";case"%s":return String(o);case"%d":return Number(o);case"%v":return""}})},Eo=function(s,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,r=[s+"="+t];if(i.names)for(var o=0;o<i.names.length;o+=1){var n=i.names[o];i.name?r.push(e[i.name][n]):r.push(e[i.names[o]])}else r.push(e[i.name]);return $f.apply(null,r)},Gf=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Wf=["i","c","b","a"];ph.exports=function(s,i){i=i||{},s.version==null&&(s.version=0),s.name==null&&(s.name=" "),s.media.forEach(function(o){o.payloads==null&&(o.payloads="")});var e=i.outerOrder||Gf,t=i.innerOrder||Wf,r=[];return e.forEach(function(o){fc[o].forEach(function(n){n.name in s&&s[n.name]!=null?r.push(Eo(o,n,s)):n.push in s&&s[n.push]!=null&&s[n.push].forEach(function(a){r.push(Eo(o,n,a))})})}),s.media.forEach(function(o){r.push(Eo("m",fc.m[0],o)),t.forEach(function(n){fc[n].forEach(function(a){a.name in o&&o[a.name]!=null?r.push(Eo(n,a,o)):a.push in o&&o[a.push]!=null&&o[a.push].forEach(function(c){r.push(Eo(n,a,c))})})})}),r.join(`\r
|
|
1
|
+
var xp=Object.create;var Us=Object.defineProperty,wp=Object.defineProperties,Su=Object.getOwnPropertyDescriptor,Up=Object.getOwnPropertyDescriptors,Vp=Object.getOwnPropertyNames,on=Object.getOwnPropertySymbols,Iu=Object.getPrototypeOf,fd=Object.prototype.hasOwnProperty,Au=Object.prototype.propertyIsEnumerable,Bp=Reflect.get;var Vs=Math.pow,pd=(s,i,e)=>i in s?Us(s,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[i]=e,v=(s,i)=>{for(var e in i||(i={}))fd.call(i,e)&&pd(s,e,i[e]);if(on)for(var e of on(i))Au.call(i,e)&&pd(s,e,i[e]);return s},k=(s,i)=>wp(s,Up(i));var Cu=(s,i)=>{var e={};for(var t in s)fd.call(s,t)&&i.indexOf(t)<0&&(e[t]=s[t]);if(s!=null&&on)for(var t of on(s))i.indexOf(t)<0&&Au.call(s,t)&&(e[t]=s[t]);return e};var di=(s,i)=>()=>(i||s((i={exports:{}}).exports,i),i.exports),ci=(s,i)=>{for(var e in i)Us(s,e,{get:i[e],enumerable:!0})},Fp=(s,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of Vp(i))!fd.call(s,r)&&r!==e&&Us(s,r,{get:()=>i[r],enumerable:!(t=Su(i,r))||t.enumerable});return s};var Pe=(s,i,e)=>(e=s!=null?xp(Iu(s)):{},Fp(i||!s||!s.__esModule?Us(e,"default",{value:s,enumerable:!0}):e,s));var y=(s,i,e,t)=>{for(var r=t>1?void 0:t?Su(i,e):i,o=s.length-1,n;o>=0;o--)(n=s[o])&&(r=(t?n(i,e,r):n(r))||r);return t&&r&&Us(i,e,r),r};var d=(s,i,e)=>pd(s,typeof i!="symbol"?i+"":i,e);var xe=(s,i,e)=>Bp(Iu(s),e,i);var f=(s,i,e)=>new Promise((t,r)=>{var o=c=>{try{a(e.next(c))}catch(l){r(l)}},n=c=>{try{a(e.throw(c))}catch(l){r(l)}},a=c=>c.done?t(c.value):Promise.resolve(c.value).then(o,n);a((e=e.apply(s,i)).next())});var je=di((WT,_d)=>{"use strict";var Hp=Object.prototype.hasOwnProperty,qe="~";function Bs(){}Object.create&&(Bs.prototype=Object.create(null),new Bs().__proto__||(qe=!1));function $p(s,i,e){this.fn=s,this.context=i,this.once=e||!1}function Ru(s,i,e,t,r){if(typeof e!="function")throw new TypeError("The listener must be a function");var o=new $p(e,t||s,r),n=qe?qe+i:i;return s._events[n]?s._events[n].fn?s._events[n]=[s._events[n],o]:s._events[n].push(o):(s._events[n]=o,s._eventsCount++),s}function nn(s,i){--s._eventsCount===0?s._events=new Bs:delete s._events[i]}function Ve(){this._events=new Bs,this._eventsCount=0}Ve.prototype.eventNames=function(){var i=[],e,t;if(this._eventsCount===0)return i;for(t in e=this._events)Hp.call(e,t)&&i.push(qe?t.slice(1):t);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i};Ve.prototype.listeners=function(i){var e=qe?qe+i:i,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,o=t.length,n=new Array(o);r<o;r++)n[r]=t[r].fn;return n};Ve.prototype.listenerCount=function(i){var e=qe?qe+i:i,t=this._events[e];return t?t.fn?1:t.length:0};Ve.prototype.emit=function(i,e,t,r,o,n){var a=qe?qe+i:i;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,h,u;if(c.fn){switch(c.once&&this.removeListener(i,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,e),!0;case 3:return c.fn.call(c.context,e,t),!0;case 4:return c.fn.call(c.context,e,t,r),!0;case 5:return c.fn.call(c.context,e,t,r,o),!0;case 6:return c.fn.call(c.context,e,t,r,o,n),!0}for(u=1,h=new Array(l-1);u<l;u++)h[u-1]=arguments[u];c.fn.apply(c.context,h)}else{var p=c.length,_;for(u=0;u<p;u++)switch(c[u].once&&this.removeListener(i,c[u].fn,void 0,!0),l){case 1:c[u].fn.call(c[u].context);break;case 2:c[u].fn.call(c[u].context,e);break;case 3:c[u].fn.call(c[u].context,e,t);break;case 4:c[u].fn.call(c[u].context,e,t,r);break;default:if(!h)for(_=1,h=new Array(l-1);_<l;_++)h[_-1]=arguments[_];c[u].fn.apply(c[u].context,h)}}return!0};Ve.prototype.on=function(i,e,t){return Ru(this,i,e,t,!1)};Ve.prototype.once=function(i,e,t){return Ru(this,i,e,t,!0)};Ve.prototype.removeListener=function(i,e,t,r){var o=qe?qe+i:i;if(!this._events[o])return this;if(!e)return nn(this,o),this;var n=this._events[o];if(n.fn)n.fn===e&&(!r||n.once)&&(!t||n.context===t)&&nn(this,o);else{for(var a=0,c=[],l=n.length;a<l;a++)(n[a].fn!==e||r&&!n[a].once||t&&n[a].context!==t)&&c.push(n[a]);c.length?this._events[o]=c.length===1?c[0]:c:nn(this,o)}return this};Ve.prototype.removeAllListeners=function(i){var e;return i?(e=qe?qe+i:i,this._events[e]&&nn(this,e)):(this._events=new Bs,this._eventsCount=0),this};Ve.prototype.off=Ve.prototype.removeListener;Ve.prototype.addListener=Ve.prototype.on;Ve.prefixed=qe;Ve.EventEmitter=Ve;typeof _d!="undefined"&&(_d.exports=Ve)});var pc=di((jE,lh)=>{"use strict";var ch=lh.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(s){return s.encoding?"rtpmap:%d %s/%s/%s":s.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(s){return s.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(s){return s.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(s){return"extmap:%d"+(s.direction?"/%s":"%v")+(s["encrypt-uri"]?" %s":"%v")+" %s"+(s.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(s){return s.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(s){var i="candidate:%s %d %s %d %s %d typ %s";return i+=s.raddr!=null?" raddr %s rport %d":"%v%v",i+=s.tcptype!=null?" tcptype %s":"%v",s.generation!=null&&(i+=" generation %d"),i+=s["network-id"]!=null?" network-id %d":"%v",i+=s["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(s){var i="ssrc:%d";return s.attribute!=null&&(i+=" %s",s.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(s){return s.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(s){return s.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(s){return"imageattr:%s %s %s"+(s.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(s){return"simulcast:%s %s"+(s.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(s){return"ts-refclk:%s"+(s.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(s){var i="mediaclk:";return i+=s.id!=null?"id=%s %s":"%v%s",i+=s.mediaClockValue!=null?"=%s":"",i+=s.rateNumerator!=null?" rate=%s":"",i+=s.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(ch).forEach(function(s){var i=ch[s];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var mh=di(Ii=>{"use strict";var us=function(s){return String(Number(s))===s?Number(s):s},Vf=function(s,i,e,t){if(t&&!e)i[t]=us(s[1]);else for(var r=0;r<e.length;r+=1)s[r+1]!=null&&(i[e[r]]=us(s[r+1]))},Bf=function(s,i,e){var t=s.name&&s.names;s.push&&!i[s.push]?i[s.push]=[]:t&&!i[s.name]&&(i[s.name]={});var r=s.push?{}:t?i[s.name]:i;Vf(e.match(s.reg),r,s.names,s.name),s.push&&i[s.push].push(r)},uh=pc(),Ff=RegExp.prototype.test.bind(/^([a-z])=(.*)/);Ii.parse=function(s){var i={},e=[],t=i;return s.split(/(\r\n|\r|\n)/).filter(Ff).forEach(function(r){var o=r[0],n=r.slice(2);o==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(uh[o]||[]).length;a+=1){var c=uh[o][a];if(c.reg.test(n))return Bf(c,t,n)}}),i.media=e,i};var hh=function(s,i){var e=i.split(/=(.+)/,2);return e.length===2?s[e[0]]=us(e[1]):e.length===1&&i.length>1&&(s[e[0]]=void 0),s};Ii.parseParams=function(s){return s.split(/;\s?/).reduce(hh,{})};Ii.parseFmtpConfig=Ii.parseParams;Ii.parsePayloads=function(s){return s.toString().split(" ").map(Number)};Ii.parseRemoteCandidates=function(s){for(var i=[],e=s.split(" ").map(us),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};Ii.parseImageAttributes=function(s){return s.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(hh,{})})};Ii.parseSimulcastStreamList=function(s){return s.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=us(e):(t=us(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var fh=di((QE,ph)=>{"use strict";var fc=pc(),Hf=/%[sdv%]/g,$f=function(s){var i=1,e=arguments,t=e.length;return s.replace(Hf,function(r){if(i>=t)return r;var o=e[i];switch(i+=1,r){case"%%":return"%";case"%s":return String(o);case"%d":return Number(o);case"%v":return""}})},Eo=function(s,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,r=[s+"="+t];if(i.names)for(var o=0;o<i.names.length;o+=1){var n=i.names[o];i.name?r.push(e[i.name][n]):r.push(e[i.names[o]])}else r.push(e[i.name]);return $f.apply(null,r)},Gf=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Wf=["i","c","b","a"];ph.exports=function(s,i){i=i||{},s.version==null&&(s.version=0),s.name==null&&(s.name=" "),s.media.forEach(function(o){o.payloads==null&&(o.payloads="")});var e=i.outerOrder||Gf,t=i.innerOrder||Wf,r=[];return e.forEach(function(o){fc[o].forEach(function(n){n.name in s&&s[n.name]!=null?r.push(Eo(o,n,s)):n.push in s&&s[n.push]!=null&&s[n.push].forEach(function(a){r.push(Eo(o,n,a))})})}),s.media.forEach(function(o){r.push(Eo("m",fc.m[0],o)),t.forEach(function(n){fc[n].forEach(function(a){a.name in o&&o[a.name]!=null?r.push(Eo(n,a,o)):a.push in o&&o[a.push]!=null&&o[a.push].forEach(function(c){r.push(Eo(n,a,c))})})})}),r.join(`\r
|
|
2
2
|
`)+`\r
|
|
3
3
|
`}});var _h=di(Ai=>{"use strict";var Tr=mh(),Jf=fh();Ai.write=Jf;Ai.parse=Tr.parse;Ai.parseParams=Tr.parseParams;Ai.parseFmtpConfig=Tr.parseFmtpConfig;Ai.parsePayloads=Tr.parsePayloads;Ai.parseRemoteCandidates=Tr.parseRemoteCandidates;Ai.parseImageAttributes=Tr.parseImageAttributes;Ai.parseSimulcastStreamList=Tr.parseSimulcastStreamList});var ru=di((px,Wm)=>{"use strict";var Gm=Wm.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(s){return s.encoding?"rtpmap:%d %s/%s/%s":s.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(s){return s.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(s){return s.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(s){return"extmap:%d"+(s.direction?"/%s":"%v")+(s["encrypt-uri"]?" %s":"%v")+" %s"+(s.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(s){return s.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(s){var i="candidate:%s %d %s %d %s %d typ %s";return i+=s.raddr!=null?" raddr %s rport %d":"%v%v",i+=s.tcptype!=null?" tcptype %s":"%v",s.generation!=null&&(i+=" generation %d"),i+=s["network-id"]!=null?" network-id %d":"%v",i+=s["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(s){var i="ssrc:%d";return s.attribute!=null&&(i+=" %s",s.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(s){return s.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(s){return s.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(s){return"imageattr:%s %s %s"+(s.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(s){return"simulcast:%s %s"+(s.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(s){return"ts-refclk:%s"+(s.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(s){var i="mediaclk:";return i+=s.id!=null?"id=%s %s":"%v%s",i+=s.mediaClockValue!=null?"=%s":"",i+=s.rateNumerator!=null?" rate=%s":"",i+=s.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(Gm).forEach(function(s){var i=Gm[s];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var jm=di(Vi=>{"use strict";var ks=function(s){return String(Number(s))===s?Number(s):s},gT=function(s,i,e,t){if(t&&!e)i[t]=ks(s[1]);else for(var r=0;r<e.length;r+=1)s[r+1]!=null&&(i[e[r]]=ks(s[r+1]))},TT=function(s,i,e){var t=s.name&&s.names;s.push&&!i[s.push]?i[s.push]=[]:t&&!i[s.name]&&(i[s.name]={});var r=s.push?{}:t?i[s.name]:i;gT(e.match(s.reg),r,s.names,s.name),s.push&&i[s.push].push(r)},Jm=ru(),ET=RegExp.prototype.test.bind(/^([a-z])=(.*)/);Vi.parse=function(s){var i={},e=[],t=i;return s.split(/(\r\n|\r|\n)/).filter(ET).forEach(function(r){var o=r[0],n=r.slice(2);o==="m"&&(e.push({rtp:[],fmtp:[]}),t=e[e.length-1]);for(var a=0;a<(Jm[o]||[]).length;a+=1){var c=Jm[o][a];if(c.reg.test(n))return TT(c,t,n)}}),i.media=e,i};var qm=function(s,i){var e=i.split(/=(.+)/,2);return e.length===2?s[e[0]]=ks(e[1]):e.length===1&&i.length>1&&(s[e[0]]=void 0),s};Vi.parseParams=function(s){return s.split(/;\s?/).reduce(qm,{})};Vi.parseFmtpConfig=Vi.parseParams;Vi.parsePayloads=function(s){return s.toString().split(" ").map(Number)};Vi.parseRemoteCandidates=function(s){for(var i=[],e=s.split(" ").map(ks),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};Vi.parseImageAttributes=function(s){return s.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(qm,{})})};Vi.parseSimulcastStreamList=function(s){return s.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=ks(e):(t=ks(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var Qm=di((_x,Xm)=>{"use strict";var su=ru(),ST=/%[sdv%]/g,IT=function(s){var i=1,e=arguments,t=e.length;return s.replace(ST,function(r){if(i>=t)return r;var o=e[i];switch(i+=1,r){case"%%":return"%";case"%s":return String(o);case"%d":return Number(o);case"%v":return""}})},zo=function(s,i,e){var t=i.format instanceof Function?i.format(i.push?e:e[i.name]):i.format,r=[s+"="+t];if(i.names)for(var o=0;o<i.names.length;o+=1){var n=i.names[o];i.name?r.push(e[i.name][n]):r.push(e[i.names[o]])}else r.push(e[i.name]);return IT.apply(null,r)},AT=["v","o","s","i","u","e","p","c","b","t","r","z","a"],CT=["i","c","b","a"];Xm.exports=function(s,i){i=i||{},s.version==null&&(s.version=0),s.name==null&&(s.name=" "),s.media.forEach(function(o){o.payloads==null&&(o.payloads="")});var e=i.outerOrder||AT,t=i.innerOrder||CT,r=[];return e.forEach(function(o){su[o].forEach(function(n){n.name in s&&s[n.name]!=null?r.push(zo(o,n,s)):n.push in s&&s[n.push]!=null&&s[n.push].forEach(function(a){r.push(zo(o,n,a))})})}),s.media.forEach(function(o){r.push(zo("m",su.m[0],o)),t.forEach(function(n){su[n].forEach(function(a){a.name in o&&o[a.name]!=null?r.push(zo(n,a,o)):a.push in o&&o[a.push]!=null&&o[a.push].forEach(function(c){r.push(zo(n,a,c))})})})}),r.join(`\r
|
|
4
4
|
`)+`\r
|
|
5
|
-
`}});var ou=di(Bi=>{"use strict";var wr=jm(),RT=Qm();Bi.write=RT;Bi.parse=wr.parse;Bi.parseParams=wr.parseParams;Bi.parseFmtpConfig=wr.parseFmtpConfig;Bi.parsePayloads=wr.parsePayloads;Bi.parseRemoteCandidates=wr.parseRemoteCandidates;Bi.parseImageAttributes=wr.parseImageAttributes;Bi.parseSimulcastStreamList=wr.parseSimulcastStreamList});import e1 from"webrtc-adapter";var xm=Pe(je());var yu=(x=>(x[x.INVALID_PARAMETER=4096]="INVALID_PARAMETER",x[x.INVALID_OPERATION=4097]="INVALID_OPERATION",x[x.NOT_SUPPORTED=4098]="NOT_SUPPORTED",x[x.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",x[x.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",x[x.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",x[x.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",x[x.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",x[x.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",x[x.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",x[x.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",x[x.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",x[x.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",x[x.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",x[x.CLIENT_BANNED=16448]="CLIENT_BANNED",x[x.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",x[x.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",x[x.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",x[x.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",x[x.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",x[x.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",x[x.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",x[x.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",x[x.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",x[x.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",x[x.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",x[x.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",x[x.API_CALL_ABORTED=16461]="API_CALL_ABORTED",x[x.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",x[x.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",x[x.UNKNOWN=65535]="UNKNOWN",x))(yu||{}),S=yu;var Gp=function(s){for(let i in S)if(S[i]===s)return i;return"UNKNOWN"},gd=class extends Error{constructor({name:e="RtcError",message:t,code:r=S.UNKNOWN,extraCode:o=0,constraint:n}){let a=`<${Gp(r)} 0x${r.toString(16)}>`,c=`${t}${n?` constraint: ${n}`:""}${t!=null&&t.includes(a)?"":` ${a}`}`;super(c);d(this,"code");d(this,"extraCode");d(this,"message");d(this,"originMessage");d(this,"name");d(this,"constraint");this.code=r,this.extraCode=o,this.name=e,this.message=c,this.constraint=n,this.originMessage=t}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},b=gd;var bu=new Date().getTime(),Td=0,Nu=function(s){bu=s,Td=bu-new Date().getTime();let i=new Date;i.setTime(s),C.info(`baseTime from server: ${i} offset: ${Td}`)},Fs=function(){return new Date().getTime()+Td},an=function(){let s=new Date;return s.setTime(Fs()),s.toLocaleString()};var nt={};ci(nt,{bytes2ms:()=>xu,convertObjectNumberToInt:()=>Zs,copyProperties:()=>Pu,deepClone:()=>lr,deepMerge:()=>Gt,delay:()=>fi,fibonacci:()=>hr,formatedTime:()=>Gu,getConstructorName:()=>Ys,getContainerFromElement:()=>$u,getEnv:()=>Mu,getInternalVersion:()=>Fu,getLoggerUrl:()=>mi,getMuteStateFromFlag:()=>pi,getNetworkType:()=>Ld,getNumNetworkType:()=>ur,getReconnectionTimeout:()=>yt,getStringByteLength:()=>Ks,getTurnServer:()=>Hu,getUint32Version:()=>In,getValueType:()=>Ae,getViewListFromView:()=>zr,glog:()=>wd,ipv4ToUint32:()=>Qr,isArray:()=>Te,isAudioWorkletSupported:()=>Bu,isBoolean:()=>me,isConstructor:()=>qr,isEmpty:()=>Xr,isFunction:()=>oe,isLangChinese:()=>Rt,isMediaStreamTrack:()=>Uu,isNumber:()=>Y,isObject:()=>$t,isOverseaSdkAppId:()=>zs,isPlainObject:()=>Ze,isPortrait:()=>Sn,isPromise:()=>Wi,isRemoteTrack:()=>Vu,isString:()=>K,isUndefined:()=>g,loadImage:()=>Yr,ms2bytes:()=>wu,ms2samples:()=>xd,performanceNow:()=>L,promiseAny:()=>jr,samples2ms:()=>Pd,setNetworkType:()=>Tn,stringify:()=>ft,stringifyIncludeValue:()=>En,throttlePromise:()=>An});var Md={};ci(Md,{AUDIO_MUTE_BIT:()=>pn,AUDIO_STAT_BIT:()=>$i,AUX_STAT_BIT:()=>ar,AUX_STREAM_MSID:()=>Rd,BACKEND_ENV:()=>mn,BASE_DOC_URL:()=>Ft,BASE_HOST:()=>vu,CAPABILITIES_KEYS:()=>gn,CLASS_NAME:()=>hf,CLOUD_CONSOLE_URL:()=>jp,CROSS_ROOM_BIT:()=>Cd,DATA_FREEZE_TIMING:()=>_n,DEFAULT_ASSETS_URL:()=>dn,DOC_URL:()=>Xp,DTLS_STATE_UNKNOWN:()=>Ct,ENV_NAME:()=>li,EXCHANGE_SDP_TIMEOUT:()=>Dd,IS_WORKER:()=>$r,IS_WORKLET:()=>$s,KIBANA_EVENT:()=>Ke,LOCAL_STREAM_PUBLISH_STATE:()=>Ou,LOGGER_CMD_TYPE:()=>Fi,LOGGER_DOMAIN:()=>Sd,LOGGER_DOMAIN_OVERSEA:()=>Id,LOG_LEVEL:()=>At,LOG_LEVEL_NAME:()=>pf,MAIN_STREAM_MSID:()=>Js,MAX_RTT:()=>Xs,MICROPHONE_COMMUNICATIONS:()=>mf,MICROPHONE_DEFAULT:()=>cr,MUTE_ALL_BIT:()=>Yp,NAME:()=>m,NETWORK_TYPE:()=>cn,NOT_SUPPORTED_H264:()=>dr,PAUSED_RETRY_COUNT:()=>Od,PEERCONNECTION_CONNECTING_TIMEOUT:()=>qs,PEER_CONNECTION_STATE:()=>ce,PEER_LEAVE_REASON:()=>kd,RECOVER_CAPTURE_INTERVAL:()=>Jr,REMOTE_STREAM_TYPE_AUX:()=>bd,REMOTE_STREAM_TYPE_MAIN:()=>yd,RENDER_FREEZE_TIMING:()=>df,SCHEDULE_DOMAIN:()=>hi,SCHEDULE_TIMEOUT:()=>uf,SDP_SEMANTICS_PLAN_B:()=>Gr,SDP_SEMANTICS_UNIFIED_PLAN:()=>Gi,SECOND_HOST:()=>Jp,SIGNAL_PING_PONG_INTERVAL:()=>zp,SIGNAL_PING_TIMEOUT:()=>Qp,SIGNAL_RECONNECTION_COUNT:()=>nf,SMALL_STAT_BIT:()=>Ws,SPEAKER_DEFAULT:()=>js,STORAGE_EXPIRES_TIME:()=>ln,STREAM_TYPE_BIG:()=>cf,STREAM_TYPE_SMALL:()=>lf,SUBSCRIBE_SMALL_RETRY_COUNT:()=>Wr,SYNC_USER_LIST_INTERVAL:()=>af,Scene:()=>Ht,THIRD_HOST:()=>qp,TRANSPORT_DIRECTION:()=>z,TRTC_ERROR_ASSISTANCE:()=>Ad,TRTC_QUALITY_BAD:()=>rf,TRTC_QUALITY_DISCONNECTED:()=>of,TRTC_QUALITY_EXCELLENT:()=>Zp,TRTC_QUALITY_GOOD:()=>ef,TRTC_QUALITY_POOR:()=>tf,TRTC_QUALITY_UNKNOWN:()=>Kp,TRTC_QUALITY_VERY_BAD:()=>sf,UPDATE_OFFER_TIMEOUT:()=>vd,VIDEO_MUTE_BIT:()=>fn,VIDEO_STAT_BIT:()=>Hi,audioProfileMap:()=>un,getRetryCount:()=>ui,getScriptDir:()=>Wp,innerVersion:()=>Hs,loggerProxy:()=>Gs,screenProfileMap:()=>hn,setLoggerProxy:()=>nr,setRetryCount:()=>Nd,setVersion:()=>Ed,version:()=>Re,videoProfileMap:()=>pt});var Hs="4.15.00.1600",Re="5.0.0";function Ed(s){Re=s;let[i,e,t]=s.split(".").map(r=>parseInt(r,10));Hs=`${i}.${Math.min(15,e)}.${Math.min(15,t)}.${e.toString().padStart(2,"0")}${t.toString().padStart(2,"0")}`}var $r=typeof importScripts!="undefined",$s=typeof registerProcessor!="undefined",Wp=()=>{let s=$r?self.location.href:document.currentScript.src;return s.substring(0,s.lastIndexOf("/")+1)},Gs="",nr=s=>Gs=s,vu="web.sdk.qcloud.com",Jp="web.sdk.tencent.cn",qp="web.sdk.cloud.tencent.cn",jp="https://console.cloud.tencent.com/trtc",Ft=`https://${vu}/trtc/webrtc/v5/doc`,dn="https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/",Xp=`${Ft}/zh-cn/`,Sd="https://yun.tim.qq.com",Id="https://apisgp.my-imcloud.com",Ad="trtc_error_assistance",Fi={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},li={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},At=(n=>(n[n.TRACE=0]="TRACE",n[n.DEBUG=1]="DEBUG",n[n.INFO=2]="INFO",n[n.WARN=3]="WARN",n[n.ERROR=4]="ERROR",n[n.NONE=5]="NONE",n))(At||{}),Qp=18e3,zp=2e3,cn={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},ln=7*24*3600*1e3,un={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}},pt={"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}},hn={"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}},m={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",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture"},z={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},mn={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Ht=(e=>(e.LIVE="live",e.RTC="rtc",e))(Ht||{}),Hi=1,Ws=2,ar=4,$i=8,pn=64,fn=16,Yp=112,Cd=128,Js="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",Rd="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",yd=m.MAIN,bd=m.AUXILIARY,Kp=0,Zp=1,ef=2,tf=3,rf=4,sf=5,of=6,Ct="unknown",ce={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Du=1/0;function Nd(s){Du=s}function ui(){return Du}var nf=30,Ke={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"},af=1e4,vd=1e4,Dd=1e4,Gi="unified-plan",Gr="plan-b",dr=1028,Ou=(t=>(t[t.UNPUBLISH=-1]="UNPUBLISH",t[t.PUBLISHING=0]="PUBLISHING",t[t.PUBLISHED=1]="PUBLISHED",t))(Ou||{}),_n=500,df=1e3,cf=m.BIG,lf=m.SMALL,qs=10*1e3,hi={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_BACKUP:"intl-schedule.cloud-rtc.com"},uf=2e3,hf={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},Od=5,cr="default",js=cr,mf="communications",pf=Object.keys(At),kd=["normal leave","timeout leave","kick","role change"],Wr=10,Jr=2e3,gn=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],Xs=10*1e3;var Mu=function(){return new URLSearchParams(location.search).get("trtc_env")||""},zs=s=>Number(s)<14e8,mi=function(s,i){let e;Gs?e=Gs:e=zs(s)?Id:Sd;let t=Math.floor(Math.random()*Vs(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${t}&sdkappid=${s}&cmdtype=${i}`},Qs="unknown";function Ld(){if(Qs!=="unknown")return Qs;let{userAgent:s,connection:i}=navigator,e=(s.match(/NetType\/\S+/)||[])[0]||"";e=e.toLowerCase().replace("nettype/",""),e==="3gnet"&&(e="3g");let t=i&&i.type&&i.type.toLowerCase(),r=i&&i.effectiveType&&i.effectiveType.toLowerCase();return r==="slow-2"&&(r="2g"),t&&(Qs=Lu(t,r)),Qs}function Lu(s,i){if(cn[s])return s;switch(s){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function Tn(s){Qs=Lu(s)}function ur(){return cn[Ld()]}function Pu(s,i){for(let e of Reflect.ownKeys(i))if(e!=="constructor"&&e!=="prototype"&&e!=="name"){let t=Object.getOwnPropertyDescriptor(i,e)||"";Object.defineProperty(s,e,t)}return s}function xu(s,i=48e3){return Pd(s/4,i)}function Pd(s,i=48e3){return s*1e3/i}function wu(s,i=48e3){return xd(s,i)*4}function xd(s,i=48e3){return s*i/1e3}var wd=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},Rt=()=>{let s=navigator.language;return s=s.substring(0,2),s==="zh"},Ze=function(s){if(!s||typeof s!="object"||Object.prototype.toString.call(s)!="[object Object]")return!1;let i=Object.getPrototypeOf(s);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 hr(s,i=1,e=1){return s<=1?e:hr(s-1,e,i+e)}function yt(s){return s>8?30*1e3:hr(s)*1e3}function Ae(s){return Reflect.apply(Object.prototype.toString,s,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var oe=s=>typeof s=="function",g=s=>typeof s=="undefined",K=s=>typeof s=="string",Y=s=>typeof s=="number",me=s=>typeof s=="boolean",$t=s=>Ae(s)==="object",Te=s=>Ae(s)==="array",Uu=s=>Ae(s)==="MediaStreamTrack".toLowerCase(),Vu=s=>s.isRemote,Wi=s=>Ae(s)==="promise",qr=s=>oe(s)&&s.prototype.constructor===s,Ys=s=>qr(s)?s.prototype.constructor.name:"",Bu=typeof AudioWorkletNode!="undefined";function jr(s){return new Promise((i,e)=>{let t=[];s.forEach(r=>{r.then(i).catch(o=>{t.push(o),t.length===s.length&&e(t)})})})}function L(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var ku=s=>+s<10?`0${s}`:s,Fu=s=>{let i=s.match(/^\d+\.\d+\.\d+/)[0];if(!i)return s;let e=i.split("."),t=ku(e[1])+ku(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${t}`},ff=Object.prototype.hasOwnProperty,{toString:eE}=Object.prototype;function Xr(s){if(s==null)return!0;if(typeof s=="boolean")return!1;if(typeof s=="number")return s===0;if(typeof s=="string"||typeof s=="function"||Array.isArray(s))return s.length===0;if(s instanceof Error)return s.message==="";if(Ze(s))switch(Object.prototype.toString.call(s)){case"[object File]":case"[object Map]":case"[object Set]":return s.size===0;case"[object Object]":{for(let i in s)if(ff.call(s,i))return!1;return!0}}return!1}function pi(s,i){return{userId:i,hasAudio:!!(s&$i),hasVideo:!!(s&Hi),hasAuxiliary:!!(s&ar),hasSmall:!!(s&Ws),audioMuted:!!(s&pn),videoMuted:!!(s&fn),audioAvailable:!!(s&$i)&&!(s&pn),videoAvailable:!!(s&Hi)&&!(s&fn)}}function Hu(s){let i={urls:s.url.startsWith("turn:")||s.url.startsWith("turns:")?s.url:`turn:${s.url}`};return!g(s.username)&&!g(s.credential)&&(i.username=s.username,i.credential=s.credential,i.credentialType="password",g(s.credentialType)||(i.credentialType=s.credentialType)),i}function Qr(s,i=!0){if(!K(s))return 0;let e=s.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 Gt=function(s,i,e,t){if(!($t(s)&&$t(i)))return 0;let r=0,o=Object.keys(i),n;for(let a=0,c=o.length;a<c;a++)if(n=o[a],!(g(i[n])||e&&e.includes(n)))if($t(s[n])&&$t(i[n]))r+=Gt(s[n],i[n],e,t);else{if(t&&t.includes(i[n]))continue;s[n]!==i[n]&&(s[n]=lr(i[n]),r+=1)}return r};function lr(s){if(Te(s)){let i=[];return s.forEach((e,t)=>{i[t]=lr(e)}),i}if($t(s)){let i={};return Object.keys(s).forEach(e=>{i[e]=lr(s[e])}),i}return s}var zr=s=>{let i=[];if(Te(s))i=[...s];else if(K(s)){let e=document.getElementById(s);e&&i.push(e)}else s&&i.push(s);return i},$u=s=>K(s)?document.getElementById(s):s,_f=s=>{let i=c=>c<10?`0${c}`:`${c}`,e=s.getFullYear(),t=s.getMonth()+1,r=s.getDate(),o=i(s.getHours()),n=i(s.getMinutes()),a=i(s.getSeconds());return`${e}/${t}/${r} ${o}:${n}:${a}`},Gu=()=>_f(new Date);function ft(s,{keysToInclude:i,keysToExclude:e}){try{if(Te(s))return`[${s.map(n=>ft(n,{keysToInclude:i,keysToExclude:e})).join(",")}]`;if(!Ze(s)||!Te(i)&&!Te(e))return JSON.stringify(s);let t={},r=new Set(i),o=new Set(e);return Object.keys(s).forEach(n=>{(o.size===0&&r.has(n)||r.size===0&&!o.has(n))&&(t[n]=Ze(s[n])||Te(s[n])?JSON.parse(ft(s[n],{keysToExclude:e,keysToInclude:i})):s[n])}),JSON.stringify(t)}catch(t){return"{}"}}function En(s,i=!1){let e=[];return Object.keys(s).forEach(t=>{i===s[t]&&e.push(t)}),ft(s,{keysToInclude:e})}function Ks(s){return s.replace(/[\u4e00-\u9fa5]/g,"aa").length}var Sn=()=>{var s,i,e,t;return(s=window.screen)!=null&&s.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},Yr=s=>f(void 0,null,function*(){return new Promise((i,e)=>{let t;if(K(s))t=new Image,t.crossOrigin="anonymous",t.src=s;else if(t=s,t.complete){i(t);return}t.onload=()=>i(t),t.onerror=()=>{e(new b({code:S.INVALID_PARAMETER,message:`load image failed, url: ${s}`}))}})}),In=s=>{let i=s.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]<<0},Zs=s=>(Object.keys(s).forEach(i=>{Y(s[i])&&(i.startsWith("uint")||i.startsWith("int"))?s[i]=Math.floor(s[i]):(Ze(s[i])||Te(s[i]))&&Zs(s[i])}),s);function fi(s,i){return new Promise(e=>{let t=setTimeout(e,s);i&&i(t)})}function An(s,i){let e=null;return function(...t){return e||(e=s.apply(i||this,t),e.finally(()=>e=null),e)}}function _i({url:s,body:i,method:e="POST",timeout:t,priority:r}){return new Promise((o,n)=>{if("fetch"in window)return fetch(s,{method:e,body:i,priority:r}).then(c=>c.text()).then(c=>{try{o({data:JSON.parse(c)})}catch(l){o({data:c})}},n);let a=new XMLHttpRequest;a.onreadystatechange=()=>{if(a.readyState===4)if(a.status>=200&&a.status<300)try{let c=JSON.parse(a.response);o({data:c})}catch(c){o({data:a.response})}else n({status:a.status,statusText:a.statusText||"request failed!"})},a.timeout=t||5e3,a.open(e,s,!0),a.send(i)})}function Ud(s){return f(this,null,function*(){let i=L(),e=JSON.stringify(s);try{if(!CompressionStream||e.length<=2800)return e;let r=new Blob([e],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),a=yield(yield(yield new Response(r)).blob()).arrayBuffer();return C.debug(`compressJSON ${e.length} -> ${a.byteLength} ${L()-i}ms`),a}catch(t){return e}})}var gf=Object.prototype.hasOwnProperty;var Wt=s=>typeof s=="function",gi=s=>typeof s=="undefined";var Wu=s=>typeof s=="boolean";var Vd=s=>s.isRemote;var Tf=function(s){if(!s||typeof s!="object"||Object.prototype.toString.call(s)!="[object Object]")return!1;let i=Object.getPrototypeOf(s);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 Ju(s){if(s==null)return!0;if(typeof s=="boolean")return!1;if(typeof s=="number")return s===0;if(typeof s=="string"||typeof s=="function"||Array.isArray(s))return s.length===0;if(s instanceof Error)return s.message==="";if(Tf(s))switch(Object.prototype.toString.call(s)){case"[object File]":case"[object Map]":case"[object Set]":return s.size===0;case"[object Object]":{for(let i in s)if(gf.call(s,i))return!1;return!0}}return!1}var Ef=0,Sf=1,qu=2;function If({retryFunction:s,settings:i,onError:e,onRetrying:t,onRetryFailed:r,onRetrySuccess:o,context:n}){return function(...a){let{retries:c=5,timeout:l=1e3}=i,h=0,u=-1,p=Ef,_=(I,R)=>f(this,null,function*(){let D=n||this;try{let G=yield s.apply(D,a);h>0&&o&&o.call(this,h),h=0,I(G)}catch(G){let te=()=>{clearTimeout(u),h=0,p=qu,R(G)},sn=()=>{p!==qu&&h<(Wt(c)?c():c)?(h++,p=Sf,Wt(t)&&t.call(this,h,te),u=window.setTimeout(()=>{u=-1,_(I,R)},Wt(l)?l(h):l)):(te(),Wt(r)&&r.call(this,G))};Wt(e)?e.call(this,{error:G,retry:sn,reject:R,retryFuncArgs:a,retriedCount:h}):sn()}});return new Promise(_)}}var Jt=If;var Kr=class{constructor(i){d(this,"userId");d(this,"remoteUserId");d(this,"id");d(this,"sdkAppId");d(this,"type");d(this,"isLocal");this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=Wu(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}`:""}]`),C.log(i,e,gi(this.userId)||Ju(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 ds={};ci(ds,{ANDROID_VERSION:()=>Hd,CHROME_MAJOR_VERSION:()=>kt,CHROME_VERSION:()=>Bn,EDGE_VERSION:()=>Rn,EDG_MAJOR_VERSION:()=>Gd,EDG_VERSION:()=>yn,FIREFOX_MAJOR_VERSION:()=>$d,FIREFOX_VERSION:()=>Cn,HUAWEI_VERSION:()=>xn,IE_VERSION:()=>bf,IOS_MAIN_VERSION:()=>at,IOS_VERSION:()=>ji,IPADQQB_VERSION:()=>Ln,IS_ANDROID:()=>pe,IS_ANDROID_WEBVIEW:()=>Qd,IS_ANY_SAFARI:()=>Ji,IS_CHROME:()=>as,IS_CHROME_OS:()=>Wd,IS_CHROMIUM_BASE:()=>Ot,IS_EDG:()=>ts,IS_EDGE:()=>es,IS_ELECTRON:()=>vf,IS_FIREFOX:()=>ae,IS_HEADLESS_CHROME:()=>Xd,IS_HONOR:()=>jd,IS_HUAWEI:()=>qd,IS_HUAWEIBROWSER:()=>lo,IS_IE:()=>zu,IS_IE8:()=>yf,IS_IOS:()=>ve,IS_IOS_13_OR_14:()=>Yd,IS_IOS_15_1:()=>zd,IS_IPAD:()=>eo,IS_IPADQQB:()=>no,IS_IPAD_PRO:()=>Fd,IS_IPHONE:()=>mr,IS_IPOD:()=>Qu,IS_LINUX:()=>ao,IS_LOCAL:()=>Mt,IS_MAC:()=>Dt,IS_MACQQB:()=>oo,IS_MIBROWSER:()=>co,IS_MQQB:()=>ss,IS_NATIVE_ANDROID:()=>Rf,IS_OLD_ANDROID:()=>Cf,IS_OPPOBROWSER:()=>os,IS_SAFARI:()=>Ve,IS_SAFARI_15_1:()=>Df,IS_SAMSUNGBROWSER:()=>uo,IS_SOGOU:()=>io,IS_SOGOUM:()=>to,IS_TBS:()=>vt,IS_UCBROWSER:()=>Jd,IS_VIVOBROWSER:()=>ns,IS_WECHAT:()=>is,IS_WIN:()=>pr,IS_WQQB:()=>so,IS_WX:()=>Nf,IS_X5MQQB:()=>rs,IS_XWEB:()=>ro,MACQQB_VERSION:()=>Mn,MI_VERSION:()=>Pn,MQQB_VERSION:()=>Zr,OPPO_VERSION:()=>Un,SAFARI_VERSION:()=>qi,SAMSUNG_VERSION:()=>wn,SOGOUM_VERSION:()=>bn,SOGOU_VERSION:()=>Nn,TBS_VERSION:()=>vn,UA_DATA_STRING:()=>bt,USER_AGENT:()=>Nt,VIVO_VERSION:()=>Vn,WECHAT_VERSION:()=>On,WQQB_VERSION:()=>kn,XWEB_VERSION:()=>Dn,browserInfo:()=>qt,getBrowserInfo:()=>Yu,getChromeMajorVersion:()=>fr,getDeviceModel:()=>_r,getOSName:()=>Fn,getOSNumber:()=>mo,getOSString:()=>Ei,getOSType:()=>Of,getTerminalType:()=>Kd,getUserAgentData:()=>ho,isLocalStorageEnabled:()=>Ti});var Nt=typeof navigator=="undefined"?"":navigator.userAgent,X=s=>new RegExp(s,"i").test(Nt),ye=s=>{if(X(s)){let i=new RegExp(`${s}\\/([\\d.]+)`),e=Nt.match(i);if(e&&e[1])return e[1]}return""},Bd=s=>{if(X(s)){let i=new RegExp(`${s}\\/(\\d+)`),e=Nt.match(i);if(e&&e[1])return parseFloat(e[1])}return NaN},ju=/AppleWebKit\/([\d.]+)/i.exec(Nt),Af=ju?parseFloat(ju[1]):NaN,eo=X("iPad"),Fd=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&X("Macintosh"),mr=X("iPhone")&&!eo,Qu=X("iPod"),ve=mr||eo||Qu||Fd,pe=X("Android"),Hd=function(){if(pe){let s=Nt.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(s){let i=s[1]&&parseFloat(s[1]),e=s[2]&&parseFloat(s[2]);if(i&&e)return parseFloat(`${s[1]}.${s[2]}`);if(i)return i}}return NaN}(),Cf=pe&&X("webkit")&&Hd<2.3,Rf=pe&&Hd<5&&Af<537,ae=X("Firefox"),Cn=ye("Firefox"),$d=Bd("Firefox"),es=X("Edge"),Rn=ye("Edge"),ts=X("Edg"),yn=ye("Edg"),Gd=Bd("Edg"),to=X("SogouMobileBrowser"),bn=ye("SogouMobileBrowser"),io=X("MetaSr\\s"),Nn=ye("MetaSr\\s"),vt=X("TBS"),vn=ye("TBS"),ro=X("XWEB"),Dn=ye("XWEB"),yf=X("MSIE\\s8\\.0"),zu=X("MSIE\\/\\d+"),bf=function(){if(zu){let s=/MSIE\s(\d+)\.\d/.exec(Nt),i=s&&parseFloat(s[1]);return!i&&/Trident\/7.0/i.test(Nt)&&/rv:11.0/.test(Nt)&&(i=11),i}return NaN}(),is=X("(micromessenger|webbrowser)"),On=ye("MicroMessenger"),rs=!vt&&X("MQQBrowser")&&X("COVC"),ss=!vt&&X("MQQBrowser")&&!X("COVC"),Zr=ss||rs?ye("MQQBrowser"):"",so=!vt&&X(" QQBrowser"),kn=ye(" QQBrowser"),oo=!vt&&X("QQBrowserLite"),Mn=ye("QQBrowserLite"),no=!vt&&X("MQBHD"),Ln=ye("MQBHD"),pr=X("Windows"),Dt=!ve&&X("MAC OS X"),ao=!pe&&X("Linux"),Wd=X("CrOS"),Nf=X("MicroMessenger"),Jd=X("UCBrowser"),vf=X("Electron"),co=X("MiuiBrowser"),Pn=ye("MiuiBrowser"),lo=X("HuaweiBrowser"),qd=X("Huawei")||X("HUAWEI"),jd=X("Honor")||X("HONOR"),xn=ye("HuaweiBrowser"),uo=X("SamsungBrowser"),wn=ye("SamsungBrowser"),os=X("HeyTapBrowser"),Un=ye("HeyTapBrowser"),ns=X("VivoBrowser"),Vn=ye("VivoBrowser"),fr=()=>Bd("Chrome"),Ot=X("Chrome"),as=!es&&!io&&!to&&!vt&&!ro&&!ts&&!so&&!co&&!lo&&!uo&&!os&&!ns&&Ot,Xd=X("HeadlessChrome"),kt=fr(),Bn=ye("Chrome"),Ve=!Ot&&!ss&&!rs&&!oo&&!no&&X("Safari"),Ji=Ve||ve,qi=ye("Version"),Qd=/Android.*(wv|.0.0.0)/.test(Nt),ji=(()=>{if(Fd)return qi;if(ve){let s=Nt.match(/OS (\d+)_(\d+)/i);if(s&&s[1]){let i=s[1];return s[2]&&(i+=`.${s[2]}`),i}}return""})(),at=Number(ji.split(".")[0]),Df=qi==="15.1",zd=ji==="15.1",Yd=(()=>{let s=Number(ji.split(".")[0]);return s===14||s===13})(),Mt=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",Ti=(()=>{let s;return()=>{if(typeof s=="undefined")try{s=!!window.localStorage}catch(i){s=!1}return s}})(),qt=Yu();function Yu(){let s=new Map([[ae,["Firefox",Cn]],[ts,["Edg",yn]],[as,["Chrome",Bn]],[Ve,["Safari",qi]],[vt,["TBS",vn]],[ro,["XWEB",Dn]],[is&&mr,["WeChat",On]],[so,["QQ(Win)",kn]],[ss,["QQ(Mobile)",Zr]],[rs,["QQ(Mobile X5)",Zr]],[oo,["QQ(Mac)",Mn]],[no,["QQ(iPad)",Ln]],[co,["MI",Pn]],[lo,["HW",xn]],[uo,["Samsung",wn]],[os,["OPPO",Un]],[ns,["VIVO",Vn]],[es,["EDGE",Rn]],[to,["SogouMobile",bn]],[io,["Sogou",Nn]]]),i="unknown",e="unknown";return s.has(!0)&&([i,e]=s.get(!0)),{name:i,version:e}}var ne=null,bt="";function ho(){return f(this,null,function*(){if(ne)return ne;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return ne=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),ne&&!bt&&(bt=`UAData: ${ne.platform}/${ne.platformVersion}`,ne.architecture&&ne.bitness&&(bt+=` ${ne.architecture}/${ne.bitness}`),ne.mobile&&(bt+=" mobile"),ne.model&&(bt+=` model: ${ne.model}`),ne.fullVersionList&&(bt+=` ${ne.fullVersionList.filter(s=>s.brand!=="Not/A)Brand").map(s=>`${s.brand}/${s.version}`).join(",")}`)),ne}catch(s){return null}})}function _r(){return(ne==null?void 0:ne.model)||""}var Xu=new Map([[pe,"Android"],[ve,"iOS"],[pr,"Windows"],[Dt,"MacOS"],[ao,"Linux"],[Wd,"ChromeOS"]]),Fn=function(){return Xu.get(!0)?Xu.get(!0):ne?ne.platform:"unknown"};function mo(){return pr?1:pe?2:Dt?3:ve?4:ao?5:Wd?6:0}var Ei=()=>{let s=Fn();return s+=`/${qt.name}/${Ve?qt.version:qt.version.split(".")[0]}`,ne!=null&&ne.platformVersion&&(s+=`/${ne.platformVersion}`),ne!=null&&ne.architecture&&(s+=`/${ne.architecture}`),s};function Kd(){return pe?4:mr?2:eo?3:Dt?12:pr?5:ao?13:1}function Of(){return pe?"Android":mr?"iPhone":eo?"iPad":Dt?"Mac":pr?"Windows":ao?"Linux":"unknown"}var Ku=Pe(je(),1),kf=new Ku.default,E=kf;var jt=(W=>(W.ROOM_DESTROY="1",W.JOIN_START="21",W.JOIN_SCHEDULE_SUCCESS="22",W.JOIN_SIGNAL_CONNECTION_START="23",W.JOIN_SIGNAL_CONNECTION_END="24",W.JOIN_SEND_CMD="25",W.JOIN_RECEIVED_CMD_RES="26",W.JOIN_SUCCESS="27",W.JOIN_FAILED="28",W.LEAVE_START="51",W.LEAVE_SEND_CMD="52",W.LEAVE_SUCCESS="53",W.PUBLISH_START="61",W.SEND_FIRST_VIDEO_FRAME="62",W.PUBLISH_FAILED="63",W.SUBSCRIBE_START="81",W.SUBSCRIBE_SUCCESS="82",W.SUBSCRIBE_FAILED="84",W.UNSUBSCRIBE_SUCCESS="83",W.LOCAL_TRACK_CAPTURE_START="101",W.LOCAL_TRACK_CAPTURE_SUCCESS="102",W.LOCAL_TRACK_CAPTURE_FAILED="103",W.LOCAL_TRACK_PUBLISHED="104",W.LOCAL_TRACK_UNPUBLISHED="105",W.LOCAL_TRACK_REPLACED="106",W.SWITCH_DEVICE_SUCCESS="107",W.TRACK_MUTED="108",W.TRACK_UNMUTED="109",W.REMOTE_TRACK_SUBSCRIBED="110",W.REMOTE_TRACK_UNSUBSCRIBED="111",W.LOCAL_TRACK_RECAPTURE="112",W.PLAY_TRACK_START="151",W.PLAYER_STATE_CHANGED="152",W.VIDEO_LOADED_DATA="153",W.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",W.SIGNAL_CONNECTION_STATE_CHANGED="201",W.PEER_CONNECTION_STATE_CHANGED="202",W.SINGLE_CONNECTION_STAT="203",W.SPC_RECONNECTED="204",W.HEARTBEAT_REPORT="251",W.RECEIVED_PUBLISHED_USER_LIST="252",W.REMOTE_PUBLISH_STATE_CHANGED="253",W.AUDIO_LEVEL_INTERVAL="260",W.NETWORK_QUALITY="261",W.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",W.QUALITY_LIMITATION_CHANGED="263",W.LOG="264",W.AEC_DEBUG="265",W))(jt||{});var T=jt;var Mf="%cTRTC%c%s",Lf="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",Pf="display: inline",Hn=class Hn{constructor(){d(this,"_isEnableUploadLog",!0);d(this,"_localJoinedUser",new Map);d(this,"_queue",[]);d(this,"_timeoutId",-1);d(this,"_logLevel",1);d(this,"_logLevelToUpload",2);!$r&&!$s&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){E.on(T.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var e;(e=i==null?void 0:i.config)!=null&&e.logLevelToUpload&&At[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),E.on(T.JOIN_SUCCESS,({room:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),E.once(T.JOIN_FAILED,()=>{this.startUpload()}),E.on(T.LEAVE_SUCCESS,({room:i})=>{this.deleteJoinedUser(i.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(i){this._localJoinedUser.set(i.userId,i),this.startUpload()}deleteJoinedUser(i){this._localJoinedUser.delete(i)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),5e3)}getLogsToUpload(){let i={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return i;let e=0;for(;e<this._queue.length&&e!==50;e++){let t=this._queue[e];if(t.forAllJoinedClients)this._localJoinedUser.forEach(({userId:r,sdkAppId:o})=>{i.map.has(r)?i.map.get(r).logs.push(t):i.map.set(r,{userId:r,sdkAppId:o,logs:[t]})});else if(K(t.userId)&&Y(t.sdkAppId)){let{userId:r,sdkAppId:o}=t;i.map.has(r)?i.map.get(r).logs.push(t):i.map.set(r,{userId:r,sdkAppId:o,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 r=[...i.values()];for(let o=0;o<r.length;o++){let{userId:n,sdkAppId:a,logs:c}=r[o];yield this.uploadLogWithRetry(JSON.stringify({timestamp:an(),sdkAppId:String(a),userId:n,version:Re,log:c.map(l=>l.log).join(`
|
|
5
|
+
`}});var ou=di(Bi=>{"use strict";var wr=jm(),RT=Qm();Bi.write=RT;Bi.parse=wr.parse;Bi.parseParams=wr.parseParams;Bi.parseFmtpConfig=wr.parseFmtpConfig;Bi.parsePayloads=wr.parsePayloads;Bi.parseRemoteCandidates=wr.parseRemoteCandidates;Bi.parseImageAttributes=wr.parseImageAttributes;Bi.parseSimulcastStreamList=wr.parseSimulcastStreamList});import e1 from"webrtc-adapter";var xm=Pe(je());var yu=(x=>(x[x.INVALID_PARAMETER=4096]="INVALID_PARAMETER",x[x.INVALID_OPERATION=4097]="INVALID_OPERATION",x[x.NOT_SUPPORTED=4098]="NOT_SUPPORTED",x[x.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",x[x.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",x[x.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",x[x.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",x[x.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",x[x.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",x[x.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",x[x.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",x[x.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",x[x.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",x[x.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",x[x.CLIENT_BANNED=16448]="CLIENT_BANNED",x[x.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",x[x.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",x[x.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",x[x.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",x[x.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",x[x.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",x[x.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",x[x.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",x[x.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",x[x.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",x[x.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",x[x.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",x[x.API_CALL_ABORTED=16461]="API_CALL_ABORTED",x[x.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",x[x.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",x[x.UNKNOWN=65535]="UNKNOWN",x))(yu||{}),S=yu;var Gp=function(s){for(let i in S)if(S[i]===s)return i;return"UNKNOWN"},gd=class extends Error{constructor({name:e="RtcError",message:t,code:r=S.UNKNOWN,extraCode:o=0,constraint:n}){let a=`<${Gp(r)} 0x${r.toString(16)}>`,c=`${t}${n?` constraint: ${n}`:""}${t!=null&&t.includes(a)?"":` ${a}`}`;super(c);d(this,"code");d(this,"extraCode");d(this,"message");d(this,"originMessage");d(this,"name");d(this,"constraint");this.code=r,this.extraCode=o,this.name=e,this.message=c,this.constraint=n,this.originMessage=t}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},b=gd;var bu=new Date().getTime(),Td=0,Nu=function(s){bu=s,Td=bu-new Date().getTime();let i=new Date;i.setTime(s),C.info(`baseTime from server: ${i} offset: ${Td}`)},Fs=function(){return new Date().getTime()+Td},an=function(){let s=new Date;return s.setTime(Fs()),s.toLocaleString()};var nt={};ci(nt,{bytes2ms:()=>xu,convertObjectNumberToInt:()=>Zs,copyProperties:()=>Pu,deepClone:()=>lr,deepMerge:()=>Gt,delay:()=>fi,fibonacci:()=>hr,formatedTime:()=>Gu,getConstructorName:()=>Ys,getContainerFromElement:()=>$u,getEnv:()=>Mu,getInternalVersion:()=>Fu,getLoggerUrl:()=>mi,getMuteStateFromFlag:()=>pi,getNetworkType:()=>Ld,getNumNetworkType:()=>ur,getReconnectionTimeout:()=>yt,getStringByteLength:()=>Ks,getTurnServer:()=>Hu,getUint32Version:()=>In,getValueType:()=>Ae,getViewListFromView:()=>zr,glog:()=>wd,ipv4ToUint32:()=>Qr,isArray:()=>Te,isAudioWorkletSupported:()=>Bu,isBoolean:()=>me,isConstructor:()=>qr,isEmpty:()=>Xr,isFunction:()=>oe,isLangChinese:()=>Rt,isMediaStreamTrack:()=>Uu,isNumber:()=>Y,isObject:()=>$t,isOverseaSdkAppId:()=>zs,isPlainObject:()=>Ze,isPortrait:()=>Sn,isPromise:()=>Wi,isRemoteTrack:()=>Vu,isString:()=>K,isUndefined:()=>g,loadImage:()=>Yr,ms2bytes:()=>wu,ms2samples:()=>xd,performanceNow:()=>L,promiseAny:()=>jr,samples2ms:()=>Pd,setNetworkType:()=>Tn,stringify:()=>ft,stringifyIncludeValue:()=>En,throttlePromise:()=>An});var Md={};ci(Md,{AUDIO_MUTE_BIT:()=>pn,AUDIO_STAT_BIT:()=>$i,AUX_STAT_BIT:()=>ar,AUX_STREAM_MSID:()=>Rd,BACKEND_ENV:()=>mn,BASE_DOC_URL:()=>Ft,BASE_HOST:()=>vu,CAPABILITIES_KEYS:()=>gn,CLASS_NAME:()=>hf,CLOUD_CONSOLE_URL:()=>jp,CROSS_ROOM_BIT:()=>Cd,DATA_FREEZE_TIMING:()=>_n,DEFAULT_ASSETS_URL:()=>dn,DOC_URL:()=>Xp,DTLS_STATE_UNKNOWN:()=>Ct,ENV_NAME:()=>li,EXCHANGE_SDP_TIMEOUT:()=>Dd,IS_WORKER:()=>$r,IS_WORKLET:()=>$s,KIBANA_EVENT:()=>Ke,LOCAL_STREAM_PUBLISH_STATE:()=>Ou,LOGGER_CMD_TYPE:()=>Fi,LOGGER_DOMAIN:()=>Sd,LOGGER_DOMAIN_OVERSEA:()=>Id,LOG_LEVEL:()=>At,LOG_LEVEL_NAME:()=>pf,MAIN_STREAM_MSID:()=>Js,MAX_RTT:()=>Xs,MICROPHONE_COMMUNICATIONS:()=>mf,MICROPHONE_DEFAULT:()=>cr,MUTE_ALL_BIT:()=>Yp,NAME:()=>m,NETWORK_TYPE:()=>cn,NOT_SUPPORTED_H264:()=>dr,PAUSED_RETRY_COUNT:()=>Od,PEERCONNECTION_CONNECTING_TIMEOUT:()=>qs,PEER_CONNECTION_STATE:()=>ce,PEER_LEAVE_REASON:()=>kd,RECOVER_CAPTURE_INTERVAL:()=>Jr,REMOTE_STREAM_TYPE_AUX:()=>bd,REMOTE_STREAM_TYPE_MAIN:()=>yd,RENDER_FREEZE_TIMING:()=>df,SCHEDULE_DOMAIN:()=>hi,SCHEDULE_TIMEOUT:()=>uf,SDP_SEMANTICS_PLAN_B:()=>Gr,SDP_SEMANTICS_UNIFIED_PLAN:()=>Gi,SECOND_HOST:()=>Jp,SIGNAL_PING_PONG_INTERVAL:()=>zp,SIGNAL_PING_TIMEOUT:()=>Qp,SIGNAL_RECONNECTION_COUNT:()=>nf,SMALL_STAT_BIT:()=>Ws,SPEAKER_DEFAULT:()=>js,STORAGE_EXPIRES_TIME:()=>ln,STREAM_TYPE_BIG:()=>cf,STREAM_TYPE_SMALL:()=>lf,SUBSCRIBE_SMALL_RETRY_COUNT:()=>Wr,SYNC_USER_LIST_INTERVAL:()=>af,Scene:()=>Ht,THIRD_HOST:()=>qp,TRANSPORT_DIRECTION:()=>z,TRTC_ERROR_ASSISTANCE:()=>Ad,TRTC_QUALITY_BAD:()=>rf,TRTC_QUALITY_DISCONNECTED:()=>of,TRTC_QUALITY_EXCELLENT:()=>Zp,TRTC_QUALITY_GOOD:()=>ef,TRTC_QUALITY_POOR:()=>tf,TRTC_QUALITY_UNKNOWN:()=>Kp,TRTC_QUALITY_VERY_BAD:()=>sf,UPDATE_OFFER_TIMEOUT:()=>vd,VIDEO_MUTE_BIT:()=>fn,VIDEO_STAT_BIT:()=>Hi,audioProfileMap:()=>un,getRetryCount:()=>ui,getScriptDir:()=>Wp,innerVersion:()=>Hs,loggerProxy:()=>Gs,screenProfileMap:()=>hn,setLoggerProxy:()=>nr,setRetryCount:()=>Nd,setVersion:()=>Ed,version:()=>Re,videoProfileMap:()=>pt});var Hs="4.15.00.1600",Re="5.0.0";function Ed(s){Re=s;let[i,e,t]=s.split(".").map(r=>parseInt(r,10));Hs=`${i}.${Math.min(15,e)}.${Math.min(15,t)}.${e.toString().padStart(2,"0")}${t.toString().padStart(2,"0")}`}var $r=typeof importScripts!="undefined",$s=typeof registerProcessor!="undefined",Wp=()=>{let s=$r?self.location.href:document.currentScript.src;return s.substring(0,s.lastIndexOf("/")+1)},Gs="",nr=s=>Gs=s,vu="web.sdk.qcloud.com",Jp="web.sdk.tencent.cn",qp="web.sdk.cloud.tencent.cn",jp="https://console.cloud.tencent.com/trtc",Ft=`https://${vu}/trtc/webrtc/v5/doc`,dn="https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/",Xp=`${Ft}/zh-cn/`,Sd="https://yun.tim.qq.com",Id="https://apisgp.my-imcloud.com",Ad="trtc_error_assistance",Fi={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},li={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},At=(n=>(n[n.TRACE=0]="TRACE",n[n.DEBUG=1]="DEBUG",n[n.INFO=2]="INFO",n[n.WARN=3]="WARN",n[n.ERROR=4]="ERROR",n[n.NONE=5]="NONE",n))(At||{}),Qp=18e3,zp=2e3,cn={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},ln=7*24*3600*1e3,un={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}},pt={"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}},hn={"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}},m={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",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture"},z={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},mn={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Ht=(e=>(e.LIVE="live",e.RTC="rtc",e))(Ht||{}),Hi=1,Ws=2,ar=4,$i=8,pn=64,fn=16,Yp=112,Cd=128,Js="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",Rd="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",yd=m.MAIN,bd=m.AUXILIARY,Kp=0,Zp=1,ef=2,tf=3,rf=4,sf=5,of=6,Ct="unknown",ce={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Du=1/0;function Nd(s){Du=s}function ui(){return Du}var nf=30,Ke={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"},af=1e4,vd=1e4,Dd=1e4,Gi="unified-plan",Gr="plan-b",dr=1028,Ou=(t=>(t[t.UNPUBLISH=-1]="UNPUBLISH",t[t.PUBLISHING=0]="PUBLISHING",t[t.PUBLISHED=1]="PUBLISHED",t))(Ou||{}),_n=500,df=1e3,cf=m.BIG,lf=m.SMALL,qs=10*1e3,hi={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_BACKUP:"intl-schedule.cloud-rtc.com"},uf=2e3,hf={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},Od=5,cr="default",js=cr,mf="communications",pf=Object.keys(At),kd=["normal leave","timeout leave","kick","role change"],Wr=10,Jr=2e3,gn=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],Xs=10*1e3;var Mu=function(){return new URLSearchParams(location.search).get("trtc_env")||""},zs=s=>Number(s)<14e8,mi=function(s,i){let e;Gs?e=Gs:e=zs(s)?Id:Sd;let t=Math.floor(Math.random()*Vs(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${t}&sdkappid=${s}&cmdtype=${i}`},Qs="unknown";function Ld(){if(Qs!=="unknown")return Qs;let{userAgent:s,connection:i}=navigator,e=(s.match(/NetType\/\S+/)||[])[0]||"";e=e.toLowerCase().replace("nettype/",""),e==="3gnet"&&(e="3g");let t=i&&i.type&&i.type.toLowerCase(),r=i&&i.effectiveType&&i.effectiveType.toLowerCase();return r==="slow-2"&&(r="2g"),t&&(Qs=Lu(t,r)),Qs}function Lu(s,i){if(cn[s])return s;switch(s){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function Tn(s){Qs=Lu(s)}function ur(){return cn[Ld()]}function Pu(s,i){for(let e of Reflect.ownKeys(i))if(e!=="constructor"&&e!=="prototype"&&e!=="name"){let t=Object.getOwnPropertyDescriptor(i,e)||"";Object.defineProperty(s,e,t)}return s}function xu(s,i=48e3){return Pd(s/4,i)}function Pd(s,i=48e3){return s*1e3/i}function wu(s,i=48e3){return xd(s,i)*4}function xd(s,i=48e3){return s*i/1e3}var wd=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},Rt=()=>{let s=navigator.language;return s=s.substring(0,2),s==="zh"},Ze=function(s){if(!s||typeof s!="object"||Object.prototype.toString.call(s)!="[object Object]")return!1;let i=Object.getPrototypeOf(s);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 hr(s,i=1,e=1){return s<=1?e:hr(s-1,e,i+e)}function yt(s){return s>8?30*1e3:hr(s)*1e3}function Ae(s){return Reflect.apply(Object.prototype.toString,s,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var oe=s=>typeof s=="function",g=s=>typeof s=="undefined",K=s=>typeof s=="string",Y=s=>typeof s=="number",me=s=>typeof s=="boolean",$t=s=>Ae(s)==="object",Te=s=>Ae(s)==="array",Uu=s=>Ae(s)==="MediaStreamTrack".toLowerCase(),Vu=s=>s.isRemote,Wi=s=>Ae(s)==="promise",qr=s=>oe(s)&&s.prototype.constructor===s,Ys=s=>qr(s)?s.prototype.constructor.name:"",Bu=typeof AudioWorkletNode!="undefined";function jr(s){return new Promise((i,e)=>{let t=[];s.forEach(r=>{r.then(i).catch(o=>{t.push(o),t.length===s.length&&e(t)})})})}function L(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var ku=s=>+s<10?`0${s}`:s,Fu=s=>{let i=s.match(/^\d+\.\d+\.\d+/)[0];if(!i)return s;let e=i.split("."),t=ku(e[1])+ku(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${t}`},ff=Object.prototype.hasOwnProperty,{toString:eE}=Object.prototype;function Xr(s){if(s==null)return!0;if(typeof s=="boolean")return!1;if(typeof s=="number")return s===0;if(typeof s=="string"||typeof s=="function"||Array.isArray(s))return s.length===0;if(s instanceof Error)return s.message==="";if(Ze(s))switch(Object.prototype.toString.call(s)){case"[object File]":case"[object Map]":case"[object Set]":return s.size===0;case"[object Object]":{for(let i in s)if(ff.call(s,i))return!1;return!0}}return!1}function pi(s,i){return{userId:i,hasAudio:!!(s&$i),hasVideo:!!(s&Hi),hasAuxiliary:!!(s&ar),hasSmall:!!(s&Ws),audioMuted:!!(s&pn),videoMuted:!!(s&fn),audioAvailable:!!(s&$i)&&!(s&pn),videoAvailable:!!(s&Hi)&&!(s&fn)}}function Hu(s){let i={urls:s.url.startsWith("turn:")||s.url.startsWith("turns:")?s.url:`turn:${s.url}`};return!g(s.username)&&!g(s.credential)&&(i.username=s.username,i.credential=s.credential,i.credentialType="password",g(s.credentialType)||(i.credentialType=s.credentialType)),i}function Qr(s,i=!0){if(!K(s))return 0;let e=s.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 Gt=function(s,i,e,t){if(!($t(s)&&$t(i)))return 0;let r=0,o=Object.keys(i),n;for(let a=0,c=o.length;a<c;a++)if(n=o[a],!(g(i[n])||e&&e.includes(n)))if($t(s[n])&&$t(i[n]))r+=Gt(s[n],i[n],e,t);else{if(t&&t.includes(i[n]))continue;s[n]!==i[n]&&(s[n]=lr(i[n]),r+=1)}return r};function lr(s){if(Te(s)){let i=[];return s.forEach((e,t)=>{i[t]=lr(e)}),i}if($t(s)){let i={};return Object.keys(s).forEach(e=>{i[e]=lr(s[e])}),i}return s}var zr=s=>{let i=[];if(Te(s))i=[...s];else if(K(s)){let e=document.getElementById(s);e&&i.push(e)}else s&&i.push(s);return i},$u=s=>K(s)?document.getElementById(s):s,_f=s=>{let i=c=>c<10?`0${c}`:`${c}`,e=s.getFullYear(),t=s.getMonth()+1,r=s.getDate(),o=i(s.getHours()),n=i(s.getMinutes()),a=i(s.getSeconds());return`${e}/${t}/${r} ${o}:${n}:${a}`},Gu=()=>_f(new Date);function ft(s,{keysToInclude:i,keysToExclude:e}){try{if(Te(s))return`[${s.map(n=>ft(n,{keysToInclude:i,keysToExclude:e})).join(",")}]`;if(!Ze(s)||!Te(i)&&!Te(e))return JSON.stringify(s);let t={},r=new Set(i),o=new Set(e);return Object.keys(s).forEach(n=>{(o.size===0&&r.has(n)||r.size===0&&!o.has(n))&&(t[n]=Ze(s[n])||Te(s[n])?JSON.parse(ft(s[n],{keysToExclude:e,keysToInclude:i})):s[n])}),JSON.stringify(t)}catch(t){return"{}"}}function En(s,i=!1){let e=[];return Object.keys(s).forEach(t=>{i===s[t]&&e.push(t)}),ft(s,{keysToInclude:e})}function Ks(s){return s.replace(/[\u4e00-\u9fa5]/g,"aa").length}var Sn=()=>{var s,i,e,t;return(s=window.screen)!=null&&s.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},Yr=s=>f(void 0,null,function*(){return new Promise((i,e)=>{let t;if(K(s))t=new Image,t.crossOrigin="anonymous",t.src=s;else if(t=s,t.complete){i(t);return}t.onload=()=>i(t),t.onerror=()=>{e(new b({code:S.INVALID_PARAMETER,message:`load image failed, url: ${s}`}))}})}),In=s=>{let i=s.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]<<0},Zs=s=>(Object.keys(s).forEach(i=>{Y(s[i])&&(i.startsWith("uint")||i.startsWith("int"))?s[i]=Math.floor(s[i]):(Ze(s[i])||Te(s[i]))&&Zs(s[i])}),s);function fi(s,i){return new Promise(e=>{let t=setTimeout(e,s);i&&i(t)})}function An(s,i){let e=null;return function(...t){return e||(e=s.apply(i||this,t),e.finally(()=>e=null),e)}}function _i({url:s,body:i,method:e="POST",timeout:t,priority:r}){return new Promise((o,n)=>{if("fetch"in window)return fetch(s,{method:e,body:i,priority:r}).then(c=>c.text()).then(c=>{try{o({data:JSON.parse(c)})}catch(l){o({data:c})}},n);let a=new XMLHttpRequest;a.onreadystatechange=()=>{if(a.readyState===4)if(a.status>=200&&a.status<300)try{let c=JSON.parse(a.response);o({data:c})}catch(c){o({data:a.response})}else n({status:a.status,statusText:a.statusText||"request failed!"})},a.timeout=t||5e3,a.open(e,s,!0),a.send(i)})}function Ud(s){return f(this,null,function*(){let i=L(),e=JSON.stringify(s);try{if(!CompressionStream||e.length<=2800)return e;let r=new Blob([e],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),a=yield(yield(yield new Response(r)).blob()).arrayBuffer();return C.debug(`compressJSON ${e.length} -> ${a.byteLength} ${L()-i}ms`),a}catch(t){return e}})}var gf=Object.prototype.hasOwnProperty;var Wt=s=>typeof s=="function",gi=s=>typeof s=="undefined";var Wu=s=>typeof s=="boolean";var Vd=s=>s.isRemote;var Tf=function(s){if(!s||typeof s!="object"||Object.prototype.toString.call(s)!="[object Object]")return!1;let i=Object.getPrototypeOf(s);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 Ju(s){if(s==null)return!0;if(typeof s=="boolean")return!1;if(typeof s=="number")return s===0;if(typeof s=="string"||typeof s=="function"||Array.isArray(s))return s.length===0;if(s instanceof Error)return s.message==="";if(Tf(s))switch(Object.prototype.toString.call(s)){case"[object File]":case"[object Map]":case"[object Set]":return s.size===0;case"[object Object]":{for(let i in s)if(gf.call(s,i))return!1;return!0}}return!1}var Ef=0,Sf=1,qu=2;function If({retryFunction:s,settings:i,onError:e,onRetrying:t,onRetryFailed:r,onRetrySuccess:o,context:n}){return function(...a){let{retries:c=5,timeout:l=1e3}=i,h=0,u=-1,p=Ef,_=(I,R)=>f(this,null,function*(){let D=n||this;try{let G=yield s.apply(D,a);h>0&&o&&o.call(this,h),h=0,I(G)}catch(G){let te=()=>{clearTimeout(u),h=0,p=qu,R(G)},sn=()=>{p!==qu&&h<(Wt(c)?c():c)?(h++,p=Sf,Wt(t)&&t.call(this,h,te),u=window.setTimeout(()=>{u=-1,_(I,R)},Wt(l)?l(h):l)):(te(),Wt(r)&&r.call(this,G))};Wt(e)?e.call(this,{error:G,retry:sn,reject:R,retryFuncArgs:a,retriedCount:h}):sn()}});return new Promise(_)}}var Jt=If;var Kr=class{constructor(i){d(this,"userId");d(this,"remoteUserId");d(this,"id");d(this,"sdkAppId");d(this,"type");d(this,"isLocal");this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=Wu(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}`:""}]`),C.log(i,e,gi(this.userId)||Ju(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 ds={};ci(ds,{ANDROID_VERSION:()=>Hd,CHROME_MAJOR_VERSION:()=>kt,CHROME_VERSION:()=>Bn,EDGE_VERSION:()=>Rn,EDG_MAJOR_VERSION:()=>Gd,EDG_VERSION:()=>yn,FIREFOX_MAJOR_VERSION:()=>$d,FIREFOX_VERSION:()=>Cn,HUAWEI_VERSION:()=>xn,IE_VERSION:()=>bf,IOS_MAIN_VERSION:()=>at,IOS_VERSION:()=>ji,IPADQQB_VERSION:()=>Ln,IS_ANDROID:()=>pe,IS_ANDROID_WEBVIEW:()=>Qd,IS_ANY_SAFARI:()=>Ji,IS_CHROME:()=>as,IS_CHROME_OS:()=>Wd,IS_CHROMIUM_BASE:()=>Ot,IS_EDG:()=>ts,IS_EDGE:()=>es,IS_ELECTRON:()=>vf,IS_FIREFOX:()=>ae,IS_HEADLESS_CHROME:()=>Xd,IS_HONOR:()=>jd,IS_HUAWEI:()=>qd,IS_HUAWEIBROWSER:()=>lo,IS_IE:()=>zu,IS_IE8:()=>yf,IS_IOS:()=>ve,IS_IOS_13_OR_14:()=>Yd,IS_IOS_15_1:()=>zd,IS_IPAD:()=>eo,IS_IPADQQB:()=>no,IS_IPAD_PRO:()=>Fd,IS_IPHONE:()=>mr,IS_IPOD:()=>Qu,IS_LINUX:()=>ao,IS_LOCAL:()=>Mt,IS_MAC:()=>Dt,IS_MACQQB:()=>oo,IS_MIBROWSER:()=>co,IS_MQQB:()=>ss,IS_NATIVE_ANDROID:()=>Rf,IS_OLD_ANDROID:()=>Cf,IS_OPPOBROWSER:()=>os,IS_SAFARI:()=>Be,IS_SAFARI_15_1:()=>Df,IS_SAMSUNGBROWSER:()=>uo,IS_SOGOU:()=>io,IS_SOGOUM:()=>to,IS_TBS:()=>vt,IS_UCBROWSER:()=>Jd,IS_VIVOBROWSER:()=>ns,IS_WECHAT:()=>is,IS_WIN:()=>pr,IS_WQQB:()=>so,IS_WX:()=>Nf,IS_X5MQQB:()=>rs,IS_XWEB:()=>ro,MACQQB_VERSION:()=>Mn,MI_VERSION:()=>Pn,MQQB_VERSION:()=>Zr,OPPO_VERSION:()=>Un,SAFARI_VERSION:()=>qi,SAMSUNG_VERSION:()=>wn,SOGOUM_VERSION:()=>bn,SOGOU_VERSION:()=>Nn,TBS_VERSION:()=>vn,UA_DATA_STRING:()=>bt,USER_AGENT:()=>Nt,VIVO_VERSION:()=>Vn,WECHAT_VERSION:()=>On,WQQB_VERSION:()=>kn,XWEB_VERSION:()=>Dn,browserInfo:()=>qt,getBrowserInfo:()=>Yu,getChromeMajorVersion:()=>fr,getDeviceModel:()=>_r,getOSName:()=>Fn,getOSNumber:()=>mo,getOSString:()=>Ei,getOSType:()=>Of,getTerminalType:()=>Kd,getUserAgentData:()=>ho,isLocalStorageEnabled:()=>Ti});var Nt=typeof navigator=="undefined"?"":navigator.userAgent,X=s=>new RegExp(s,"i").test(Nt),ye=s=>{if(X(s)){let i=new RegExp(`${s}\\/([\\d.]+)`),e=Nt.match(i);if(e&&e[1])return e[1]}return""},Bd=s=>{if(X(s)){let i=new RegExp(`${s}\\/(\\d+)`),e=Nt.match(i);if(e&&e[1])return parseFloat(e[1])}return NaN},ju=/AppleWebKit\/([\d.]+)/i.exec(Nt),Af=ju?parseFloat(ju[1]):NaN,eo=X("iPad"),Fd=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&X("Macintosh"),mr=X("iPhone")&&!eo,Qu=X("iPod"),ve=mr||eo||Qu||Fd,pe=X("Android"),Hd=function(){if(pe){let s=Nt.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(s){let i=s[1]&&parseFloat(s[1]),e=s[2]&&parseFloat(s[2]);if(i&&e)return parseFloat(`${s[1]}.${s[2]}`);if(i)return i}}return NaN}(),Cf=pe&&X("webkit")&&Hd<2.3,Rf=pe&&Hd<5&&Af<537,ae=X("Firefox"),Cn=ye("Firefox"),$d=Bd("Firefox"),es=X("Edge"),Rn=ye("Edge"),ts=X("Edg"),yn=ye("Edg"),Gd=Bd("Edg"),to=X("SogouMobileBrowser"),bn=ye("SogouMobileBrowser"),io=X("MetaSr\\s"),Nn=ye("MetaSr\\s"),vt=X("TBS"),vn=ye("TBS"),ro=X("XWEB"),Dn=ye("XWEB"),yf=X("MSIE\\s8\\.0"),zu=X("MSIE\\/\\d+"),bf=function(){if(zu){let s=/MSIE\s(\d+)\.\d/.exec(Nt),i=s&&parseFloat(s[1]);return!i&&/Trident\/7.0/i.test(Nt)&&/rv:11.0/.test(Nt)&&(i=11),i}return NaN}(),is=X("(micromessenger|webbrowser)"),On=ye("MicroMessenger"),rs=!vt&&X("MQQBrowser")&&X("COVC"),ss=!vt&&X("MQQBrowser")&&!X("COVC"),Zr=ss||rs?ye("MQQBrowser"):"",so=!vt&&X(" QQBrowser"),kn=ye(" QQBrowser"),oo=!vt&&X("QQBrowserLite"),Mn=ye("QQBrowserLite"),no=!vt&&X("MQBHD"),Ln=ye("MQBHD"),pr=X("Windows"),Dt=!ve&&X("MAC OS X"),ao=!pe&&X("Linux"),Wd=X("CrOS"),Nf=X("MicroMessenger"),Jd=X("UCBrowser"),vf=X("Electron"),co=X("MiuiBrowser"),Pn=ye("MiuiBrowser"),lo=X("HuaweiBrowser"),qd=X("Huawei")||X("HUAWEI"),jd=X("Honor")||X("HONOR"),xn=ye("HuaweiBrowser"),uo=X("SamsungBrowser"),wn=ye("SamsungBrowser"),os=X("HeyTapBrowser"),Un=ye("HeyTapBrowser"),ns=X("VivoBrowser"),Vn=ye("VivoBrowser"),fr=()=>Bd("Chrome"),Ot=X("Chrome"),as=!es&&!io&&!to&&!vt&&!ro&&!ts&&!so&&!co&&!lo&&!uo&&!os&&!ns&&Ot,Xd=X("HeadlessChrome"),kt=fr(),Bn=ye("Chrome"),Be=!Ot&&!ss&&!rs&&!oo&&!no&&X("Safari"),Ji=Be||ve,qi=ye("Version"),Qd=/Android.*(wv|.0.0.0)/.test(Nt),ji=(()=>{if(Fd)return qi;if(ve){let s=Nt.match(/OS (\d+)_(\d+)/i);if(s&&s[1]){let i=s[1];return s[2]&&(i+=`.${s[2]}`),i}}return""})(),at=Number(ji.split(".")[0]),Df=qi==="15.1",zd=ji==="15.1",Yd=(()=>{let s=Number(ji.split(".")[0]);return s===14||s===13})(),Mt=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",Ti=(()=>{let s;return()=>{if(typeof s=="undefined")try{s=!!window.localStorage}catch(i){s=!1}return s}})(),qt=Yu();function Yu(){let s=new Map([[ae,["Firefox",Cn]],[ts,["Edg",yn]],[as,["Chrome",Bn]],[Be,["Safari",qi]],[vt,["TBS",vn]],[ro,["XWEB",Dn]],[is&&mr,["WeChat",On]],[so,["QQ(Win)",kn]],[ss,["QQ(Mobile)",Zr]],[rs,["QQ(Mobile X5)",Zr]],[oo,["QQ(Mac)",Mn]],[no,["QQ(iPad)",Ln]],[co,["MI",Pn]],[lo,["HW",xn]],[uo,["Samsung",wn]],[os,["OPPO",Un]],[ns,["VIVO",Vn]],[es,["EDGE",Rn]],[to,["SogouMobile",bn]],[io,["Sogou",Nn]]]),i="unknown",e="unknown";return s.has(!0)&&([i,e]=s.get(!0)),{name:i,version:e}}var ne=null,bt="";function ho(){return f(this,null,function*(){if(ne)return ne;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return ne=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),ne&&!bt&&(bt=`UAData: ${ne.platform}/${ne.platformVersion}`,ne.architecture&&ne.bitness&&(bt+=` ${ne.architecture}/${ne.bitness}`),ne.mobile&&(bt+=" mobile"),ne.model&&(bt+=` model: ${ne.model}`),ne.fullVersionList&&(bt+=` ${ne.fullVersionList.filter(s=>s.brand!=="Not/A)Brand").map(s=>`${s.brand}/${s.version}`).join(",")}`)),ne}catch(s){return null}})}function _r(){return(ne==null?void 0:ne.model)||""}var Xu=new Map([[pe,"Android"],[ve,"iOS"],[pr,"Windows"],[Dt,"MacOS"],[ao,"Linux"],[Wd,"ChromeOS"]]),Fn=function(){return Xu.get(!0)?Xu.get(!0):ne?ne.platform:"unknown"};function mo(){return pr?1:pe?2:Dt?3:ve?4:ao?5:Wd?6:0}var Ei=()=>{let s=Fn();return s+=`/${qt.name}/${Be?qt.version:qt.version.split(".")[0]}`,ne!=null&&ne.platformVersion&&(s+=`/${ne.platformVersion}`),ne!=null&&ne.architecture&&(s+=`/${ne.architecture}`),s};function Kd(){return pe?4:mr?2:eo?3:Dt?12:pr?5:ao?13:1}function Of(){return pe?"Android":mr?"iPhone":eo?"iPad":Dt?"Mac":pr?"Windows":ao?"Linux":"unknown"}var Ku=Pe(je(),1),kf=new Ku.default,E=kf;var jt=(W=>(W.ROOM_DESTROY="1",W.JOIN_START="21",W.JOIN_SCHEDULE_SUCCESS="22",W.JOIN_SIGNAL_CONNECTION_START="23",W.JOIN_SIGNAL_CONNECTION_END="24",W.JOIN_SEND_CMD="25",W.JOIN_RECEIVED_CMD_RES="26",W.JOIN_SUCCESS="27",W.JOIN_FAILED="28",W.LEAVE_START="51",W.LEAVE_SEND_CMD="52",W.LEAVE_SUCCESS="53",W.PUBLISH_START="61",W.SEND_FIRST_VIDEO_FRAME="62",W.PUBLISH_FAILED="63",W.SUBSCRIBE_START="81",W.SUBSCRIBE_SUCCESS="82",W.SUBSCRIBE_FAILED="84",W.UNSUBSCRIBE_SUCCESS="83",W.LOCAL_TRACK_CAPTURE_START="101",W.LOCAL_TRACK_CAPTURE_SUCCESS="102",W.LOCAL_TRACK_CAPTURE_FAILED="103",W.LOCAL_TRACK_PUBLISHED="104",W.LOCAL_TRACK_UNPUBLISHED="105",W.LOCAL_TRACK_REPLACED="106",W.SWITCH_DEVICE_SUCCESS="107",W.TRACK_MUTED="108",W.TRACK_UNMUTED="109",W.REMOTE_TRACK_SUBSCRIBED="110",W.REMOTE_TRACK_UNSUBSCRIBED="111",W.LOCAL_TRACK_RECAPTURE="112",W.PLAY_TRACK_START="151",W.PLAYER_STATE_CHANGED="152",W.VIDEO_LOADED_DATA="153",W.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",W.SIGNAL_CONNECTION_STATE_CHANGED="201",W.PEER_CONNECTION_STATE_CHANGED="202",W.SINGLE_CONNECTION_STAT="203",W.SPC_RECONNECTED="204",W.HEARTBEAT_REPORT="251",W.RECEIVED_PUBLISHED_USER_LIST="252",W.REMOTE_PUBLISH_STATE_CHANGED="253",W.AUDIO_LEVEL_INTERVAL="260",W.NETWORK_QUALITY="261",W.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",W.QUALITY_LIMITATION_CHANGED="263",W.LOG="264",W.AEC_DEBUG="265",W))(jt||{});var T=jt;var Mf="%cTRTC%c%s",Lf="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",Pf="display: inline",Hn=class Hn{constructor(){d(this,"_isEnableUploadLog",!0);d(this,"_localJoinedUser",new Map);d(this,"_queue",[]);d(this,"_timeoutId",-1);d(this,"_logLevel",1);d(this,"_logLevelToUpload",2);!$r&&!$s&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){E.on(T.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var e;(e=i==null?void 0:i.config)!=null&&e.logLevelToUpload&&At[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),E.on(T.JOIN_SUCCESS,({room:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),E.once(T.JOIN_FAILED,()=>{this.startUpload()}),E.on(T.LEAVE_SUCCESS,({room:i})=>{this.deleteJoinedUser(i.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(i){this._localJoinedUser.set(i.userId,i),this.startUpload()}deleteJoinedUser(i){this._localJoinedUser.delete(i)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),5e3)}getLogsToUpload(){let i={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return i;let e=0;for(;e<this._queue.length&&e!==50;e++){let t=this._queue[e];if(t.forAllJoinedClients)this._localJoinedUser.forEach(({userId:r,sdkAppId:o})=>{i.map.has(r)?i.map.get(r).logs.push(t):i.map.set(r,{userId:r,sdkAppId:o,logs:[t]})});else if(K(t.userId)&&Y(t.sdkAppId)){let{userId:r,sdkAppId:o}=t;i.map.has(r)?i.map.get(r).logs.push(t):i.map.set(r,{userId:r,sdkAppId:o,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 r=[...i.values()];for(let o=0;o<r.length;o++){let{userId:n,sdkAppId:a,logs:c}=r[o];yield this.uploadLogWithRetry(JSON.stringify({timestamp:an(),sdkAppId:String(a),userId:n,version:Re,log:c.map(l=>l.log).join(`
|
|
6
6
|
`)}),a),c.forEach(l=>l.uploaded=!0)}}catch(r){}let t=e.filter(r=>!r.uploaded);t.length>0&&(this._queue=t.concat(this._queue))})}uploadLogWithRetry(i,e){return Jt({retryFunction:()=>_i({url:mi(e,Fi.LOG),body:i,timeout:5e3,priority:"low"}),settings:{retries:3,timeout:2e3},onError:({retry:t})=>{t()}})()}getPrefix(i){let e=new Date;e.setTime(Fs());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}] <${At[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){g(At[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(K(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch(e){return""}}log(i,e,t=!0,r,o){var c;e.unshift(this.getPrefix(i));let n={log:e.reduce((l,h)=>`${l} ${this.logChunkToString(h)}`.trim(),""),level:i,userId:r,sdkAppId:o,forAllJoinedClients:t};if(E.emit(T.LOG,{log:n}),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push(n),i<this._logLevel)return;let a=((c=At[i])==null?void 0:c.toLowerCase())||"info";Hn.PRINT_LOG_TAG?console[a](Mf,Lf,Pf,...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 Kr(i)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),t=e?Number(e):-1;At[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}};d(Hn,"PRINT_LOG_TAG",!(ve||pe||Xd));var Zd=Hn,C=new Zd;var xf=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{let i=Math.random()*16|0;return(s=="x"?i:i&3|8).toString(16)})},po=xf;var ec=class{constructor(){d(this,"_prefix","TRTC");d(this,"_queue",new Map)}getRealKey(i){return`${this._prefix}_${i}`}checkStorage(){if(!Ti())return;setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(t=>{if(t.startsWith(this._prefix))try{let r=localStorage.getItem(t);if(!r)return!1;let o=JSON.parse(r);if(o&&o.expiresIn<Date.now())return!0}catch(r){return!1}return!1}).forEach(t=>localStorage.removeItem(t))}doFlush(){if(Ti())try{for(let[i,e]of this._queue)localStorage.setItem(i,JSON.stringify(e))}catch(i){C.warn(i)}}getItem(i){if(!Ti())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){C.warn(e)}}setItem(i,e){if(Ti())try{let t={expiresIn:Date.now()+ln,value:e};this._queue.set(this.getRealKey(i),t)}catch(t){C.warn(t)}}deleteItem(i){if(!Ti())return!1;try{return i=this.getRealKey(i),this._queue.delete(i),localStorage.removeItem(i),!0}catch(e){return C.warn(e),!1}}clear(){if(Ti())try{localStorage.clear()}catch(i){C.warn(i)}}},cs=new ec;var Yt={};ci(Yt,{HTTPS_API:()=>Zf,IS_GET_CAPABILITIES_SUPPORTED:()=>yc,IS_GET_SETTINGS_SUPPORTED:()=>zt,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>Rc,IS_INSERTABLE_STREAM_SUPPORTED:()=>Ri,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>Kn,IS_RTC_RTP_SENDER_SUPPORTED:()=>Ao,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>Yn,IS_SEI_SUPPORTED:()=>Ro,IS_SPC_SUPPORTED:()=>hs,basis:()=>r_,capabilityCheck:()=>Nc,checkSystemRequirementsInternal:()=>zn,decodeSupportStatus:()=>Qn,encodeSupportStatus:()=>Sc,getBrowserInfo:()=>zf,getDisplayResolution:()=>Eh,isAddTransceiverSupported:()=>gt,isBrowserSupported:()=>Ic,isGetReceiversSupported:()=>Sr,isGetSendersSupported:()=>Ki,isGetTransceiversSupported:()=>Qt,isGetUserMediaSupported:()=>Sh,isMediaDevicesSupported:()=>Xn,isMediaSessionSupported:()=>Rh,isMediaStreamTrackProcessorSupported:()=>Ac,isReplaceTrackSupported:()=>Cc,isRequestVideoFrameCallbackSupported:()=>Ir,isSIMDSupported:()=>i_,isScreenCaptureApiAvailable:()=>So,isSelectedCandidatePair:()=>Yi,isSetParametersSupported:()=>Co,isSmallStreamAPISupported:()=>Ah,isSmallStreamSupported:()=>Io,isStopTransceiverSupported:()=>t_,isTRTCSupported:()=>Yf,isUnifiedPlanDefault:()=>e_,isUsedInHttpProtocol:()=>Ci,isWebAudioSupported:()=>Ih,isWebCodecSupported:()=>Ch,isWebCodecsSupported:()=>Th,isWebRTCSupported:()=>bc,isWebTransportSupported:()=>yh});var mc={};ci(mc,{AUDIO_LEVEL_SCALE:()=>_t,AudioCodecPipelineType:()=>uc,AudioDecoderDowngradeState:()=>sc,AudioPlayerMode:()=>cc,AudioType:()=>ih,BASIC_TYPE:()=>Qi,BannedReason:()=>lc,CONNECTION_CLOSED_REASON:()=>ic,ClientEvent:()=>Zu,CodecType:()=>ah,ConnectionEvent:()=>Lt,ConnectionState:()=>dt,DECODE_FAILED_ERROR_CODE:()=>hc,FacingMode:()=>$n,LeaveReason:()=>nh,LocalTrackEvent:()=>fo,MULTI_VIDEO_DATA_TYPE:()=>Pt,MediaType:()=>De,MediaTypeLabel:()=>wf,MonitorEventId:()=>go,MutedFlag:()=>th,NetworkQualityValue:()=>dc,PlayerState:()=>ls,ReceiveMode:()=>oh,RemoteStreamType:()=>et,RemoteTrackEvent:()=>_o,RoomEvent:()=>Xi,SceneNumber:()=>rc,StreamEvent:()=>eh,StreamType:()=>sh,SubscribeMediaType:()=>tc,TIMER_TYPE:()=>Xt,TRACK_ACTION:()=>ac,TRACK_KIND:()=>nc,TrackEvent:()=>Si,UserRole:()=>Xe,UserRoleNumber:()=>gr,VideoCodec:()=>zi,VideoCodecPipelineType:()=>Wn,VideoContentHint:()=>To,VideoDecoderDowngradeState:()=>oc,VideoPlayerMode:()=>Gn,VideoType:()=>rh});var Lt=(R=>(R.TRACK_ADDED="track-added",R.TRACK_UPDATED="track-updated",R.TRACK_SUBSCRIBED="track-subscribed",R.STREAM_ADDED="stream-added",R.STREAM_REMOVED="stream-removed",R.STREAM_UPDATED="stream-updated",R.STREAM_PUBLISHED="stream-published",R.STREAM_SUBSCRIBED="stream-subscribed",R.STREAM_UNSUBSCRIBED="stream-unsubscribed",R.STATE_CHANGED="state-changed",R.ERROR="error",R.CONNECTION_STATE_CHANGED="connection-state-changed",R.FIREWALL_RESTRICTION="firewall-restriction",R.SEI_MESSAGE="sei-message",R.CLOSED="closed",R))(Lt||{}),ic=(n=>(n.REMOTE_LEAVE="remote user exitRoom",n.REMOTE_UNPUBLISH="remote user unpublished",n.LOCAL_LEAVE="you exitRoom",n.LOCAL_UNPUBLISH="you unpublished",n.LOCAL_UNSUBSCRIBE="you unsubscribed",n.SWITCH_ROLE="you switch role to audience",n))(ic||{}),Zu=(D=>(D.STREAM_ADDED="stream-added",D.STREAM_REMOVED="stream-removed",D.STREAM_UPDATED="stream-updated",D.STREAM_SUBSCRIBED="stream-subscribed",D.CONNECTION_STATE_CHANGED="connection-state-changed",D.PEER_JOIN="peer-join",D.PEER_LEAVE="peer-leave",D.MUTE_AUDIO="mute-audio",D.MUTE_VIDEO="mute-video",D.UNMUTE_AUDIO="unmute-audio",D.UNMUTE_VIDEO="unmute-video",D.CLIENT_BANNED="client-banned",D.NETWORK_QUALITY="network-quality",D.AUDIO_VOLUME="audio-volume",D.SEI_MESSAGE="sei-message",D.ERROR="error",D))(Zu||{}),eh=(o=>(o.PLAYER_STATE_CHANGED="player-state-changed",o.SCREEN_SHARING_STOPPED="screen-sharing-stopped",o.CONNECTION_STATE_CHANGED="connection-state-changed",o.DEVICE_AUTO_RECOVERED="device-auto-recovered",o.ERROR="error",o))(eh||{}),fo=(n=>(n.DEVICE_AUTO_RECOVERED="1",n.DEVICE_RECOVER_FAILED="5",n.DEVICE_CHANGED="2",n.ERROR="3",n.PUBLISH_STATE_CHANGED="4",n.ENCODE_FAILED="6",n))(fo||{}),ls=(t=>(t.PAUSED="PAUSED",t.PLAYING="PLAYING",t.STOPPED="STOPPED",t))(ls||{}),Xi=(te=>(te.PEER_JOIN="peer-join",te.PEER_LEAVE="peer-leave",te.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",te.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",te.BANNED="banned",te.NETWORK_QUALITY="network-quality",te.AUDIO_VOLUME="audio-volume",te.SEI_MESSAGE="sei-message",te.ERROR="error",te.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",te.REMOTE_PUBLISHED="remote-published",te.REMOTE_UNPUBLISHED="remote-unpublished",te.FIREWALL_RESTRICTION="firewall-restriction",te.HEARTBEAT_REPORT="heartbeat-report",te.CUSTOM_MESSAGE="custom-message",te.LAYER_DATA="layerData",te.FIRST_VIDEO_FRAME="first-video-frame",te.DUMP="dump",te))(Xi||{}),Si=(a=>(a.PLAYER_STATE_CHANGED="player-state-changed",a.MUTE="mute",a.UNMUTE="unmute",a.ERROR="error",a.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",a.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",a.FIRST_VIDEO_FRAME="first-video-frame",a))(Si||{}),_o=(e=>(e.DECODE_FAILED="decode-failed",e.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",e))(_o||{}),th=(a=>(a[a.VIDEO=1]="VIDEO",a[a.SMALL=2]="SMALL",a[a.AUX=4]="AUX",a[a.AUDIO=8]="AUDIO",a[a.VIDEO_MUTE=16]="VIDEO_MUTE",a[a.AUX_MUTE=32]="AUX_MUTE",a[a.AUDIO_MUTE=64]="AUDIO_MUTE",a))(th||{}),rc=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(rc||{}),gr=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(gr||{}),Xe=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(Xe||{}),dt=(o=>(o.CONNECTED="CONNECTED",o.DISCONNECTED="DISCONNECTED",o.CONNECTING="CONNECTING",o.RECONNECTED="RECONNECTED",o.RECONNECTING="RECONNECTING",o))(dt||{}),sc=(r=>(r.INITIALIZED="INITIALIZED",r.STARTING="STARTING",r.STARTED="STARTED",r.FAILED="FAILED",r))(sc||{}),oc=(r=>(r.INITIALIZED="INITIALIZED",r.STARTING="STARTING",r.STARTED="STARTED",r.FAILED="FAILED",r))(oc||{}),nc=(t=>(t.AUDIO="audio",t.VIDEO="video",t.AUXILIARY="auxVideo",t))(nc||{}),ac=(e=>(e.ADD="add",e.REMOVE="remove",e))(ac||{}),De=(o=>(o[o.NULL=0]="NULL",o[o.AUDIO=1]="AUDIO",o[o.AUX_VIDEO=2]="AUX_VIDEO",o[o.BIG_VIDEO=4]="BIG_VIDEO",o[o.SMALL_VIDEO=8]="SMALL_VIDEO",o))(De||{}),wf={1:"audio",2:"auxVideo",4:"video"},ih=(i=>(i[i.opus=111]="opus",i))(ih||{}),rh=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(rh||{}),sh=(e=>(e.Big="big",e.Small="small",e))(sh||{}),et=(e=>(e.Main="main",e.Aux="auxiliary",e))(et||{}),Pt=(o=>(o[o.MULTI_DATA_AUDIO=1]="MULTI_DATA_AUDIO",o[o.MULTI_DATA_BIG_IMG=2]="MULTI_DATA_BIG_IMG",o[o.MULTI_DATA_SMALL_IMG=3]="MULTI_DATA_SMALL_IMG",o[o.MULTI_DATA_AUX_IMG=7]="MULTI_DATA_AUX_IMG",o[o.MULTI_DATA_TYPE_BUTT=12]="MULTI_DATA_TYPE_BUTT",o))(Pt||{}),go=(O=>(O[O.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",O[O.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",O[O.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",O[O.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",O[O.MUTE_AUDIO=32772]="MUTE_AUDIO",O[O.MUTE_VIDEO=32773]="MUTE_VIDEO",O[O.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",O[O.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",O[O.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",O[O.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",O[O.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",O[O.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",O[O.SWITCH_CAMERA=32780]="SWITCH_CAMERA",O[O.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",O[O.REPLACE_VIDEO=32782]="REPLACE_VIDEO",O[O.REPLACE_AUDIO=32783]="REPLACE_AUDIO",O[O.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",O[O.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",O[O.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",O[O.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",O[O.JOIN=32788]="JOIN",O[O.LEAVE=32789]="LEAVE",O[O.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",O[O.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",O[O.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",O[O.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",O[O.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",O[O.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",O[O.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",O[O.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",O[O.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",O[O.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",O[O.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",O[O.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",O[O.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",O[O.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",O[O.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",O[O.PUBLISH_AUX=32805]="PUBLISH_AUX",O[O.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",O[O.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",O[O.VIDEO_ENCODER=4004]="VIDEO_ENCODER",O[O.VIDEO_DECODER=4005]="VIDEO_DECODER",O))(go||{}),dc=(a=>(a[a.UNKNOWN=0]="UNKNOWN",a[a.EXCELLENT=1]="EXCELLENT",a[a.GOOD=2]="GOOD",a[a.POOR=3]="POOR",a[a.BAD=4]="BAD",a[a.VERY_BAD=5]="VERY_BAD",a[a.DISCONNECTED=6]="DISCONNECTED",a))(dc||{}),oh=(r=>(r[r.MANUAL=0]="MANUAL",r[r.AUTO_AUDIO=1]="AUTO_AUDIO",r[r.AUTO_VIDEO=2]="AUTO_VIDEO",r[r.AUTO_ALL=3]="AUTO_ALL",r))(oh||{}),$n=(e=>(e.user="user",e.environment="environment",e))($n||{}),Gn=(t=>(t[t.ELEMENT=0]="ELEMENT",t[t.CANVAS_FROM_ELEMENT=1]="CANVAS_FROM_ELEMENT",t[t.CANVAS_WITHOUT_ELEMENT=2]="CANVAS_WITHOUT_ELEMENT",t))(Gn||{}),cc=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(cc||{}),lc=(r=>(r.BANNED="banned",r.KICK="kick",r.USER_TIME_OUT="user_time_out",r.ROOM_DISBAND="room_disband",r))(lc||{}),nh=(l=>(l[l.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",l[l.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",l[l.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",l[l.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",l[l.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",l[l.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",l[l.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",l[l.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",l[l.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",l))(nh||{}),_t=1e8,tc=class{constructor(){d(this,"mediaType",0)}set audio(i){i?this.mediaType|=1:this.mediaType&=-2}get audio(){return!!(this.mediaType&1)}set video(i){i?this.mediaType|=4:this.mediaType&=-5}get video(){return!!(this.mediaType&4)}set auxiliary(i){i?this.mediaType|=2:this.mediaType&=-3}get auxiliary(){return!!(this.mediaType&2)}set smallVideo(i){i?this.mediaType|=8:this.mediaType&=-9}get smallVideo(){return!!(this.mediaType&8)}},Qi=(o=>(o.String="string",o.Number="number",o.Boolean="boolean",o.Array="array",o.Object="object",o))(Qi||{}),zi=(t=>(t.H264="h264",t.H265="h265",t.VP8="vp8",t))(zi||{}),Wn=(r=>(r[r.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",r[r.DUMP=1]="DUMP",r[r.SEI=2]="SEI",r[r.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",r))(Wn||{}),uc=(r=>(r[r.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",r[r.NTP_TO_AUDIO_FRAME=1]="NTP_TO_AUDIO_FRAME",r[r.DUMP=2]="DUMP",r[r.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",r))(uc||{}),ah=(t=>(t.WebRTC="webrtc",t.WebCodecs="webcodecs",t.WebAssembly="webassembly",t))(ah||{}),hc=(u=>(u[u.SUCCESS=0]="SUCCESS",u[u.FAILED=1]="FAILED",u[u.WEBCODEC_INIT=2]="WEBCODEC_INIT",u[u.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",u[u.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",u[u.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",u[u.WASM_INIT=6]="WASM_INIT",u[u.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",u[u.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",u[u.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",u[u.TEST=10]="TEST",u))(hc||{}),To=(r=>(r.NONE="",r.DETAIL="detail",r.MOTION="motion",r.TEXT="text",r))(To||{}),Xt=(o=>(o.INTERVAL="interval",o.TIMEOUT="timeout",o.RAF="raf",o.RIC="ric",o.INTERVAL_IN_WORKER="intervalInWorker",o))(Xt||{});var w={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"},Oe={AVOID_REPEATED_CALL(s){return`previous ${s.name}() is ongoing, please avoid repeated calls.`},INVALID_PARAMETER_REQUIRED({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:s,rule:i,fnName:e,value:t}){let r=`${s||i.name}`,o="";return Array.isArray(i.type)?o=i.type.join("|"):o=i.type,`'${r}' must be type of ${o} when calling ${e}(), received type: ${Ae(t)}.`},INVALID_PARAMETER_EMPTY({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:s,rule:i,fnName:e,value:t}){let r=`${s||i.name}`,o=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${o} when calling ${e}(), received type: ${Ae(t)}.`},INVALID_PARAMETER_RANGE({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_MIN({key:s,rule:i,fnName:e,value:t}){return`the min value of ${s||i.name} is ${i.min}, received: ${t}.`},INVALID_PARAMETER_MAX({key:s,rule:i,fnName:e,value:t}){return`the max value of ${s||i.name} is ${i.max}, received: ${t}.`},API_CALL_TIMEOUT(s){return`${s.commandDesc||s.command} timeout observed.`},SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED(s){return`SignalChannel setup failure: (errorCode: ${s.errorCode}, errorMsg: ${s.errorMsg} }).`},ERROR_MESSAGE(s){let i=`${s.type} failed`;return s.message&&(i=`${i}: ${s.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(s){return`exchange sdp failed ${s.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(s){return`'${s}' must be validate string when useStringRoomId is true.`},INVALID_ROOMID_INTEGER(s){return`'${s}' 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:s,code:i}){return`Failed to join room - ${s} code: ${i}`},REJOIN_ROOM_FAILED(s){return`reJoin room: ${s.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(s){return`duplicate ${s} stream publishing, please unpublish your prev ${s} 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:s,userId:i,streamType:e}){return`failed to subscribe ${i} ${e} stream, reason: ${s}.`},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(s){return`switchRole failed, errCode: ${s.code} errMsg: ${s.message}.`},CLIENT_BANNED(s){return`client was banned because of ${s.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(s){return`startPublishCDNStream failed, errMsg: ${s.message}.`},STOP_PUBLISH_CDN_FAILED(s){return`stopPublishCDNStream failed, errMsg: ${s.message}.`},INVALID_STREAM_ID(s){return`'${s}' 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(s){return`cannot replace ${s.kind} track because stream has not ${s.kind} track`},NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED(s){return`startMixTranscode failed, errMsg: ${s.message}.`},STOP_MIX_TRANSCODE_FAILED(s){return`stopMixTranscode failed, errMsg: ${s.message}.`},MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO({key:s,rule:i,fnName:e,value:t}){return`'${s||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(s){return`'${s}' 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:s,fnName:i})=>`'${s}' is not found in the document object when calling ${i}().`,INVALID_ELEMENT_ID_TYPE:({key:s,fnName:i,type:e})=>`the element corresponding to '${s}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`,PLAY_FAILED:s=>`${s.media} play failed, browser exception: ${s.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(s){return`${s}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(s){return`${s.signalResponse} failed, response code is ${s.code} , errMsg: ${s.message}.`},CATCH_HANDLER_ERROR({name:s,event:i}){return`an error was caught in ${s}.on('${i}', handler), please check your code in 'handler'.`},API_NOT_EXIST({name:s}){return`experimental api ${s} does not exist.`},REPEAT_JOIN:s=>"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:s}){return`failed to call ${s}() because client was destroyed.`},SEI_NOT_SUPPORT:s=>`not support to sendSEIMessage${s===!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:s,name:i,timesInSecond:e,maxSizeInSecond:t})=>`api ${i} call ${s?"size":"times"} is over ${s?`${t} bytes`:e} in a second.`,CONNECTION_ABORTED(s){return`connection aborted due to: ${s}`},API_CALL_ABORTED(s){let i;return s.message.includes("REMOTE_STREAM_NOT_EXIST")?i=`Subscribe ${s.userId} ${s.streamType} stream aborted, reason: remote user ${s.userId} unpublished stream.`:i=`API aborted, reason: ${s.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:s=>`'streamType' is required when 'userId' is not '*', calling ${s}()`};var dh=(s,i)=>i?`${Ft}/${s}/${i}`:`${Ft}/${s}/index.html`;var Uf=()=>{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 s=localStorage==null?void 0:localStorage.getItem(Ad);if(s){s=JSON.parse(s);let i=document.createElement("script");i.type="text/javascript",i.text=s.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 V(s){let{key:i,data:e,link:t,addDocLink:r=!0}=s,o="",n="",a="";oe(Oe[i])?o=Oe[i](e):K(Oe[i])&&(o=Oe[i]);let{TRTC_ERROR_INFO:c,TRTC_ERROR_LINK:l}=Uf();t?a=`${t.className}.html#${t.fnName}`:l&&l[i]&&(oe(l[i])?a=l[i](e):K(l[i])&&(a=l[i]));let h=o;return Rt()&&(c&&c[i]&&(oe(c[i])?n=c[i](e):K(c[i])&&(n=c[i])),n&&(r?h=`${n}
|
|
7
7
|
\u8BF7\u67E5\u770B\u6587\u6863: ${dh("zh-cn",a)}
|
|
8
8
|
|
|
@@ -10,7 +10,7 @@ var xp=Object.create;var Us=Object.defineProperty,wp=Object.defineProperties,Su=
|
|
|
10
10
|
|
|
11
11
|
`,h+=o)),r&&(h+=`
|
|
12
12
|
Refer to: ${dh("en",a)}
|
|
13
|
-
`),h}var Ec=Pe(_h(),1);var qf=1,jf=0,Jn=class{constructor(i=!0){d(this,"countMap",new Map);d(this,"distributionMap",new Map);d(this,"version");d(this,"log",C.createLogger({id:"kv"}));i&&(E.on("102",({track:e,cost:t})=>{this.addSuccessEvent({key:e.kind===m.AUDIO?501700:511700,cost:t})}),E.on("103",({track:e,error:t})=>{this.addFailedEvent({key:e.kind===m.AUDIO?501700:511700,error:t})}))}getReportData(){let i={msg_sdk_basic_info:{uint32_sdk_version:In(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(([r,o])=>({uint32_item_key:r,uint32_item_value:o}))}))};return this.countMap.clear(),this.distributionMap.clear(),i}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(i){let e=+String(i).slice(-3);return e>=700&&e<799}isErrorCodeKey(i){let e=+String(i).slice(-3);return e>=600&&e<699}isCountKey(i){let e=+String(i).slice(-3);return e>=0&&e<599}isNumberKey(i){let e=+String(i).slice(-3);return e>=800&&e<899}addCount({key:i,useUV:e=!1}){if(!this.isCountKey(i)){this.log.debug(`${i} is not count key, last 3 number should be 0~599`);return}e&&this.countMap.has(i)||this.countMap.set(i,(this.countMap.get(i)||0)+1)}addEnum({key:i,value:e,useUV:t=!0}){var o;if(!this.isEnumKey(i))return this.log.debug(`${i} is not enum key, last 3 number should be 700~799`);if(t&&this.countMap.has(i))return;this.countMap.set(i,(this.countMap.get(i)||0)+1);let r=((o=this.distributionMap)==null?void 0:o.get(i))||new Map;r.set(e,(r.get(e)||0)+1),this.distributionMap.set(i,r)}addNumber({key:i,value:e,split:t=100,useUV:r=!1}){var a;if(!this.isNumberKey(i))return this.log.debug(`${i} is not number key, last 3 number should be 800~899`);if(r&&this.countMap.has(i))return;this.countMap.set(i,(this.countMap.get(i)||0)+1);let o=((a=this.distributionMap)==null?void 0:a.get(i))||new Map,n=0;if(Y(t))n=Math.floor(e/t);else for(let c=t.length-1;c>0;c--)if(e>t[c]){n=c;break}o.set(n,(o.get(n)||0)+1),this.distributionMap.set(i,o)}addSuccessEvent({key:i,cost:e,timeKey:t,split:r}){if(i&&(this.addEnum({key:i,value:qf,useUV:!1}),e)){let o=+String(i).slice(-3);o<800&&o>=700?this.addNumber({key:t||i+100,value:e,split:r}):t||this.log.debug(`time stat ignored, ${i}`)}}addFailedEvent({key:i,error:e}){if(!i)return;let t=S.UNKNOWN;e&&(Y(e)?t=e:(!g(e.extraCode)||!g(e.code))&&(t=e.extraCode||e.code)),this.addEnum({key:i,value:jf,useUV:!1}),this.addEnum({key:i,value:t,useUV:!1})}},qn=(j=>(j[j.enterRoom=500700]="enterRoom",j[j.exitRoom=500701]="exitRoom",j[j.switchRole=500702]="switchRole",j[j.destroy=500703]="destroy",j[j.startLocalAudio=500704]="startLocalAudio",j[j.updateLocalAudio=500705]="updateLocalAudio",j[j.stopLocalAudio=500706]="stopLocalAudio",j[j.startLocalVideo=500707]="startLocalVideo",j[j.updateLocalVideo=500708]="updateLocalVideo",j[j.stopLocalVideo=500709]="stopLocalVideo",j[j.startScreenShare=500710]="startScreenShare",j[j.updateScreenShare=500711]="updateScreenShare",j[j.stopScreenShare=500712]="stopScreenShare",j[j.startRemoteVideo=500713]="startRemoteVideo",j[j.updateRemoteVideo=500714]="updateRemoteVideo",j[j.stopRemoteVideo=500715]="stopRemoteVideo",j[j.muteRemoteAudio=500716]="muteRemoteAudio",j[j.setRemoteAudioVolume=500717]="setRemoteAudioVolume",j[j.use=500718]="use",j[j.sendSEIMessage=5e5]="sendSEIMessage",j[j.sendCustomMessage=500001]="sendCustomMessage",j))(qn||{}),_c=(l=>(l[l.AudioMixer=550700]="AudioMixer",l[l.AIDenoiser=551700]="AIDenoiser",l[l.VirtualBackground=570700]="VirtualBackground",l[l.Beauty=571700]="Beauty",l[l.Watermark=572700]="Watermark",l[l.BasicBeauty=574700]="BasicBeauty",l[l.CDNStreaming=590700]="CDNStreaming",l[l.DeviceDetector=591700]="DeviceDetector",l[l.Debug=592700]="Debug",l))(_c||{}),gc=(l=>(l[l.AudioMixer=550701]="AudioMixer",l[l.AIDenoiser=551701]="AIDenoiser",l[l.VirtualBackground=570701]="VirtualBackground",l[l.Beauty=571701]="Beauty",l[l.Watermark=572701]="Watermark",l[l.BasicBeauty=574701]="BasicBeauty",l[l.CDNStreaming=590701]="CDNStreaming",l[l.DeviceDetector=591701]="DeviceDetector",l[l.Debug=592701]="Debug",l))(gc||{}),Tc=(l=>(l[l.AudioMixer=550702]="AudioMixer",l[l.AIDenoiser=551702]="AIDenoiser",l[l.VirtualBackground=570702]="VirtualBackground",l[l.Beauty=571702]="Beauty",l[l.Watermark=572702]="Watermark",l[l.BasicBeauty=574702]="BasicBeauty",l[l.CDNStreaming=590702]="CDNStreaming",l[l.DeviceDetector=591702]="DeviceDetector",l[l.Debug=592702]="Debug",l))(Tc||{});var Xf=new Jn(!0),Er=new Jn(!1);var N=Xf;var ie={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},Qf=new Map([[ae,["Firefox",Cn]],[ts,["Edg",yn]],[as,["Chrome",Bn]],[Ve,["Safari",qi]],[vt,["TBS",vn]],[ro,["XWEB",Dn]],[is&&mr,["WeChat",On]],[so,["QQ(Win)",kn]],[ss,["QQ(Mobile)",Zr]],[rs,["QQ(Mobile X5)",Zr]],[oo,["QQ(Mac)",Mn]],[no,["QQ(iPad)",Ln]],[co,["MI",Pn]],[lo,["HW",xn]],[uo,["Samsung",wn]],[os,["OPPO",Un]],[ns,["VIVO",Vn]],[es,["EDGE",Rn]],[to,["SogouMobile",bn]],[io,["Sogou",Nn]]]);function zf(){let s=Qf.get(!0),i=s?s[0]:"unknown",e=s?s[1]:"unknown";return{browserName:i,browserVersion:e}}var Ic=function(){return!(Jd||es||ts&&Gd<80||ae&&$d<56)},Th=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every(i=>i in window)},Xn=function(){if(!navigator.mediaDevices)return Ci()||C.error(Oe.NOT_SUPPORTED_MEDIA),!1;let s=["getUserMedia","enumerateDevices"];return s.filter(i=>i in navigator.mediaDevices).length===s.length},gh=!1;function Ci(){return location.protocol==="http:"&&!Mt?(gh||C.error(V({key:w.NOT_SUPPORTED_HTTP})),gh=!0,!0):!1}var Ac=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},Sc=function(){return f(this,null,function*(){if(ie.detail.isH264EncodeSupported&&ie.detail.isVp8EncodeSupported)return{isH264EncodeSupported:ie.detail.isH264EncodeSupported,isVp8EncodeSupported:ie.detail.isVp8EncodeSupported};let s,i=!1,e=!1;try{let t=new RTCPeerConnection,r=document.createElement(m.CANVAS);r.getContext("2d");let o=r.captureStream(0);return t.addTrack(o.getVideoTracks()[0],o),s=yield t.createOffer(),s.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),s.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),t.close(),ie.detail.isH264EncodeSupported=i,ie.detail.isVp8EncodeSupported=e,{isH264EncodeSupported:ie.detail.isH264EncodeSupported,isVp8EncodeSupported:ie.detail.isVp8EncodeSupported}}catch(t){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}})},Qn=function(){return f(this,null,function*(){if(ie.detail.isH264DecodeSupported&&ie.detail.isVp8DecodeSupported)return{isH264DecodeSupported:ie.detail.isH264DecodeSupported,isVp8DecodeSupported:ie.detail.isVp8DecodeSupported};let s,i=!1,e=!1;try{let t=new RTCPeerConnection;return s=yield t.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),s.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),s.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),t.close(),{isH264DecodeSupported:i,isVp8DecodeSupported:e}}catch(t){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}})},zn=An(()=>f(void 0,null,function*(){if(ie.result&&ie.detail.isH264EncodeSupported&&ie.detail.isVp8EncodeSupported&&ie.detail.isH264DecodeSupported&&ie.detail.isVp8DecodeSupported)return ie;let s=Date.now(),i=Ic(),e=bc(),t=Th(),r=Xn(),{isH264EncodeSupported:o,isVp8EncodeSupported:n}=yield Sc(),{isH264DecodeSupported:a,isVp8DecodeSupported:c}=yield Qn();if(!o||!n){let l=yield Sc();C.warn(`detect encode again h264:${o} vp8:${n} result: ${JSON.stringify(l)}`),o=l.isH264EncodeSupported,n=l.isVp8EncodeSupported}if(o&&a&&(os||ns||Qd)&&!vt&&fr()<79){let{encode:l,decode:h}=yield Kf();o=l,a=h}return ie.result=i&&e&&r&&(o||n)&&(a||c),ie.detail.isBrowserSupported=i,ie.detail.isWebRTCSupported=e,ie.detail.isWebCodecsSupported=t,ie.detail.isMediaDevicesSupported=r,ie.detail.isScreenShareSupported=So(),ie.detail.isSmallStreamSupported=Io(),ie.detail.isH264EncodeSupported=o,ie.detail.isVp8EncodeSupported=n,ie.detail.isH264DecodeSupported=a,ie.detail.isVp8DecodeSupported=c,ie.result||C.error(`${navigator.userAgent} ${En(ie.detail,!1)}`),s_(),N.addNumber({key:523800,value:Date.now()-s}),ie})),Yf=function(){return ie.result},So=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},jn=null;function Kf(){return f(this,null,function*(){return jn||(jn=new Promise(s=>f(this,null,function*(){let i={encode:!1,decode:!1},e=()=>{};try{C.warn("detectH264Supported start");let t=document.createElement("canvas"),r=t.getContext("2d");t.width=320,t.height=240;let o=setInterval(()=>{r.fillText("test",Math.floor(Math.random()*320),Math.floor(Math.random()*240))},66),n=-1,a=-1;e=()=>{clearInterval(n),clearInterval(o),clearTimeout(a),l.close(),h.close(),c.getTracks().forEach(R=>R.stop())},a=setTimeout(()=>{e(),s(i)},2*1e3);let c=t.captureStream(),l=new RTCPeerConnection({}),h=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});l.addEventListener("icecandidate",R=>h.addIceCandidate(R.candidate)),h.addEventListener("icecandidate",R=>l.addIceCandidate(R.candidate)),l.addTrack(c.getVideoTracks()[0],c);let u=yield l.createOffer();yield l.setLocalDescription(u),yield h.setRemoteDescription(u);let p=yield h.createAnswer(),_=Ec.default.parse(p.sdp),I=_.media[0].rtp.findIndex(R=>R.codec==="H264");_.media[0].rtp=[_.media[0].rtp[I]],_.media[0].fmtp=_.media[0].fmtp.filter(R=>R.payload===_.media[0].rtp[0].payload),_.media[0].rtcpFb&&(_.media[0].rtcpFb=_.media[0].rtcpFb.filter(R=>R.payload===_.media[0].rtp[0].payload)),p.sdp=Ec.default.write(_),yield h.setLocalDescription(p),yield l.setRemoteDescription(p),n=setInterval(()=>f(this,null,function*(){i.encode&&i.decode&&(e(),s(i));let R=yield l.getSenders()[0].getStats(),D=yield h.getReceivers()[0].getStats();i.encode||R.forEach(G=>{G.type==="outbound-rtp"&&G.mediaType===m.VIDEO&&G.bytesSent>0&&(i.encode=!0)}),i.decode||D.forEach(G=>{G.type==="inbound-rtp"&&G.mediaType===m.VIDEO&&G.bytesReceived>0&&(i.decode=!0)})}),100)}catch(t){e(),C.warn(t),s(i)}})).then(s=>((!s.encode||!s.decode)&&C.warn(`detectH264Supported encode: ${s.encode} decode: ${s.decode} ${bt}`),s)),jn)})}var Zf=(s,i,e)=>{location.protocol==="http:"&&!Mt&&(s[i]=()=>{throw new b({code:S.INVALID_OPERATION,message:Oe.NOT_SUPPORTED_HTTP})})},Yi=function(s){return s.type==="candidate-pair"&&s.nominated&&(s.state==="in-progress"||s.state==="succeeded")?!(me(s.selected)&&!s.selected):!1};function Eh(){let s="";if(screen.width){let i=screen.width?screen.width*window.devicePixelRatio:"",e=screen.height?screen.height*window.devicePixelRatio:"";s+=`${i} * ${e}`}return s}function Sh(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function Ih(){let s={isSupported:!1},i=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let e=0;e<i.length;e++)if(i[e]in window){s.isSupported=!0;break}return s.isSupported}function Ah(){return"captureStream"in HTMLCanvasElement.prototype}function Io(){return is||ve||kt&&kt<63?!1:!!(Ic()&&Ah())}var e_=function(){if(g(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let s=null,i=!1;try{s=new RTCPeerConnection({sdpSemantics:Gi}),s.addTransceiver(m.AUDIO),i=!0}catch(e){}return s==null||s.close(),i};function Sr(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function Ki(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function Qt(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function gt(){return at===11?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var hs=!(!gt()||Ot&&kt<86);function t_(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var Ao="RTCRtpSender"in window;function Cc(){return Ao&&"replaceTrack"in window.RTCRtpSender.prototype}function Co(){return Ao&&"setParameters"in window.RTCRtpSender.prototype&&Ki()}var Rc="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,zt=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,yc=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,Ri=Ao&&"createEncodedStreams"in window.RTCRtpSender.prototype&&fr()>=86,Yn="RTCRtpScriptTransform"in window,Ro=Ao&&(Ri||Yn),bc=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(i=>i in window).length>0};function Ch(){let s={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return g(window.AudioDecoder)||(s.AudioDecoder=!0),g(window.AudioEncoder)||(s.AudioEncoder=!0),g(window.VideoDecoder)||(s.VideoDecoder=!0),g(window.VideoEncoder)||(s.VideoEncoder=!0),g(window.ImageDecoder)||(s.ImageDecoder=!0),s}function Rh(){return"mediaSession"in navigator&&!g(navigator.mediaSession.setActionHandler)}function yh(){return!g(window.WebTransport)}function i_(){return typeof WebAssembly=="undefined"?!1:WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]))}function r_(){let s={browser:`${qt.name}/${qt.version}`,os:Fn(),displayResolution:Eh(),isScreenShareSupported:So(),isWebRTCSupported:bc(),isGetUserMediaSupported:Sh(),isWebAudioSupported:Ih(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:Ch(),isMediaSessionSupported:Rh(),isWebTransportSupported:yh()};return navigator.userAgent.includes("miniProgram")&&(s.browser=`mini/${s.browser}`),s}var bh="checkResult";function s_(){cs.setItem(bh,{ua:navigator.userAgent,checkResult:ie})}function Nc(){Ci();let s=cs.getItem(bh);s&&s.ua===navigator.userAgent&&(ie=s.checkResult),zn()}function Ir(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var Kn="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;var vh=Pe(je(),1);var Nh=Symbol("instance"),gS=Symbol("abortCtrl"),Zn=Symbol("cacheResult"),yo=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,vo.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},bo=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function o_(s){return typeof s=="object"&&s&&"then"in s}var No=new Map;function le(s,i,e={}){return(t,r,o)=>{let n=e.action||r;if(!e.context){let c=No.get(t)||[];No.has(t)||No.set(t,c),c.push({from:s,to:i,action:n})}let a=o.value;o.value=function(...c){let l=this;if(e.context&&(l=Q.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),l.state===i)return e.sync?l[Zn]:Promise.resolve(l[Zn]);l.state instanceof yo&&l.state.action==e.abortAction&&l.state.abort(l);let h=null;Array.isArray(s)?s.length==0?l.state instanceof yo&&l.state.abort(l):(typeof l.state!="string"||!s.includes(l.state))&&(h=new bo(l._state,`${l.name} ${n} to ${i} failed: current state ${l._state} not from ${s.join("|")}`)):s!==l.state&&(h=new bo(l._state,`${l.name} ${n} to ${i} failed: current state ${l._state} not from ${s}`));let u=D=>{if(e.fail&&e.fail.call(this,D),e.sync){if(e.ignoreError)return D;throw D}else return e.ignoreError?Promise.resolve(D):Promise.reject(D)};if(h)return u(h);let p=l.state,_=new yo(p,i,n);vo.call(l,_);let I=D=>{var G;return l[Zn]=D,_.aborted||(vo.call(l,i),(G=e.success)===null||G===void 0||G.call(this,l[Zn])),D},R=D=>(vo.call(l,p,D),u(D));try{let D=a.apply(this,c);return o_(D)?D.then(I).catch(R):e.sync?I(D):Promise.resolve(I(D))}catch(D){return R(new bo(l._state,`${l.name} ${n} from ${s} to ${i} failed: ${D}`,D instanceof Error?D:new Error(String(D))))}}}}var n_=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 vo(s,i){let e=this._state;this._state=s;let t=s.toString();s&&this.emit(t,e),this.emit(Q.STATECHANGED,s,e,i),this.updateDevTools({value:s,old:e,err:i instanceof Error?i.message:String(i)})}var Q=class s extends vh.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=s.INIT,i||(i=Date.now().toString(36)),t?Object.setPrototypeOf(this,t):t=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let r=t[Nh];r?this.name=r.name+"-"+r.count++:t[Nh]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=No.get(i)||[],t=new Set,r=[],o=[],n=new Set,a=Object.getPrototypeOf(i);No.has(a)&&(a.stateDiagram.forEach(l=>t.add(l)),a.allStates.forEach(l=>n.add(l))),e.forEach(({from:l,to:h,action:u})=>{typeof l=="string"?r.push({from:l,to:h,action:u}):l.length?l.forEach(p=>{r.push({from:p,to:h,action:u})}):o.push({to:h,action:u})}),r.forEach(({from:l,to:h,action:u})=>{n.add(l),n.add(h),n.add(u+"ing"),t.add(`${l} --> ${u}ing : ${u}`),t.add(`${u}ing --> ${h} : ${u} \u{1F7E2}`),t.add(`${u}ing --> ${l} : ${u} \u{1F534}`)}),o.forEach(({to:l,action:h})=>{t.add(`${h}ing --> ${l} : ${h} \u{1F7E2}`),n.forEach(u=>{u!==l&&t.add(`${u} --> ${h}ing : ${h}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:n}}),c}static get(i){let e;return typeof i=="string"?(e=s.instances.get(i),e||s.instances.set(i,e=new s(i,void 0,Object.create(s.prototype)))):(e=s.instances2.get(i),e||s.instances2.set(i,e=new s(i.constructor.name,void 0,Object.create(s.prototype)))),e}static getState(i){var e;return(e=s.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){n_(s.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){vo.call(this,i)}};Q.STATECHANGED="stateChanged";Q.UPDATEAFSM="updateAFSM";Q.INIT="[*]";Q.ON="on";Q.OFF="off";Q.instances=new Map;Q.instances2=new WeakMap;var Dc=typeof window!="undefined",Dh=Dc&&window.requestIdleCallback||function(s){let i=Date.now();return setTimeout(()=>{s({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-i))}})},1e3)},a_=Dc&&window.cancelIdleCallback||function(s){clearTimeout(s)},Oh=Dc&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),Ce=class Ce{static generateTaskID(){return this.currentTaskID++}static run(i,e,t){t!=null&&t.fps&&(t.delay=t.delay||Number((1e3/t.fps).toFixed(2))),i==="interval"?t=v({delay:2e3,count:0,backgroundTask:!0},t):i==="ric"?t=v({delay:1e4,count:0},t):i==="raf"?t=v({fps:60,delay:16.6,count:0,backgroundTask:!0},t):t=v({delay:2e3,count:0,backgroundTask:!0},t);let r=k(v({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:i,callback:e},t),{delay:t.delay});return this.taskMap.set(r.taskID,r),this[i](r),r.taskID}static interval(i){let e=()=>{i.callback(),i.loopCount+=1,Ce.isBreakLoop(i)};return i.intervalID=setInterval(e,i.delay)}static intervalInWorker(i){Ce.sharedWorker||(Ce.sharedWorker=new Worker(URL.createObjectURL(new Blob([`
|
|
13
|
+
`),h}var Ec=Pe(_h(),1);var qf=1,jf=0,Jn=class{constructor(i=!0){d(this,"countMap",new Map);d(this,"distributionMap",new Map);d(this,"version");d(this,"log",C.createLogger({id:"kv"}));i&&(E.on("102",({track:e,cost:t})=>{this.addSuccessEvent({key:e.kind===m.AUDIO?501700:511700,cost:t})}),E.on("103",({track:e,error:t})=>{this.addFailedEvent({key:e.kind===m.AUDIO?501700:511700,error:t})}))}getReportData(){let i={msg_sdk_basic_info:{uint32_sdk_version:In(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(([r,o])=>({uint32_item_key:r,uint32_item_value:o}))}))};return this.countMap.clear(),this.distributionMap.clear(),i}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(i){let e=+String(i).slice(-3);return e>=700&&e<799}isErrorCodeKey(i){let e=+String(i).slice(-3);return e>=600&&e<699}isCountKey(i){let e=+String(i).slice(-3);return e>=0&&e<599}isNumberKey(i){let e=+String(i).slice(-3);return e>=800&&e<899}addCount({key:i,useUV:e=!1}){if(!this.isCountKey(i)){this.log.debug(`${i} is not count key, last 3 number should be 0~599`);return}e&&this.countMap.has(i)||this.countMap.set(i,(this.countMap.get(i)||0)+1)}addEnum({key:i,value:e,useUV:t=!0}){var o;if(!this.isEnumKey(i))return this.log.debug(`${i} is not enum key, last 3 number should be 700~799`);if(t&&this.countMap.has(i))return;this.countMap.set(i,(this.countMap.get(i)||0)+1);let r=((o=this.distributionMap)==null?void 0:o.get(i))||new Map;r.set(e,(r.get(e)||0)+1),this.distributionMap.set(i,r)}addNumber({key:i,value:e,split:t=100,useUV:r=!1}){var a;if(!this.isNumberKey(i))return this.log.debug(`${i} is not number key, last 3 number should be 800~899`);if(r&&this.countMap.has(i))return;this.countMap.set(i,(this.countMap.get(i)||0)+1);let o=((a=this.distributionMap)==null?void 0:a.get(i))||new Map,n=0;if(Y(t))n=Math.floor(e/t);else for(let c=t.length-1;c>0;c--)if(e>t[c]){n=c;break}o.set(n,(o.get(n)||0)+1),this.distributionMap.set(i,o)}addSuccessEvent({key:i,cost:e,timeKey:t,split:r}){if(i&&(this.addEnum({key:i,value:qf,useUV:!1}),e)){let o=+String(i).slice(-3);o<800&&o>=700?this.addNumber({key:t||i+100,value:e,split:r}):t||this.log.debug(`time stat ignored, ${i}`)}}addFailedEvent({key:i,error:e}){if(!i)return;let t=S.UNKNOWN;e&&(Y(e)?t=e:(!g(e.extraCode)||!g(e.code))&&(t=e.extraCode||e.code)),this.addEnum({key:i,value:jf,useUV:!1}),this.addEnum({key:i,value:t,useUV:!1})}},qn=(j=>(j[j.enterRoom=500700]="enterRoom",j[j.exitRoom=500701]="exitRoom",j[j.switchRole=500702]="switchRole",j[j.destroy=500703]="destroy",j[j.startLocalAudio=500704]="startLocalAudio",j[j.updateLocalAudio=500705]="updateLocalAudio",j[j.stopLocalAudio=500706]="stopLocalAudio",j[j.startLocalVideo=500707]="startLocalVideo",j[j.updateLocalVideo=500708]="updateLocalVideo",j[j.stopLocalVideo=500709]="stopLocalVideo",j[j.startScreenShare=500710]="startScreenShare",j[j.updateScreenShare=500711]="updateScreenShare",j[j.stopScreenShare=500712]="stopScreenShare",j[j.startRemoteVideo=500713]="startRemoteVideo",j[j.updateRemoteVideo=500714]="updateRemoteVideo",j[j.stopRemoteVideo=500715]="stopRemoteVideo",j[j.muteRemoteAudio=500716]="muteRemoteAudio",j[j.setRemoteAudioVolume=500717]="setRemoteAudioVolume",j[j.use=500718]="use",j[j.sendSEIMessage=5e5]="sendSEIMessage",j[j.sendCustomMessage=500001]="sendCustomMessage",j))(qn||{}),_c=(l=>(l[l.AudioMixer=550700]="AudioMixer",l[l.AIDenoiser=551700]="AIDenoiser",l[l.VirtualBackground=570700]="VirtualBackground",l[l.Beauty=571700]="Beauty",l[l.Watermark=572700]="Watermark",l[l.BasicBeauty=574700]="BasicBeauty",l[l.CDNStreaming=590700]="CDNStreaming",l[l.DeviceDetector=591700]="DeviceDetector",l[l.Debug=592700]="Debug",l))(_c||{}),gc=(l=>(l[l.AudioMixer=550701]="AudioMixer",l[l.AIDenoiser=551701]="AIDenoiser",l[l.VirtualBackground=570701]="VirtualBackground",l[l.Beauty=571701]="Beauty",l[l.Watermark=572701]="Watermark",l[l.BasicBeauty=574701]="BasicBeauty",l[l.CDNStreaming=590701]="CDNStreaming",l[l.DeviceDetector=591701]="DeviceDetector",l[l.Debug=592701]="Debug",l))(gc||{}),Tc=(l=>(l[l.AudioMixer=550702]="AudioMixer",l[l.AIDenoiser=551702]="AIDenoiser",l[l.VirtualBackground=570702]="VirtualBackground",l[l.Beauty=571702]="Beauty",l[l.Watermark=572702]="Watermark",l[l.BasicBeauty=574702]="BasicBeauty",l[l.CDNStreaming=590702]="CDNStreaming",l[l.DeviceDetector=591702]="DeviceDetector",l[l.Debug=592702]="Debug",l))(Tc||{});var Xf=new Jn(!0),Er=new Jn(!1);var N=Xf;var ie={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},Qf=new Map([[ae,["Firefox",Cn]],[ts,["Edg",yn]],[as,["Chrome",Bn]],[Be,["Safari",qi]],[vt,["TBS",vn]],[ro,["XWEB",Dn]],[is&&mr,["WeChat",On]],[so,["QQ(Win)",kn]],[ss,["QQ(Mobile)",Zr]],[rs,["QQ(Mobile X5)",Zr]],[oo,["QQ(Mac)",Mn]],[no,["QQ(iPad)",Ln]],[co,["MI",Pn]],[lo,["HW",xn]],[uo,["Samsung",wn]],[os,["OPPO",Un]],[ns,["VIVO",Vn]],[es,["EDGE",Rn]],[to,["SogouMobile",bn]],[io,["Sogou",Nn]]]);function zf(){let s=Qf.get(!0),i=s?s[0]:"unknown",e=s?s[1]:"unknown";return{browserName:i,browserVersion:e}}var Ic=function(){return!(Jd||es||ts&&Gd<80||ae&&$d<56)},Th=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every(i=>i in window)},Xn=function(){if(!navigator.mediaDevices)return Ci()||C.error(Oe.NOT_SUPPORTED_MEDIA),!1;let s=["getUserMedia","enumerateDevices"];return s.filter(i=>i in navigator.mediaDevices).length===s.length},gh=!1;function Ci(){return location.protocol==="http:"&&!Mt?(gh||C.error(V({key:w.NOT_SUPPORTED_HTTP})),gh=!0,!0):!1}var Ac=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},Sc=function(){return f(this,null,function*(){if(ie.detail.isH264EncodeSupported&&ie.detail.isVp8EncodeSupported)return{isH264EncodeSupported:ie.detail.isH264EncodeSupported,isVp8EncodeSupported:ie.detail.isVp8EncodeSupported};let s,i=!1,e=!1;try{let t=new RTCPeerConnection,r=document.createElement(m.CANVAS);r.getContext("2d");let o=r.captureStream(0);return t.addTrack(o.getVideoTracks()[0],o),s=yield t.createOffer(),s.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),s.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),t.close(),ie.detail.isH264EncodeSupported=i,ie.detail.isVp8EncodeSupported=e,{isH264EncodeSupported:ie.detail.isH264EncodeSupported,isVp8EncodeSupported:ie.detail.isVp8EncodeSupported}}catch(t){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}})},Qn=function(){return f(this,null,function*(){if(ie.detail.isH264DecodeSupported&&ie.detail.isVp8DecodeSupported)return{isH264DecodeSupported:ie.detail.isH264DecodeSupported,isVp8DecodeSupported:ie.detail.isVp8DecodeSupported};let s,i=!1,e=!1;try{let t=new RTCPeerConnection;return s=yield t.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),s.sdp.toLowerCase().indexOf("h264")!==-1&&(i=!0),s.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),t.close(),{isH264DecodeSupported:i,isVp8DecodeSupported:e}}catch(t){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}})},zn=An(()=>f(void 0,null,function*(){if(ie.result&&ie.detail.isH264EncodeSupported&&ie.detail.isVp8EncodeSupported&&ie.detail.isH264DecodeSupported&&ie.detail.isVp8DecodeSupported)return ie;let s=Date.now(),i=Ic(),e=bc(),t=Th(),r=Xn(),{isH264EncodeSupported:o,isVp8EncodeSupported:n}=yield Sc(),{isH264DecodeSupported:a,isVp8DecodeSupported:c}=yield Qn();if(!o||!n){let l=yield Sc();C.warn(`detect encode again h264:${o} vp8:${n} result: ${JSON.stringify(l)}`),o=l.isH264EncodeSupported,n=l.isVp8EncodeSupported}if(o&&a&&(os||ns||Qd)&&!vt&&fr()<79){let{encode:l,decode:h}=yield Kf();o=l,a=h}return ie.result=i&&e&&r&&(o||n)&&(a||c),ie.detail.isBrowserSupported=i,ie.detail.isWebRTCSupported=e,ie.detail.isWebCodecsSupported=t,ie.detail.isMediaDevicesSupported=r,ie.detail.isScreenShareSupported=So(),ie.detail.isSmallStreamSupported=Io(),ie.detail.isH264EncodeSupported=o,ie.detail.isVp8EncodeSupported=n,ie.detail.isH264DecodeSupported=a,ie.detail.isVp8DecodeSupported=c,ie.result||C.error(`${navigator.userAgent} ${En(ie.detail,!1)}`),s_(),N.addNumber({key:523800,value:Date.now()-s}),ie})),Yf=function(){return ie.result},So=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},jn=null;function Kf(){return f(this,null,function*(){return jn||(jn=new Promise(s=>f(this,null,function*(){let i={encode:!1,decode:!1},e=()=>{};try{C.warn("detectH264Supported start");let t=document.createElement("canvas"),r=t.getContext("2d");t.width=320,t.height=240;let o=setInterval(()=>{r.fillText("test",Math.floor(Math.random()*320),Math.floor(Math.random()*240))},66),n=-1,a=-1;e=()=>{clearInterval(n),clearInterval(o),clearTimeout(a),l.close(),h.close(),c.getTracks().forEach(R=>R.stop())},a=setTimeout(()=>{e(),s(i)},2*1e3);let c=t.captureStream(),l=new RTCPeerConnection({}),h=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});l.addEventListener("icecandidate",R=>h.addIceCandidate(R.candidate)),h.addEventListener("icecandidate",R=>l.addIceCandidate(R.candidate)),l.addTrack(c.getVideoTracks()[0],c);let u=yield l.createOffer();yield l.setLocalDescription(u),yield h.setRemoteDescription(u);let p=yield h.createAnswer(),_=Ec.default.parse(p.sdp),I=_.media[0].rtp.findIndex(R=>R.codec==="H264");_.media[0].rtp=[_.media[0].rtp[I]],_.media[0].fmtp=_.media[0].fmtp.filter(R=>R.payload===_.media[0].rtp[0].payload),_.media[0].rtcpFb&&(_.media[0].rtcpFb=_.media[0].rtcpFb.filter(R=>R.payload===_.media[0].rtp[0].payload)),p.sdp=Ec.default.write(_),yield h.setLocalDescription(p),yield l.setRemoteDescription(p),n=setInterval(()=>f(this,null,function*(){i.encode&&i.decode&&(e(),s(i));let R=yield l.getSenders()[0].getStats(),D=yield h.getReceivers()[0].getStats();i.encode||R.forEach(G=>{G.type==="outbound-rtp"&&G.mediaType===m.VIDEO&&G.bytesSent>0&&(i.encode=!0)}),i.decode||D.forEach(G=>{G.type==="inbound-rtp"&&G.mediaType===m.VIDEO&&G.bytesReceived>0&&(i.decode=!0)})}),100)}catch(t){e(),C.warn(t),s(i)}})).then(s=>((!s.encode||!s.decode)&&C.warn(`detectH264Supported encode: ${s.encode} decode: ${s.decode} ${bt}`),s)),jn)})}var Zf=(s,i,e)=>{location.protocol==="http:"&&!Mt&&(s[i]=()=>{throw new b({code:S.INVALID_OPERATION,message:Oe.NOT_SUPPORTED_HTTP})})},Yi=function(s){return s.type==="candidate-pair"&&s.nominated&&(s.state==="in-progress"||s.state==="succeeded")?!(me(s.selected)&&!s.selected):!1};function Eh(){let s="";if(screen.width){let i=screen.width?screen.width*window.devicePixelRatio:"",e=screen.height?screen.height*window.devicePixelRatio:"";s+=`${i} * ${e}`}return s}function Sh(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function Ih(){let s={isSupported:!1},i=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let e=0;e<i.length;e++)if(i[e]in window){s.isSupported=!0;break}return s.isSupported}function Ah(){return"captureStream"in HTMLCanvasElement.prototype}function Io(){return is||ve||kt&&kt<63?!1:!!(Ic()&&Ah())}var e_=function(){if(g(window.RTCRtpTransceiver)||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let s=null,i=!1;try{s=new RTCPeerConnection({sdpSemantics:Gi}),s.addTransceiver(m.AUDIO),i=!0}catch(e){}return s==null||s.close(),i};function Sr(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function Ki(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function Qt(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function gt(){return at===11?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var hs=!(!gt()||Ot&&kt<86);function t_(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var Ao="RTCRtpSender"in window;function Cc(){return Ao&&"replaceTrack"in window.RTCRtpSender.prototype}function Co(){return Ao&&"setParameters"in window.RTCRtpSender.prototype&&Ki()}var Rc="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,zt=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,yc=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,Ri=Ao&&"createEncodedStreams"in window.RTCRtpSender.prototype&&fr()>=86,Yn="RTCRtpScriptTransform"in window,Ro=Ao&&(Ri||Yn),bc=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(i=>i in window).length>0};function Ch(){let s={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return g(window.AudioDecoder)||(s.AudioDecoder=!0),g(window.AudioEncoder)||(s.AudioEncoder=!0),g(window.VideoDecoder)||(s.VideoDecoder=!0),g(window.VideoEncoder)||(s.VideoEncoder=!0),g(window.ImageDecoder)||(s.ImageDecoder=!0),s}function Rh(){return"mediaSession"in navigator&&!g(navigator.mediaSession.setActionHandler)}function yh(){return!g(window.WebTransport)}function i_(){return typeof WebAssembly=="undefined"?!1:WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]))}function r_(){let s={browser:`${qt.name}/${qt.version}`,os:Fn(),displayResolution:Eh(),isScreenShareSupported:So(),isWebRTCSupported:bc(),isGetUserMediaSupported:Sh(),isWebAudioSupported:Ih(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:Ch(),isMediaSessionSupported:Rh(),isWebTransportSupported:yh()};return navigator.userAgent.includes("miniProgram")&&(s.browser=`mini/${s.browser}`),s}var bh="checkResult";function s_(){cs.setItem(bh,{ua:navigator.userAgent,checkResult:ie})}function Nc(){Ci();let s=cs.getItem(bh);s&&s.ua===navigator.userAgent&&(ie=s.checkResult),zn()}function Ir(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var Kn="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;var vh=Pe(je(),1);var Nh=Symbol("instance"),gS=Symbol("abortCtrl"),Zn=Symbol("cacheResult"),yo=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,vo.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},bo=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function o_(s){return typeof s=="object"&&s&&"then"in s}var No=new Map;function le(s,i,e={}){return(t,r,o)=>{let n=e.action||r;if(!e.context){let c=No.get(t)||[];No.has(t)||No.set(t,c),c.push({from:s,to:i,action:n})}let a=o.value;o.value=function(...c){let l=this;if(e.context&&(l=Q.get(typeof e.context=="function"?e.context.call(this,...c):e.context)),l.state===i)return e.sync?l[Zn]:Promise.resolve(l[Zn]);l.state instanceof yo&&l.state.action==e.abortAction&&l.state.abort(l);let h=null;Array.isArray(s)?s.length==0?l.state instanceof yo&&l.state.abort(l):(typeof l.state!="string"||!s.includes(l.state))&&(h=new bo(l._state,`${l.name} ${n} to ${i} failed: current state ${l._state} not from ${s.join("|")}`)):s!==l.state&&(h=new bo(l._state,`${l.name} ${n} to ${i} failed: current state ${l._state} not from ${s}`));let u=D=>{if(e.fail&&e.fail.call(this,D),e.sync){if(e.ignoreError)return D;throw D}else return e.ignoreError?Promise.resolve(D):Promise.reject(D)};if(h)return u(h);let p=l.state,_=new yo(p,i,n);vo.call(l,_);let I=D=>{var G;return l[Zn]=D,_.aborted||(vo.call(l,i),(G=e.success)===null||G===void 0||G.call(this,l[Zn])),D},R=D=>(vo.call(l,p,D),u(D));try{let D=a.apply(this,c);return o_(D)?D.then(I).catch(R):e.sync?I(D):Promise.resolve(I(D))}catch(D){return R(new bo(l._state,`${l.name} ${n} from ${s} to ${i} failed: ${D}`,D instanceof Error?D:new Error(String(D))))}}}}var n_=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 vo(s,i){let e=this._state;this._state=s;let t=s.toString();s&&this.emit(t,e),this.emit(Q.STATECHANGED,s,e,i),this.updateDevTools({value:s,old:e,err:i instanceof Error?i.message:String(i)})}var Q=class s extends vh.default{constructor(i,e,t){super(),this.name=i,this.groupName=e,this._state=s.INIT,i||(i=Date.now().toString(36)),t?Object.setPrototypeOf(this,t):t=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let r=t[Nh];r?this.name=r.name+"-"+r.count++:t[Nh]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=No.get(i)||[],t=new Set,r=[],o=[],n=new Set,a=Object.getPrototypeOf(i);No.has(a)&&(a.stateDiagram.forEach(l=>t.add(l)),a.allStates.forEach(l=>n.add(l))),e.forEach(({from:l,to:h,action:u})=>{typeof l=="string"?r.push({from:l,to:h,action:u}):l.length?l.forEach(p=>{r.push({from:p,to:h,action:u})}):o.push({to:h,action:u})}),r.forEach(({from:l,to:h,action:u})=>{n.add(l),n.add(h),n.add(u+"ing"),t.add(`${l} --> ${u}ing : ${u}`),t.add(`${u}ing --> ${h} : ${u} \u{1F7E2}`),t.add(`${u}ing --> ${l} : ${u} \u{1F534}`)}),o.forEach(({to:l,action:h})=>{t.add(`${h}ing --> ${l} : ${h} \u{1F7E2}`),n.forEach(u=>{u!==l&&t.add(`${u} --> ${h}ing : ${h}`)})});let c=[...t];return Object.defineProperties(i,{stateDiagram:{value:c},allStates:{value:n}}),c}static get(i){let e;return typeof i=="string"?(e=s.instances.get(i),e||s.instances.set(i,e=new s(i,void 0,Object.create(s.prototype)))):(e=s.instances2.get(i),e||s.instances2.set(i,e=new s(i.constructor.name,void 0,Object.create(s.prototype)))),e}static getState(i){var e;return(e=s.get(i))===null||e===void 0?void 0:e.state}updateDevTools(i={}){n_(s.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){vo.call(this,i)}};Q.STATECHANGED="stateChanged";Q.UPDATEAFSM="updateAFSM";Q.INIT="[*]";Q.ON="on";Q.OFF="off";Q.instances=new Map;Q.instances2=new WeakMap;var Dc=typeof window!="undefined",Dh=Dc&&window.requestIdleCallback||function(s){let i=Date.now();return setTimeout(()=>{s({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-i))}})},1e3)},a_=Dc&&window.cancelIdleCallback||function(s){clearTimeout(s)},Oh=Dc&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),Ce=class Ce{static generateTaskID(){return this.currentTaskID++}static run(i,e,t){t!=null&&t.fps&&(t.delay=t.delay||Number((1e3/t.fps).toFixed(2))),i==="interval"?t=v({delay:2e3,count:0,backgroundTask:!0},t):i==="ric"?t=v({delay:1e4,count:0},t):i==="raf"?t=v({fps:60,delay:16.6,count:0,backgroundTask:!0},t):t=v({delay:2e3,count:0,backgroundTask:!0},t);let r=k(v({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:i,callback:e},t),{delay:t.delay});return this.taskMap.set(r.taskID,r),this[i](r),r.taskID}static interval(i){let e=()=>{i.callback(),i.loopCount+=1,Ce.isBreakLoop(i)};return i.intervalID=setInterval(e,i.delay)}static intervalInWorker(i){Ce.sharedWorker||(Ce.sharedWorker=new Worker(URL.createObjectURL(new Blob([`
|
|
14
14
|
const timers = new Map();
|
|
15
15
|
self.onmessage = function(e) {
|
|
16
16
|
const { taskId, delay, type } = e.data;
|
|
@@ -23,14 +23,14 @@ Refer to: ${dh("en",a)}
|
|
|
23
23
|
timers.delete(taskId);
|
|
24
24
|
}
|
|
25
25
|
};
|
|
26
|
-
`],{type:"application/javascript"}))),Ce.sharedWorker.onmessage=e=>{var t;if(e.data.type==="tick"){let r=Ce.workerTasks.get(e.data.taskId);r&&(r.callback(),r.loopCount+=1,Ce.isBreakLoop(r)&&((t=Ce.sharedWorker)==null||t.postMessage({type:"stop",taskId:r.taskID}),Ce.workerTasks.delete(r.taskID)))}}),Ce.workerTasks.set(i.taskID,i),Ce.sharedWorker.postMessage({taskId:i.taskID,delay:i.delay,type:"start"})}static timeout(i){let e=()=>{if(i.callback(),i.loopCount+=1,!Ce.isBreakLoop(i))return i.timeoutID=setTimeout(e,i.delay)};return i.timeoutID=setTimeout(e,i.delay)}static ric(i){let e=L(),t,r=()=>{if(t=L()-e,t>=i.delay&&(e=L()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!Ce.isBreakLoop(i))return i.ricID=Dh(r,{timeout:i.delay})};return i.ricID=Dh(r,{timeout:i.delay})}static raf(i){let e=L(),t,r=()=>{if(document.hidden&&i.backgroundTask)return t=L()-e,e=L(),i.callback(),i.loopCount+=1,Ce.isBreakLoop(i)?void 0:i.timeoutID=setTimeout(r,i.delay-Math.floor(t%i.delay));if(t=L()-e,t>=i.delay&&(e=L()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!Ce.isBreakLoop(i))return i.rafID=requestAnimationFrame(r)};if(i.rafID=requestAnimationFrame(r),i.backgroundTask){let o=()=>{if(document.hidden){let n=L()-e;n>=i.delay?r():i.timeoutID=setTimeout(r,i.delay-n)}};document.addEventListener("visibilitychange",o),i.onVisibilitychange=o,document.hidden&&o()}return i.taskID}static hasTask(i){return this.taskMap.has(i)}static clearTask(i){if(!this.taskMap.has(i))return!0;let{intervalID:e,timeoutID:t,rafID:r,ricID:o,onVisibilitychange:n,worker:a}=this.taskMap.get(i);return a&&a.terminate(),e&&clearInterval(e),t&&clearTimeout(t),r&&Oh&&Oh(r),o&&a_(o),n&&document.removeEventListener("visibilitychange",n),this.taskMap.delete(i),!0}static isBreakLoop(i){return this.taskMap.has(i.taskID)?i.count!==0&&i.loopCount>=i.count?(this.clearTask(i.taskID),!0):!1:!0}};d(Ce,"taskMap",new Map),d(Ce,"currentTaskID",1),d(Ce,"sharedWorker",null),d(Ce,"workerTasks",new Map);var vc=Ce,re=vc;var NS={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:m.SEI_MESSAGE,ERROR:"error"};var de={LOADED_DATA:m.LOADEDDATA,LOADED_META_DATA:m.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error"};var Kt={};ci(Kt,{create:()=>
|
|
27
|
-
${t.stack}`)),this.sendRequest(mi(this._configs.sdkAppId,Fi.LOG),r)}sendRequest(i,e){setTimeout(()=>_i({url:i,body:JSON.stringify(e),priority:"low"}).catch(()=>{}),2e3)}},ee=new Oc;var Zt=new WeakMap;function tt({settings:s={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(r,o,n){let a=Jt({retryFunction:n.value,settings:s,onError({error:c,retry:l,reject:h,retryFuncArgs:u}){var p;i?i.call(this,c,()=>{var _;(_=Zt.get(r))!=null&&_.has(o)?l():h(c)},h,u):(p=Zt.get(r))!=null&&p.has(o)?l():h(c)},onRetrying(c,l){var h;Wt(e)&&e.call(this,c,l),(h=Zt.get(r))!=null&&h.has(o)&&(Zt.get(r).get(o).stopRetry=l)},onRetryFailed:t});return n.value=function(...c){let l=Zt.get(r);return l?l.set(o,{args:c}):Zt.set(r,new Map([[o,{args:c}]])),a.apply(this,c).finally(()=>{var h;return(h=Zt.get(r))==null?void 0:h.delete(o)})},n}}function Oo({fnName:s,callback:i,validateArgs:e=!0}){return function(t,r,o){let n=o.value;return o.value=function(...a){var c,l;if((c=Zt.get(t))!=null&&c.has(s)){let{stopRetry:h,args:u}=Zt.get(t).get(s),p=!0;if(e){for(let _ of u)if(!a.find(I=>I===_)){p=!1;break}}p&&(i&&i.apply(this,a),h&&h(),(l=Zt.get(t))==null||l.delete(s))}return n.apply(this,a)},o}}var ei=class extends Q{constructor(e,t){super(e.id,`${t}-player`);this.kind=t;d(this,"id");d(this,"element",null);d(this,"track");d(this,"url");d(this,"attr");d(this,"mode");d(this,"muted");d(this,"_log");d(this,"_pausedRetryCount");d(this,"_isElementPlayingFired",!1);d(this,"_interval");d(this,"_delayDestroyTimeoutId",0);d(this,"_playSuccessResolve");d(this,"_isReplayByRecreateMediaStreamCalled",!1);d(this,"isInAutoPlayFailedState",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=Od,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||this.track&&this.track.readyState==="live"&&!this.track.muted)}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 new Promise((e,t)=>{this._playSuccessResolve=e,this.element.play().then(e,t)})}catch(e){let t=V({key:w.PLAY_FAILED,data:{media:this.kind,error:e}});if(this.track&&!this.track.muted&&this._log.warn(e),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new b({code:S.PLAY_NOT_ALLOWED,message:t})}})}stop(e=0){this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!Ji?this._delayDestroyTimeoutId||(this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(m.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():zd?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 Be(this.element,this.element).add(m.PLAYING,e).add(m.ENDED,e).add(m.PAUSE,e).add(m.ERROR,e).add(m.LOADEDDATA,e).add(m.LOADEDMETADATA,e)}}bindTrackEvents(e=this.track){if(e){let t=this.handleTrackEvent.bind(this);Kt==null||Kt.create(e,e).add(m.ENDED,t).add(m.MUTE,t).add(m.UNMUTE,t),e.readyState===m.ENDED&&this.handleTrackEvent({type:m.ENDED}),e.muted&&this.handleTrackEvent({type:m.MUTE})}}bindAutoPlayEvent(){E.on(T.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(e=this.track){e&&Se(e)}unbindEvents(){this.element&&Se(this.element),this.unbindTrackEvents(),E.off(T.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case m.PLAYING:this.isInAutoPlayFailedState=!1,this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(m.PLAYING),this._interval&&(re.clearTask(this._interval),this._interval=-1);break;case m.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(m.ENDED);break;case m.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(m.PAUSE),ve&&(this._interval=re.run("timeout",()=>{this.element&&this._state==="PAUSED"&&this.resume()},{delay:3e3}));break;case m.ERROR:if(this.element&&this.element.error){this.handlePaused(m.ERROR);let{code:r,message:o}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${r} message: ${o} userAgent: ${navigator.userAgent}`),ee.uploadEvent({log:`stat-${this.kind}-${Ke.PLAYER_ERROR}-${r}-${navigator.userAgent}`,error:this.element.error}),jd||qd?this.emit(de.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case m.LOADEDDATA:this.kind===m.VIDEO&&this.emit(de.LOADED_DATA);break;case m.LOADEDMETADATA:this.kind===m.VIDEO&&this.emit(de.LOADED_META_DATA);break}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),ee.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),N.addSuccessEvent({key:this.kind===m.AUDIO?506700:516700})}).catch(()=>{var t;this._log.error("replayByRecreateMediaStream failed"),ee.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),N.addFailedEvent({key:this.kind===m.AUDIO?506700:516700,error:(t=this.element)==null?void 0:t.error}),this.emit(de.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((t,r)=>{fi(e).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var o,n,a;this._log.warn(`element onerror ${(n=(o=this.element)==null?void 0:o.error)==null?void 0:n.code} fired after recreated mediaStream`),r((a=this.element)==null?void 0:a.error)}),fi(5e3).then(()=>{var o,n;(!this.isPlaying||(o=this.element)!=null&&o.error)&&r((n=this.element)==null?void 0:n.error),t()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(e){switch(e.type){case m.ENDED:this.handleStopped(m.ENDED);break;case m.MUTE:this.handlePaused(m.MUTE);break;case m.UNMUTE:this._isElementPlayingFired?this.handlePlaying(m.UNMUTE):this.mode>0&&this.handlePlaying(this.mode.toString());break}}handlePlaying(e){var t;(t=this._playSuccessResolve)==null||t.call(this,e),this.emit(de.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(de.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(de.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};y([tt({settings:{retries:2,timeout:0},onError(e,t,r,o){o[0]=(o[0]||1e3)+1e3,t()}})],ei.prototype,"doReplayByRecreateMediaStream",1),y([le([],"PLAYING",{sync:!0})],ei.prototype,"handlePlaying",1),y([le("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],ei.prototype,"handlePaused",1),y([le([],"STOPPED",{sync:!0})],ei.prototype,"handleStopped",1);var yi="trtc_autoplay",kc=`${yi}_mask`,ms=`${yi}_wrapper`,kh=`${yi}_header`,Mc=`${yi}_content`,ea=`${yi}_action_wrapper`,Lc=`${yi}_question`,Pc=`${yi}_collapse`,ta=`${yi}_action_confirm`,Mh=`${yi}_detail`,Lh="#2473E8",wc="dialog",c_=`${wc}-show`,l_=`${wc}-1`,u_=`${wc}-2`,Ph=!1,Uc=()=>!!document.querySelector(`.${ms}`),wh=`${Ft}/${Rt()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,xh=`<br><a href='${wh}' target='_blank'>${Rt()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,h_=`${Rt()?`\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${xh}`:`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. ${xh}`}`,xc=class{constructor(){d(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");d(this,"_dialogNode",null);d(this,"_bodyPosition","");d(this,"_showDetail",!1);d(this,"_isCollapseClicked",!1);d(this,"_isQuestionClicked",!1);if(Rt()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!Ph){let i=document.createElement("style");i.innerHTML=`.${kc}{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;}.${kc} div:not(.${ea}){display:block !important;}.${ms}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${ms} a{color:${Lh};}.${kh}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${Mc}{margin:8px 0;}.${ea}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${Pc}{margin-right:auto;cursor:pointer}.${Lc}{height:100%;line-height:16px;cursor:pointer;}.${ta}{margin-left:8px;color:#fff;background:${Lh};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${ta}:hover{opacity:0.9;}.${Pc},.${ta},.${Mc},.${Lc}{font-size:14px;}@media screen and (max-width:750px){.${ms}{width:80vw;}}`,document.head.appendChild(i),Ph=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${kc}"><div class='${ms}'><div class='${kh}'>${location.host}</div><div class='${Mc}'>${this.content}</div><div class='${Mh}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${h_}</div><div class='${ea}'></div></div></div>`.trim();let e=document.createElement("button");e.className=ta,e.innerText=Rt()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let t=document.createElement("div");t.className=Lc,t.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
|
|
26
|
+
`],{type:"application/javascript"}))),Ce.sharedWorker.onmessage=e=>{var t;if(e.data.type==="tick"){let r=Ce.workerTasks.get(e.data.taskId);r&&(r.callback(),r.loopCount+=1,Ce.isBreakLoop(r)&&((t=Ce.sharedWorker)==null||t.postMessage({type:"stop",taskId:r.taskID}),Ce.workerTasks.delete(r.taskID)))}}),Ce.workerTasks.set(i.taskID,i),Ce.sharedWorker.postMessage({taskId:i.taskID,delay:i.delay,type:"start"})}static timeout(i){let e=()=>{if(i.callback(),i.loopCount+=1,!Ce.isBreakLoop(i))return i.timeoutID=setTimeout(e,i.delay)};return i.timeoutID=setTimeout(e,i.delay)}static ric(i){let e=L(),t,r=()=>{if(t=L()-e,t>=i.delay&&(e=L()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!Ce.isBreakLoop(i))return i.ricID=Dh(r,{timeout:i.delay})};return i.ricID=Dh(r,{timeout:i.delay})}static raf(i){let e=L(),t,r=()=>{if(document.hidden&&i.backgroundTask)return t=L()-e,e=L(),i.callback(),i.loopCount+=1,Ce.isBreakLoop(i)?void 0:i.timeoutID=setTimeout(r,i.delay-Math.floor(t%i.delay));if(t=L()-e,t>=i.delay&&(e=L()-Math.floor(t%i.delay),i.callback(),i.loopCount+=1),!Ce.isBreakLoop(i))return i.rafID=requestAnimationFrame(r)};if(i.rafID=requestAnimationFrame(r),i.backgroundTask){let o=()=>{if(document.hidden){let n=L()-e;n>=i.delay?r():i.timeoutID=setTimeout(r,i.delay-n)}};document.addEventListener("visibilitychange",o),i.onVisibilitychange=o,document.hidden&&o()}return i.taskID}static hasTask(i){return this.taskMap.has(i)}static clearTask(i){if(!this.taskMap.has(i))return!0;let{intervalID:e,timeoutID:t,rafID:r,ricID:o,onVisibilitychange:n,worker:a}=this.taskMap.get(i);return a&&a.terminate(),e&&clearInterval(e),t&&clearTimeout(t),r&&Oh&&Oh(r),o&&a_(o),n&&document.removeEventListener("visibilitychange",n),this.taskMap.delete(i),!0}static isBreakLoop(i){return this.taskMap.has(i.taskID)?i.count!==0&&i.loopCount>=i.count?(this.clearTask(i.taskID),!0):!1:!0}};d(Ce,"taskMap",new Map),d(Ce,"currentTaskID",1),d(Ce,"sharedWorker",null),d(Ce,"workerTasks",new Map);var vc=Ce,re=vc;var NS={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:m.SEI_MESSAGE,ERROR:"error"};var de={LOADED_DATA:m.LOADEDDATA,LOADED_META_DATA:m.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error"};var Kt={};ci(Kt,{create:()=>Fe,remove:()=>Se});var Do=new WeakMap;function Fe(s,i){Do.has(s)||Do.set(s,[]);let e=Do.get(s),r={add:(o,n)=>("addEventListener"in i?(e.push(i.removeEventListener.bind(i,o,n)),i.addEventListener(o,n)):(e.push(i.off.bind(i,o,n)),i.on(o,n)),r)};return r}function Se(s){let i=Do.get(s);i&&(i.forEach(e=>e()),Do.delete(s))}var Oc=class{constructor(){d(this,"_roomIdMap",new Map);d(this,"_configs");typeof registerProcessor=="undefined"&&(this._configs={sdkAppId:"",userId:"",version:Re,env:li.QCLOUD,browserVersion:qt.name+qt.version,ua:navigator.userAgent})}setConfig({sdkAppId:i,env:e,userId:t,roomId:r}){i!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(i)),this._configs.env=e,this._configs.userId=t,this._roomIdMap.set(t,String(r))}logSuccessEvent(i){Mt||!C.isAbleToUpload||this._configs.env===li.QCLOUD&&this.uploadEventToKibana(k(v({},i),{result:"success"}))}logFailedEvent(i){if(Mt||!C.isAbleToUpload)return;let{eventType:e,code:t,error:r,userId:o}=i,n={roomId:this._roomIdMap.get(o||this._configs.userId),userId:o,eventType:e,result:"failed",code:t||(r==null?void 0:r.extraCode)||(r==null?void 0:r.code)||S.UNKNOWN};this._configs.env===li.QCLOUD&&this.uploadEventToKibana(k(v({},n),{error:r}))}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 r={timestamp:an(),sdkAppId:this._configs.sdkAppId,userId:e||this._configs.userId,version:Re,log:i};t&&(r.errorInfo=t.message,t.stack&&(r.errorInfo+=`
|
|
27
|
+
${t.stack}`)),this.sendRequest(mi(this._configs.sdkAppId,Fi.LOG),r)}sendRequest(i,e){setTimeout(()=>_i({url:i,body:JSON.stringify(e),priority:"low"}).catch(()=>{}),2e3)}},ee=new Oc;var Zt=new WeakMap;function tt({settings:s={retries:5,timeout:2e3},onError:i,onRetrying:e,onRetryFailed:t}){return function(r,o,n){let a=Jt({retryFunction:n.value,settings:s,onError({error:c,retry:l,reject:h,retryFuncArgs:u}){var p;i?i.call(this,c,()=>{var _;(_=Zt.get(r))!=null&&_.has(o)?l():h(c)},h,u):(p=Zt.get(r))!=null&&p.has(o)?l():h(c)},onRetrying(c,l){var h;Wt(e)&&e.call(this,c,l),(h=Zt.get(r))!=null&&h.has(o)&&(Zt.get(r).get(o).stopRetry=l)},onRetryFailed:t});return n.value=function(...c){let l=Zt.get(r);return l?l.set(o,{args:c}):Zt.set(r,new Map([[o,{args:c}]])),a.apply(this,c).finally(()=>{var h;return(h=Zt.get(r))==null?void 0:h.delete(o)})},n}}function Oo({fnName:s,callback:i,validateArgs:e=!0}){return function(t,r,o){let n=o.value;return o.value=function(...a){var c,l;if((c=Zt.get(t))!=null&&c.has(s)){let{stopRetry:h,args:u}=Zt.get(t).get(s),p=!0;if(e){for(let _ of u)if(!a.find(I=>I===_)){p=!1;break}}p&&(i&&i.apply(this,a),h&&h(),(l=Zt.get(t))==null||l.delete(s))}return n.apply(this,a)},o}}var ei=class extends Q{constructor(e,t){super(e.id,`${t}-player`);this.kind=t;d(this,"id");d(this,"element",null);d(this,"track");d(this,"url");d(this,"attr");d(this,"mode");d(this,"muted");d(this,"_log");d(this,"_pausedRetryCount");d(this,"_isElementPlayingFired",!1);d(this,"_interval");d(this,"_delayDestroyTimeoutId",0);d(this,"_playSuccessResolve");d(this,"_isReplayByRecreateMediaStreamCalled",!1);d(this,"isInAutoPlayFailedState",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=Od,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||this.track&&this.track.readyState==="live"&&!this.track.muted)}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 new Promise((e,t)=>{this._playSuccessResolve=e,this.element.play().then(e,t)})}catch(e){let t=V({key:w.PLAY_FAILED,data:{media:this.kind,error:e}});if(this.track&&!this.track.muted&&this._log.warn(e),t.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new b({code:S.PLAY_NOT_ALLOWED,message:t})}})}stop(e=0){this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!Ji?this._delayDestroyTimeoutId||(this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(m.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():zd?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 Fe(this.element,this.element).add(m.PLAYING,e).add(m.ENDED,e).add(m.PAUSE,e).add(m.ERROR,e).add(m.LOADEDDATA,e).add(m.LOADEDMETADATA,e)}}bindTrackEvents(e=this.track){if(e){let t=this.handleTrackEvent.bind(this);Kt==null||Kt.create(e,e).add(m.ENDED,t).add(m.MUTE,t).add(m.UNMUTE,t),e.readyState===m.ENDED&&this.handleTrackEvent({type:m.ENDED}),e.muted&&this.handleTrackEvent({type:m.MUTE})}}bindAutoPlayEvent(){E.on(T.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(e=this.track){e&&Se(e)}unbindEvents(){this.element&&Se(this.element),this.unbindTrackEvents(),E.off(T.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case m.PLAYING:this.isInAutoPlayFailedState=!1,this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(m.PLAYING),this._interval&&(re.clearTask(this._interval),this._interval=-1);break;case m.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(m.ENDED);break;case m.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(m.PAUSE),ve&&(this._interval=re.run("timeout",()=>{this.element&&this._state==="PAUSED"&&this.resume()},{delay:3e3}));break;case m.ERROR:if(this.element&&this.element.error){this.handlePaused(m.ERROR);let{code:r,message:o}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${r} message: ${o} userAgent: ${navigator.userAgent}`),ee.uploadEvent({log:`stat-${this.kind}-${Ke.PLAYER_ERROR}-${r}-${navigator.userAgent}`,error:this.element.error}),jd||qd?this.emit(de.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case m.LOADEDDATA:this.kind===m.VIDEO&&this.emit(de.LOADED_DATA);break;case m.LOADEDMETADATA:this.kind===m.VIDEO&&this.emit(de.LOADED_META_DATA);break}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),ee.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),N.addSuccessEvent({key:this.kind===m.AUDIO?506700:516700})}).catch(()=>{var t;this._log.error("replayByRecreateMediaStream failed"),ee.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),N.addFailedEvent({key:this.kind===m.AUDIO?506700:516700,error:(t=this.element)==null?void 0:t.error}),this.emit(de.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((t,r)=>{fi(e).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var o,n,a;this._log.warn(`element onerror ${(n=(o=this.element)==null?void 0:o.error)==null?void 0:n.code} fired after recreated mediaStream`),r((a=this.element)==null?void 0:a.error)}),fi(5e3).then(()=>{var o,n;(!this.isPlaying||(o=this.element)!=null&&o.error)&&r((n=this.element)==null?void 0:n.error),t()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(e){switch(e.type){case m.ENDED:this.handleStopped(m.ENDED);break;case m.MUTE:this.handlePaused(m.MUTE);break;case m.UNMUTE:this._isElementPlayingFired?this.handlePlaying(m.UNMUTE):this.mode>0&&this.handlePlaying(this.mode.toString());break}}handlePlaying(e){var t;(t=this._playSuccessResolve)==null||t.call(this,e),this.emit(de.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(de.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(de.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};y([tt({settings:{retries:2,timeout:0},onError(e,t,r,o){o[0]=(o[0]||1e3)+1e3,t()}})],ei.prototype,"doReplayByRecreateMediaStream",1),y([le([],"PLAYING",{sync:!0})],ei.prototype,"handlePlaying",1),y([le("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],ei.prototype,"handlePaused",1),y([le([],"STOPPED",{sync:!0})],ei.prototype,"handleStopped",1);var yi="trtc_autoplay",kc=`${yi}_mask`,ms=`${yi}_wrapper`,kh=`${yi}_header`,Mc=`${yi}_content`,ea=`${yi}_action_wrapper`,Lc=`${yi}_question`,Pc=`${yi}_collapse`,ta=`${yi}_action_confirm`,Mh=`${yi}_detail`,Lh="#2473E8",wc="dialog",c_=`${wc}-show`,l_=`${wc}-1`,u_=`${wc}-2`,Ph=!1,Uc=()=>!!document.querySelector(`.${ms}`),wh=`${Ft}/${Rt()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,xh=`<br><a href='${wh}' target='_blank'>${Rt()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,h_=`${Rt()?`\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${xh}`:`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. ${xh}`}`,xc=class{constructor(){d(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");d(this,"_dialogNode",null);d(this,"_bodyPosition","");d(this,"_showDetail",!1);d(this,"_isCollapseClicked",!1);d(this,"_isQuestionClicked",!1);if(Rt()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!Ph){let i=document.createElement("style");i.innerHTML=`.${kc}{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;}.${kc} div:not(.${ea}){display:block !important;}.${ms}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${ms} a{color:${Lh};}.${kh}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${Mc}{margin:8px 0;}.${ea}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${Pc}{margin-right:auto;cursor:pointer}.${Lc}{height:100%;line-height:16px;cursor:pointer;}.${ta}{margin-left:8px;color:#fff;background:${Lh};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${ta}:hover{opacity:0.9;}.${Pc},.${ta},.${Mc},.${Lc}{font-size:14px;}@media screen and (max-width:750px){.${ms}{width:80vw;}}`,document.head.appendChild(i),Ph=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${kc}"><div class='${ms}'><div class='${kh}'>${location.host}</div><div class='${Mc}'>${this.content}</div><div class='${Mh}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${h_}</div><div class='${ea}'></div></div></div>`.trim();let e=document.createElement("button");e.className=ta,e.innerText=Rt()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let t=document.createElement("div");t.className=Lc,t.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
|
|
28
28
|
<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">
|
|
29
29
|
<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"/>
|
|
30
30
|
<path d="m512 960c-247.04 0-448-200.96-448-448s200.96-448 448-448 448 200.96 448 448-200.96 448-448 448zm0-831.71c-211.58 0-383.71 172.13-383.71 383.71 0 211.55 172.13 383.71 383.71 383.71 211.55 0 383.71-172.16 383.71-383.71 0-211.58-172.16-383.71-383.71-383.71z" p-id="2032"/>
|
|
31
31
|
<path d="m512 673.7c-17.665 0-32.001-14.336-32.001-31.999v-54.112c0-52.353 40-92.352 75.328-127.65 25.887-25.92 52.672-52.672 52.672-74.017 0-53.343-43.072-96.735-95.999-96.735-53.823 0-95.999 41.536-95.999 94.559 0 17.665-14.336 31.999-32.001 31.999s-32.001-14.336-32.001-31.999c0-87.424 71.775-158.56 160-158.56s160 72.095 160 160.74c0 47.904-36.32 84.192-71.424 119.3-27.84 27.776-56.576 56.512-56.576 82.336v54.112c0 17.665-14.336 32.032-32.001 32.032z" p-id="2033"/>
|
|
32
32
|
</svg>
|
|
33
|
-
`,t.onclick=this.onQuestionClick.bind(this);let r=document.createElement("div");r.className=Pc,r.innerText=`${Rt()?"\u8BE6\u60C5 >":"Detail >"}`,r.onclick=this.onCollapseClick.bind(this);let o=i.content.firstChild,n=o.querySelector(`.${ea}`);return n.appendChild(r),n.appendChild(t),n.appendChild(e),o}addDiaLog(){Uc()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${ms}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",C.info("show autoplay dialog"),ee.uploadEvent({log:c_}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){C.warn("confirm clicked, try resume stream"),E.emit(T.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${Mh}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||ee.uploadEvent({log:l_}),this._isCollapseClicked=!0}onQuestionClick(){window.open(wh,"_blank"),this._isQuestionClicked||ee.uploadEvent({log:u_}),this._isQuestionClicked=!0}},Uh=xc;var ct=class extends ei{constructor(e){super(e,m.VIDEO);d(this,"stat",{});d(this,"_calculateTimeout",-1);d(this,"viewMirror",!1);d(this,"objectFit");d(this,"container");d(this,"canvas");d(this,"canvasTrack");this.mode=e.canvas?1:0,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(m.VIDEO);this.track&&this.mode!==2&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,(t=this.container)==null||t.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}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.canvasTrack)&&this.elementToRender&&((t=this.container)==null||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(m.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(m.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleTrackEvent(e){var t;super.handleTrackEvent(e),e.type===m.MUTE&&((t=this.stat)!=null&&t.fps)&&(this.stat.fps=0)}handleElementEvent(e){var r;if(this.mode===2)return;super.handleElementEvent(e);let t=e.type;if(t===m.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn(`${this.kind} player has been remove, element ID: ${(r=this.container)==null?void 0:r.id}`),this._pausedRetryCount>0&&!Uc()&&(this._log.info(`${this.kind} player auto resume when paused`),this.resume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let o=this.element.style.transform;t===m.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=o.replace("scaleX(-1)",""):t===m.LEAVE_PICTURE_IN_PICTURE&&!o.includes("scaleX")&&(this.element.style.transform=`${o} scaleX(-1)`)}}setCanvas(e,t=1){var r,o,n,a;this.canvas!==e&&((r=this.canvas)==null||r.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?t:0,this.mode===2&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?((o=this.element)==null||o.remove(),(n=this.container)==null||n.appendChild(e)):this.element&&((a=this.container)==null||a.appendChild(this.element)))}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width=`${e}px`,this.elementToRender.style.height=`${t}px`)}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit=`${e}`),this.objectFit=e}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(),this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(de.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(Ir()&&this.element&&this._calculateTimeout<0){let e=0,t=null,r=(o,n)=>{this.stat.width=n.width,this.stat.height=n.height,t&&(this.stat.fps=Math.round((n.presentedFrames-t.presentedFrames)/(o-e)*1e3)),e=o,t=n,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var a;return(a=this.element)==null?void 0:a.requestVideoFrameCallback(r)},2e3))};this.element.requestVideoFrameCallback(r)}}catch(e){this._log.warn("init stat failed",e)}}};function bi(s,i){return f(this,null,function*(){if(!s.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield s.audioWorklet.addModule(i),C.info("worklet addModule success")}catch(e){throw C.info(`worklet addModule catch error. ${e.message}`),e}})}var ko;typeof AudioContext!="undefined"?ko=AudioContext:typeof webkitAudioContext!="undefined"?ko=webkitAudioContext:typeof mozAudioContext!="undefined"&&(ko=mozAudioContext);var xt,Vh=-1;Bh();function Bh(){try{if(xt)return;xt=new ko({sampleRate:48e3}),xt.onstatechange=()=>{C.info(`context state: ${xt.state}${xt.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),ps()},clearTimeout(Vh)}catch(s){C.error(`initAudioContext failed: ${s} typeof AudioContextClass: ${typeof ko}`),Vh=setTimeout(Bh,1e3)}}var ps=()=>{xt.state==="suspended"?(fs(),document.addEventListener("click",ps)):xt.state==="interrupted"?fs():(document.removeEventListener("visibilitychange",ps),document.removeEventListener("click",ps))},Vc=0,Bc=-1;function fs(){return new Promise((s,i)=>{if(xt.state==="running")return s();Date.now()-Vc<1e3?(clearTimeout(Bc),Bc=setTimeout(()=>{Vc=Date.now(),xt.resume().then(s,i)},1e3)):(clearTimeout(Bc),Vc=Date.now(),xt.resume().then(s,i))}).catch(s=>{C.warn(`context resume failed: ${s}`),document.addEventListener("visibilitychange",ps)})}document.addEventListener("click",ps);var Fe=s=>xt;var He=class{constructor(){d(this,"node");d(this,"pre",new Set);d(this,"next",new Set);d(this,"context");d(this,"connectedNodes",new Set);d(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(),N.addSuccessEvent({key:502701})}catch(t){C.error(t),N.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(),N.addSuccessEvent({key:502702})}catch(e){C.error(e),N.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}},ia=class extends He{constructor(e=256){super();this.fftSize=e;d(this,"dataArray",new Uint8Array(0))}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),t=1,r=0,o=0,n=`M${r},${o}`;for(let a=0;a<e.length;a++)o=e[a]/128*100/2,n+=`L${r},${o}`,r+=t;return n}},Mo=class{constructor(){d(this,"source",new He);d(this,"gain",new He);d(this,"destination",new He)}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(Lo(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}},_s=class extends Mo{constructor(e){super();this.context=e;d(this,"aec",new He);d(this,"mixNode",new He);d(this,"denoiser",new He);this.source.pipeTo(this.aec.pipeTo(this.denoiser.pipeTo(this.gain.pipeTo(this.destination)))),this.mixNode.pipeTo(this.aec)}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.aec.setContext(this.context),this.mixNode.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.aec.removeContext(),this.mixNode.removeContext(),this.denoiser.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.aec.deleteNode(),this.mixNode.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}},ra=class{constructor(){d(this,"audioContext",Fe("audio-mixer"));d(this,"destination",this.audioContext.createMediaStreamDestination());d(this,"inputs",new Set);d(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]}},Fh=new WeakMap;function Lo(s){let i=Fh.get(s);if(i)return i;let e=Fe();if(s instanceof HTMLAudioElement)i=e.createMediaElementSource(s);else if(s instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([s]));else return s;return Fh.set(s,i),i}var lt=class lt{constructor(i){d(this,"_volume",0);d(this,"_volumeDb",0);d(this,"_log");d(this,"_scriptProcessorNode",null);d(this,"_audioWorkletNode",null);d(this,"_interval",200);d(this,"ready",this.preload());let{log:e}=i;this._log=e,E.on(T.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-lt.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!lt.workletReady){let i='class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,s){t=t[0],s=s[0];if(t||s){if(this.isStop)return!1;var i=s&&s[0]?s[0].length:0,h=this.cache.length,a=(i<h?(s[0].set(this.cache.slice(0,i)),this.cache=this.cache.slice(i)):this.unmute&&s[0].set(t[0]),(i<h?s:t)[0]);if(a){let e=0;for(let t=0;t<a.length;++t)e=Math.max(Math.abs(a[t]),e);s=a.reduce((t,e)=>t+e*e,0)/a.length;this.volume=e,this.tick-=a.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,volumeDb:Math.max(10*Math.log10(s)+100,0)/100,cacheLen:h,outputLen:i}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';lt.workletReady=bi(lt.audioContext,URL.createObjectURL(new Blob([i],{type:"application/javascript"})))}return lt.workletReady.then(()=>this.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(lt.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{lt.lastMessageTime=Date.now(),this._volume=e.data.volume||0,this._volumeDb=e.data.volumeDb||0,!i&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),i=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(i){this._log.error(`volumeMeter init audio worklet error: ${i}`),ee.logFailedEvent({userId:this._log.userId,eventType:Ke.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=Fe("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{lt.lastMessageTime=Date.now();let e=i.inputBuffer.getChannelData(0),t=0;for(let r=0;r<e.length;++r)t+=e[r]*e[r];this._volume=Math.sqrt(t/e.length)||0}}catch(i){this._log.error(`volumeMeter init script processor error: ${i}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,E.off(T.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}getVolumeDb(){return Math.floor(this._volumeDb*100)}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}};d(lt,"lastMessageTime",0),d(lt,"audioContext",Fe("volume-meter")),d(lt,"workletReady");var sa=lt,oa=class extends He{constructor(e){super();d(this,"_volumeMeter");this._volumeMeter=new sa(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()}getVolumeDb(){return this._volumeMeter.getVolumeDb()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),r=new Float32Array(t>>2);e.copyTo(r,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:r},[r.buffer]),e.close()}}},Ar=sa;var Wh=Pe(je(),1);var $h=s=>i=>i.deviceId===s;var Po=class{constructor(i,e="Input"){d(this,"kind");d(this,"type");d(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(r=>r.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&gs(this.devices[0])){this.devices=t;return}e&&(t.forEach(r=>{if(r.deviceId&&!this.devices.find($h(r.deviceId))){let o=`${this.kind}${this.type}Added`;C.warn(`${o}: ${JSON.stringify(r)}`),e.emit(o,r)}}),this.devices.forEach(r=>{if(r.deviceId&&!t.find($h(r.deviceId))){let o=`${this.kind}${this.type}Removed`;C.warn(`${o}: ${JSON.stringify(r)}`),e.emit(o,r)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},Fc=class extends Wh.EventEmitter{constructor(){super();d(this,"audioInputs",new Po(m.AUDIO));d(this,"videoInputs",new Po(m.VIDEO));d(this,"audioOutputs",new Po(m.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||re.run("interval",()=>{this.update()},{delay:1e4}))}init(){na().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 na(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}},be=$s||$r?null:new Fc;function gs(s){return s.deviceId===s.groupId&&s.groupId===""}function na(){return f(this,arguments,function*(s=0){if(Ci()||!Xn())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(s!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{gs(t)&&(t.kind===m.AUDIO_INPUT?e.audio=!0:t.kind===m.VIDEO_INPUT&&(e.video=!0))}),s===2&&(e.audio=!1),s===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e),e.audio&&fs()}catch(r){C.debug("capture before getDevices failed: ",r)}i=yield navigator.mediaDevices.enumerateDevices(),t==null||t.getTracks().forEach(r=>r.stop())}}return i.map((e,t)=>{let r={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${t}`};return e.deviceId.length>0&&Hc.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(r.getCapabilities=()=>e.getCapabilities()),r})})}function it(s=!1){return be.update(s?1:0).then(i=>i.audioInputs.devices)}function ut(s=!1){return be.update(s?2:0).then(i=>i.videoInputs.devices)}var Gh=!1;function Jh(){return f(this,null,function*(){try{Gh||(Gh=!0,C.info(`speakers:${(yield Zi()).map(s=>` ${s.deviceId.slice(0,8)}: ${s.label}`)}`))}catch(s){}})}function Zi(s=!1){return f(this,null,function*(){return(ve||Ve)&&(s=!1),be.update(s?1:0).then(i=>i.audioOutputs.devices)})}var Hc=new Set;function qh(s){if(s instanceof CanvasCaptureMediaStreamTrack||!(s instanceof MediaStreamTrack))return!1;let i=s.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let t=`${((s==null?void 0:s.getSettings())||{}).deviceId}_${m.VIDEO_INPUT}`;return!!Hc.has(t)}function jh(s){if(s instanceof CanvasCaptureMediaStreamTrack||!(s instanceof MediaStreamTrack))return!1;let i=s.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("\u9EA6\u514B\u98CE"))return!0;let t=`${((s==null?void 0:s.getSettings())||{}).deviceId}_${m.AUDIO_INPUT}`;return!!Hc.has(t)}function $c(s,i){return f(this,null,function*(){let t=(yield it()).find(r=>r.deviceId===cr);return!i&&(t==null?void 0:t.groupId)===s||(t==null?void 0:t.groupId)===s&&t.label===i})}function Xh(o){return f(this,arguments,function*({newDeviceId:s,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:r}){return s!==i?!1:r===m.AUDIO&&s===cr?yield $c(e,t):!0})}var aa,Gc=class extends Mo{constructor(e){super();this.log=e;d(this,"volumeMeter");d(this,"volumeDestination");d(this,"analyser",new ia);this.volumeMeter=new oa({log:this.log}),this.volumeDestination=new He,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},da=class s extends ei{constructor(e){super(e,m.AUDIO);d(this,"_outputDeviceId");d(this,"_volume",1);d(this,"_destination",Fe("player").createMediaStreamDestination());d(this,"pipeline");d(this,"volumeMeterMode","worklet");this.mode=0,this.pipeline=new Gc(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((ji==="15.2"||ji==="15.3"||ji==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let r=aa||new Audio;r.setAttribute("autoplay","autoplay"),r.srcObject=this.getMediaStream(),r.muted=this.muted,this.element=r,Y(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),r===aa&&(aa=void 0),this.bindElementEvents()}play(e){return f(this,null,function*(){if(this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(e==null?void 0:e.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?this.pipeline.volumeMeter.init():this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(Fe("player").createAnalyser()),Jh(),xe(s.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(e)}setSinkId(e){return f(this,null,function*(){var t,r;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(r=(t=this.element).setSinkId)==null?void 0:r.call(t,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){this.element&&(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}},ca=class extends da{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(de.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)}},la=class extends da{constructor(e){super(e);d(this,"_sourceElement");d(this,"_output",new He);this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter.pipeTo(this._output),this.pipeline.destination))}setOutput(){this.mode=1,this._output.setNode(Fe("player").destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,r,o;((r=(t=this.element)==null?void 0:t.error)==null?void 0:r.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(de.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=((o=e.getSettings())==null?void 0:o.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`)):e<=1?this.element?(this._log.info(`set element volume: ${e}`),this.element.volume=e):this._log.info("set element volume: no element"):ve||(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),Se(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(e=0){this.pipeline.destroy();let t=this._sourceElement||this.element;t&&Ji&&(aa=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var Cr=class extends Q{constructor({userId:e,sdkAppId:t,mediaType:r,room:o,PlayerClass:n=r===1?la:ct}){var a;super();d(this,"id",po());d(this,"userId","");d(this,"isRemote");d(this,"mediaType");d(this,"room");d(this,"user");d(this,"_log");d(this,"_inputTrack");d(this,"_outputTrack");d(this,"isPlayCalled");d(this,"container",null);d(this,"player");d(this,"subVideoPlayerMap");d(this,"muted",!1);d(this,"abortCtrl");d(this,"objectFit","cover");d(this,"mirror");d(this,"isScreen",!1);d(this,"manager");d(this,"trackSettings");d(this,"isFirstVideoFrameEmitted",!1);this.userId=e||"",this.mediaType=r,this._log=C.createLogger({id:`${this.kind[0]}t`,userId:(a=o||this.room)==null?void 0:a.userId,remoteUserId:this instanceof Ni?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof Ni}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(de.PLAYER_STATE_CHANGED,c=>{E.emit(T.PLAYER_STATE_CHANGED,v({track:this},c)),this.emit("player-state-changed",c)}),this.kind===m.VIDEO&&(this.player.on(de.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(de.LOADED_DATA),E.emit(T.VIDEO_LOADED_DATA,{track:this})}),this.player.on(de.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(de.LOADED_META_DATA)}),this.player.on(de.MEDIA_TRACK_CHANGED,c=>{var l;(l=this.subVideoPlayerMap)==null||l.forEach(h=>h.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(de.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||C}get kind(){return this.mediaType===1?m.AUDIO:m.VIDEO}get strMediaType(){return this.mediaType===4?m.VIDEO:this.mediaType===2?m.SCREEN:m.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}get isMediaTrackActive(){return this.mediaTrack?!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled:!1}play(e,t){return f(this,null,function*(){let r=Te(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 ct&&(this.player.setObjectFit(this.objectFit),this.container!==r&&r&&(this.container=r,this.player.setContainer(r)),Te(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===m.VIDEO)&&this.setPlayerMute(!0),t&&!g(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof ct&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,r&&(this.container=r,this.player instanceof ct&&this.player.setContainer(r)),E.emit(T.PLAY_TRACK_START,{track:this}),!this._outputTrack){this.log.info("play has not mediaTrack, abort");return}this._log.info(`play with options: ${JSON.stringify(t)}`);try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(t),Te(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(o){throw this.handleAutoPlayFailed(o),o}})}setMirror(e,t){if(this.isScreen||this.kind!==m.VIDEO||g(e)||e===this.mirror)return;this.mirror=e;let r=this.player;t&&(r=t);let o=this.manager;if(me(this.mirror)){r.setViewMirror(this.mirror),o&&(o.mirror=!1);return}switch(this.mirror){case"view":{o&&(o.mirror=!1),r.setViewMirror(!0);break}case"publish":{o&&(o.mirror=!0),r.setViewMirror(!0);break}case"both":o&&(o.mirror=!0),r.setViewMirror(!1)}}playSubContainer(e,t){return f(this,null,function*(){if(!this._outputTrack||this.kind===m.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((o,n)=>{var a;e.find(c=>n===c)||(o.stop(),(a=this.subVideoPlayerMap)==null||a.delete(n))});for(let[o,n]of e.entries()){let a=this.subVideoPlayerMap.get(n);a?t&&(g(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new ct({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${o+1}`})}))}let r=[...this.subVideoPlayerMap.values()];for(let o of r)o.setViewMirror(this.player.mirror),yield o.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(e=!1){this.isPlayCalled&&(this.isPlayCalled=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(Vd(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(t=>{t.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(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),E.emit(e?T.TRACK_MUTED:T.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){Be(e,e).add(m.MUTE,this.onTrackMuted).add(m.UNMUTE,this.onTrackUnmuted).add(m.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===m.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){Se(e)}setInputMediaStreamTrack(e){var r;let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.trackSettings=(r=e.getSettings)==null?void 0:r.call(e),e.enabled=!this.muted,t&&this.uninstallTrackEvent(t),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,t||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var r;let t=this._outputTrack;e!==t&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(r=e.getSettings)==null?void 0:r.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(t=>this.handleAutoPlayFailed(t)),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(Vd(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(e){if(this.room&&this.room.enableAutoPlayDialog)new Uh;else{let t=()=>{this.resume().then(()=>{document.removeEventListener("click",t,!0)})};document.addEventListener("click",t,!0)}this.emit("error",e)}getVideoFrame(){return this.player instanceof ct?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var n,a,c;if(this.isFirstVideoFrameEmitted)return;let t=(n=this.mediaTrack)==null?void 0:n.getSettings(),r=(t==null?void 0:t.width)||((a=this.player.element)==null?void 0:a.videoWidth)||0,o=(t==null?void 0:t.height)||((c=this.player.element)==null?void 0:c.videoHeight)||0;e===de.LOADED_META_DATA&&!r&&!o||(e===de.LOADED_DATA&&!r&&!o&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,this.emit("first-video-frame",{width:r,height:o,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};y([le([],Q.INIT,{sync:!0})],Cr.prototype,"close",1);var m_=Object.prototype.hasOwnProperty,{toString:XA}=Object.prototype;function p_(s){if(s==null)return!0;if(typeof s=="boolean")return!1;if(typeof s=="number")return s===0;if(typeof s=="string"||typeof s=="function"||Array.isArray(s))return s.length===0;if(s instanceof Error)return s.message==="";if(Ze(s))switch(Object.prototype.toString.call(s)){case"[object File]":case"[object Map]":case"[object Set]":return s.size===0;case"[object Object]":{for(let i in s)if(m_.call(s,i))return!1;return!0}}return!1}var ti=p_;var f_=function(s){return f(this,null,function*(){let i=g_(s);C.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],r=["label","deviceId","groupId"];i.audio&&(e=yield it(),C.info(`microphones: ${ft(e.map(o=>k(v({},o),{groupId:o.groupId.substring(0,8)})),{keysToInclude:r})}`)),i.video&&(t=yield ut(),C.info(`cameras: ${ft(t,{keysToInclude:r})}`));try{let o=yield navigator.mediaDevices.getUserMedia(i);return yc&&o.getTracks().forEach(n=>{C.info(`${n.kind} capabilities: ${ft(n.getCapabilities(),{keysToInclude:gn})}`)}),i.audio&&fs(),o}catch(o){let{message:n}=o;throw o.name==="NotFoundError"&&(s.video&&t&&t.length===0&&(n=V({key:w.CAMERA_NOT_FOUND})),s.audio&&e&&e.length===0&&(n=V({key:w.MICROPHONE_NOT_FOUND}))),new b({code:S.INITIALIZE_FAILED,name:o.name,message:n,constraint:o.constraint})}})},__=Jt({retryFunction:f_,settings:{retries:3,timeout:500},onError:({error:s,retry:i,reject:e,retryFuncArgs:t,retriedCount:r})=>{let o=r+1;s.name==="NotReadableError"||s.name==="OverconstrainedError"?(o===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)),t[0].retryWhenExactFailed&&t[0].useExactDeviceId&&(t[0].useExactDeviceId=!1)):o===2?t[0].useDeviceIdOnly=!0:o===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(s),t[0].microphoneId&&Qh(t[0].microphoneId,!1),t[0].cameraId&&Qh(t[0].cameraId,!0)},onRetrying:s=>{C.warn(`getUserMedia NotReadableError observed, retrying [${s}/3]`)},onRetryFailed:s=>{ee.logFailedEvent({eventType:Ke.GET_USER_MEDIA_RETRY,error:s})},onRetrySuccess:s=>{ee.logSuccessEvent({eventType:Ke.GET_USER_MEDIA_RETRY}),ee.uploadEvent({log:`stat-${Ke.GET_USER_MEDIA_RETRY}-success-${s}`})}});function Qh(s,i){return f(this,null,function*(){let t=(i?yield ut():yield it()).find(r=>r.deviceId===s);t&&oe(t.getCapabilities)&&C.warn(ft(t.getCapabilities(),{keysToInclude:gn}))})}function g_(s){return{audio:T_(s),video:E_(s)}}function T_(s){if(!s.audio)return!1;if(s.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:s.sampleRate};return!ti(s.microphoneId)&&(i.deviceId=s.useExactDeviceId?{exact:s.microphoneId}:s.microphoneId,s.useDeviceIdOnly)?i:(Y(s.channelCount)&&(i.channelCount=s.channelCount),me(s.echoCancellation)&&!s.echoCancellation&&(i.echoCancellation=!1),me(s.noiseSuppression)&&!s.noiseSuppression&&(i.noiseSuppression=!1),me(s.autoGainControl)&&!s.autoGainControl&&(i.autoGainControl=!1),ti(i)?!0:i)}function E_(s){if(!s.video)return!1;if(s.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=s,e={};return s.cameraId?e.deviceId=s.useExactDeviceId?{exact:s.cameraId}:s.cameraId:s.facingMode&&(e.facingMode=s.facingMode),s.useDeviceIdOnly&&!ti(e)?e:(s.width&&(e.width={ideal:s.width},i&&!ae&&(e.width.max=s.width)),s.height&&(e.height={ideal:s.height},i&&!ae&&(e.height.max=s.height)),ae&&Dt&&s.width&&s.height&&s.width*s.height<352*288&&(e.width=s.width,e.height=s.height),s.frameRate&&(e.frameRate=s.frameRate),ti(e)?!0:e)}var zh=__;function ua(s){return J((i,e)=>function(...t){return f(this,null,function*(){return yield s.apply(this,t),i.apply(this,t)})})}function Qe(s){return J((i,e)=>function(...t){return f(this,null,function*(){let r=yield i.apply(this,t);return yield s.call(this,...t),r})})}function ha(s){return J((i,e)=>function(...t){return f(this,null,function*(){try{return yield i.apply(this,t)}catch(r){s.call(this,r)}})})}function J(s){return function(i,e,t){return t.value=s(t.value,e),t}}var Yh=(()=>{let s=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&C.info(`visibility change: ${document.visibilityState}`),!s&&(document.addEventListener("visibilitychange",()=>{C.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),s=!0)}})();var S_=0,ma=class{constructor(){d(this,"log",C.createLogger({id:`fq${++S_}`}));d(this,"isRunning",!1);d(this,"queue",[])}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(i,e=!1){var o,n;let t=v({},i),r=new Promise((a,c)=>{t.resolve=a,t.reject=c});return t.promise=r,e?this.length<=1?this.queue.push(t):(n=(o=this.lastQueueItem)==null?void 0:o.promise)==null||n.then(t.resolve,t.reject):this.queue.push(t),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),r}shift(){let i=this.queue.shift();return this.log.debug(`shift ${this.length}`),i}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:i,args:e,context:t,resolve:r,reject:o}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(r,o).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},xo=new WeakMap,pa=new WeakMap;function ii(s=!1){return function(i,e,t){let r=t.value;return t.value=function(...o){let n=xo.get(this)||new ma;return xo.set(this,n),n.push({fn:r,args:o,context:this},s)},t}}function Kh(s){return function(i,e,t){let r=t.value;return t.value=function(...o){let n=xo.get(this);if(n){let a=n.queue.filter((c,l)=>{if(l===0)return!0;let h=!0;return c.args.forEach(u=>{o.find(p=>p===u)||(h=!1)}),h?(c.reject(new b({code:S.API_CALL_ABORTED,message:s})),!1):!0});n.queue=a}return r.apply(this,o)},t}}function fa(s){return function(i,e,t){let r=t.value;return t.value=function(...o){var a,c,l;let n=[];return(c=(a=xo.get(this))==null?void 0:a.queue)==null||c.forEach(h=>n.push(h)),(l=pa.get(this))==null||l.forEach(h=>h==null?void 0:h.queue.forEach(u=>n.push(u))),n.forEach(h=>{h.reject(new b({code:S.API_CALL_ABORTED,message:s}))}),xo.delete(this),pa.delete(this),r.apply(this,o)},t}}function vi(s){return function(i,e,t){let r=t.value,o=n=>s(...n);return t.value=function(...n){let a=pa.get(this)||new Map,c=a.get(o(n))||new ma;return a.set(o(n),c),pa.set(this,a),c.push({fn:r,args:n,context:this})},t}}function rt(s,i){return J((e,t)=>function(...r){let o=s;try{let n=e.apply(this,r),a=L();return Wi(n)?n.then(c=>(i?N.addSuccessEvent({key:o,cost:L()-a}):N.addSuccessEvent({key:o}),c)).catch(c=>{throw N.addFailedEvent({key:o,error:c}),c}):(N.addSuccessEvent({key:o}),n)}catch(n){throw N.addFailedEvent({key:o,error:n}),n}})}var Rr=class Rr extends Cr{constructor(e,t){super({mediaType:e,PlayerClass:t});d(this,"isRemote",!1);d(this,"deviceId");d(this,"groupId","");d(this,"label","");d(this,"_isRecapturing",!1);d(this,"_lastRecaptureTime",0);d(this,"_onMuteTimeoutId",-1);d(this,"_encodeCheckTimeoutId",-1);d(this,"profile")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){Be(e,e).add(m.MUTE,this.onTrackMuted).add(m.UNMUTE,this.onTrackUnmuted).add(m.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===m.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){Se(e)}setStateToCapture(){}capture(e){return f(this,null,function*(){var t;try{let r=L();E.emit(T.LOCAL_TRACK_CAPTURE_START,{track:this});let o;e.customSource?(o=new MediaStream,o.addTrack(e.customSource)):((t=this.mediaTrack)==null||t.stop(),o=yield zh(e));let n=o.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),E.emit(T.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:L()-r}),o}catch(r){throw E.emit(T.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:r}),this.log.error(`getUserMedia error observed ${r}`),r}})}setInputMediaStreamTrack(e){return this.state===Q.INIT&&this.setStateToCapture(),super.setInputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.isPublishing||this.isPublished)return(t=this.room)==null?void 0:t.replaceTrack(this)}publish(e,t){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),t}unpublish(){this.room&&this.room.localTracks.delete(this),E.emit(T.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return f(this,null,function*(){if(this.mediaTrack&&zt){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:r}=this.mediaTrack;(yield Xh({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=r,t&&(this.groupId=t),na().then(n=>{let a=n.find(c=>c.deviceId===e);a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.mediaTrack||this.kind===m.AUDIO&&!jh(this.mediaTrack)||this.kind===m.VIDEO&&!qh(this.mediaTrack)||this._isRecapturing||e&&Dt&&Ve)}onTrackMuted(){if(super.onTrackMuted(),Yh(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<Jr){setTimeout(()=>this.onTrackMuted(),Jr);return}this._onMuteTimeoutId=setTimeout(()=>f(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((ve||pe)&&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(xe(Rr.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<Jr){setTimeout(()=>this.onTrackEnded(),Jr);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return f(this,null,function*(){var r;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),(r=this._inputTrack)==null||r.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let t={useExactDeviceId:!0};if(e==="user"||e==="environment")t.facingMode=e;else{let o;(this.kind==="audio"?yield it():yield ut()).find(a=>a.deviceId===e)&&(o=e),t.deviceId=o}return this.capture(t).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),E.emit(T.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(o=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${o.message}`),this.emit("5",o),E.emit(T.LOCAL_TRACK_RECAPTURE,{track:this,error:o})})})}getRecoverCaptureDeviceId(){return f(this,null,function*(){let e=this instanceof $e;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let r=(wo.get(t)||0)+1;if(wo.set(t,r),r>=3){let o=e?(yield ut()).find(n=>!wo.has(n.deviceId)):(yield it()).find(n=>!wo.has(n.deviceId));o&&(this.log.warn(`${t} capture fail ${r} times, change new ${o.deviceId}`),t=o.deviceId)}}return t})}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),(e=this.manager)==null||e.removeInput(this)}};y([le(Q.INIT,"capture",{ignoreError:!0,sync:!0})],Rr.prototype,"setStateToCapture",1),y([ii()],Rr.prototype,"capture",1),y([le("capture","publish",{ignoreError:!0,success(){var t,r;this.room.localTracks.add(this),E.emit(T.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),!((((r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.uplinkNetworkQuality)||0)>3)&&(this._encodeCheckTimeoutId=setTimeout(()=>{var n,a;if(!((((a=(n=this.room)==null?void 0:n.networkQuality)==null?void 0:a.uplinkNetworkQuality)||0)>3)&&this.isPublished&&this.isMediaTrackActive){let c=this.kind===m.AUDIO,l=this.stat.bytesSent>0;N[l?"addSuccessEvent":"addFailedEvent"]({key:c?503700:513702}),l||(N.addEnum({key:c?503701:513703,value:mo()}),ee.uploadEvent({log:`stat-encode-failed-${this.kind}-${_r()||Ei()}`,userId:this.userId}),this.log.warn("encode failed"),this.emit("6",this))}},5e3))},fail(e){let t="error";if(e.cause instanceof RTCError){let r=e.cause;r.message.includes("timeout")?t="timeout":r.code===S.API_CALL_ABORTED&&(t="api-call")}this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:e.cause||e})}}),rt(521714,!1)],Rr.prototype,"publish",1),y([J(e=>function(){return f(this,null,function*(){let t=this.state==="publish"?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),le([],"capture",{sync:!0})],Rr.prototype,"unpublish",1);var Ni=Rr,wo=new Map;E.on(T.SWITCH_DEVICE_SUCCESS,s=>{s.track.deviceId&&wo.delete(s.track.deviceId)});var ht=class s extends Ni{constructor(e){super(1,ca);d(this,"mediaType",1);d(this,"volume",0);d(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});d(this,"playerMuted",!0);d(this,"pipeline");d(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});d(this,"mixedUsersMap",new Map);this.manager=e,this.pipeline=new _s(e),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}get dbVolume(){return Ar.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}get playerMediaTrack(){return this.mediaTrack}setInputMediaStreamTrack(e){return f(this,null,function*(){let t=this.trackSettings||{};N.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),N.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),N.addEnum({key:502700,value:0});let{sampleRate:r,channelCount:o}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:r,channelCount:o})}`),this.pipeline.source.channelCount=o||1,this.pipeline.replaceSource(e),yield xe(s.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture({deviceId:e,customSource:t,useExactDeviceId:r=!0,retryWhenExactFailed:o=!0}){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:r,retryWhenExactFailed:o,customSource:t})}switchDevice(e){return f(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e)if(e===cr){if(yield $c(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,retryWhenExactFailed:!1}),E.emit(T.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(t){throw this.log.error(`switch microphone failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}}})}listenDeviceChange(){be&&!be.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&be.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current microphone is lost: ${JSON.stringify(e)}`),he(this.userId,{eventId:2003,param1:6,streamType:1});let t=yield it();t[0]?this.recapture(t[0].deviceId):be.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(o){return f(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:r}){let n=!1;!g(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,n=!0),!g(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,n=!0),!g(r)&&r!==this.profile.autoGainControl&&(this.profile.autoGainControl=r,n=!0),n&&this.deviceId&&(yield this.recapture(this.deviceId))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&N.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(r=>this._log.warn(`${e?"enable":"disable"} ANS failed `,r))}enableTrackAEC(e){if(!this._inputTrack)return;let t=this._inputTrack.getConstraints();return t.echoCancellation=e,this._inputTrack.applyConstraints(t).catch(r=>this._log.warn(`${e?"enable":"disable"} AEC failed `,r))}addDenoiser(e){var t;if(kt<=92&&((t=this.trackSettings)==null?void 0:t.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}N.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.resetPlayerSource(),this.enableTrackANS(!1)}mixPlayTrack(e,t){if(!e){this.log.warn("[aec] mixPlayTrack failed. reason: remote audio track is null");return}if(this.mixedUsersMap.has(t))return;this.log.warn("[aec] mixPlayTrack()",t===""?"*local":t);let r=Lo(e),o=new He;o.pipeTo(this.pipeline.mixNode),o.setNode(r),this.mixedUsersMap.set(t,o)}unMixPlayTrack(e){let t=this.mixedUsersMap.get(e);t&&(this.log.warn("[aec] unMixPlayTrack()",e===""?"\u2191":e),t.deleteNode(),this.mixedUsersMap.delete(e))}addAEC(e,t){this.pipeline.mixNode.setNode(t),this.pipeline.aec.setNode(e),this.resetPlayerSource(),this.enableTrackAEC(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.resetPlayerSource(),this.enableTrackANS(!0))}removeAEC(e){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.resetPlayerSource(),this.enableTrackAEC(!0))}resetPlayerSource(){this.player.setSourceNode(this.pipeline.gain.node||this.pipeline.denoiser.node||this.pipeline.aec.node||this.pipeline.source.node)}close(){this.pipeline.remove(),be.off("audioInputAdded",this.handleMicrophoneAdded,this),be.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return f(this,null,function*(){try{yield xe(s.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield it()).find(o=>o.deviceId!==e);if(r)yield xe(s.prototype,this,"recapture").call(this,r.deviceId);else throw t}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((t,r)=>r?r({frame:t}):t,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}};var Di=class{constructor(i,e=!1){this.dataView=i;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-2,t=[],r=0;for(let n=i;n<=e;n++){let a=this.dataView.getInt8(n);switch(a){case 0:case 1:case 2:case 3:r===2&&(t.push(3),r=0),a==0?r++:r=0,t.push(a);break;default:r=0,t.push(a);break}}t.push(this.dataView.getInt8(this.dataView.byteLength-1));let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=o}removePreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,t=[],r=0;for(let n=i;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:r++,t.push(this.dataView.getInt8(n));break;case 3:r!==2&&t.push(this.dataView.getInt8(n)),r=0;break;default:t.push(this.dataView.getInt8(n)),r=0;break}let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=o}get isSEI(){return this.dataView.getUint8(4)===6}get seiPayloadStartIndex(){let i=6;for(let e=6;e<this.dataView.buffer.byteLength&&(i++,this.dataView.getUint8(e)===255);e++);return i}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let i=0,e=6;for(let o=6;o<this.dataView.buffer.byteLength;o++){let n=this.dataView.getUint8(o);if(e++,n===255)i+=255;else{i+=n;break}}let t=new ArrayBuffer(i),r=new DataView(t);for(let o=0;o<t.byteLength;o++,e++)r.setInt8(o,this.dataView.getInt8(e));return r}};var _a=class{constructor(){d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_seiPayloadType",243)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,o=[];o.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)o.push(255);o.push(r);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Di(new DataView(new Uint8Array(o).buffer),!0)}sendSEI(i,e){e!=null&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(i),e!=null&&e.small&&this._smallSeiMessageList.push(i)}isEmpty(){return!this._seiMessageList.length}getNaluCount(i){let e=0,t=0,r=new DataView(i);for(let o=0;o<i.byteLength;o++)switch(r.getUint8(o)){case 0:e++;break;case 1:(e===2||e===3)&&t++,e=0;break;default:e=0;break}return t}encode(i,e){let t=e?this._smallSeiMessageList:this._seiMessageList;if(t.length>0&&i.data.byteLength>0){let o=9-this.getNaluCount(i.data);if(o<=0)return 0;let n=t.splice(0,o).reverse().map(this.encodeSEINalu.bind(this)),a=n.reduce((p,_)=>p+_.dataView.byteLength,0),c=new ArrayBuffer(a+i.data.byteLength),l=new DataView(c),h=new DataView(i.data),u=0;for(let p=0;p<n.length;p++)for(let _=0;_<n[p].dataView.byteLength;_++)l.setInt8(u++,n[p].dataView.getInt8(_));for(let p=0;p<i.data.byteLength;p++)l.setInt8(u++,h.getInt8(p));return i.data=c,n.length}return 0}};var yr=class yr extends Ni{constructor(e,t=4){super(t,ct);d(this,"profile",{width:640,height:480,frameRate:15,bitrate:500});d(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0});d(this,"small");d(this,"isNeedToSetBandwidth");d(this,"muteImage");d(this,"manager");d(this,"_seiCodec",new _a);this.manager=e;let r=()=>{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(k(v({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",r),this.on("publish",r),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!zt||!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,r,o;if(K(e)){if(this.muteImage===e)return;yield(t=this.manager)==null?void 0:t.deleteWatermark("mute"),yield(r=this.manager)==null?void 0:r.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e}),this.muteImage=e,xe(yr.prototype,this,"setMute").call(this,!1)}else yield(o=this.manager)==null?void 0:o.deleteWatermark("mute"),this.muteImage=void 0,xe(yr.prototype,this,"setMute").call(this,e)})}capture({deviceId:e,facingMode:t,useExactDeviceId:r=!0,customSource:o,retryWhenExactFailed:n=!0}){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:r,retryWhenExactFailed:n,customSource:o})}setProfile(e){let t=v({},e),r=t.width>t.height;t.width*t.height<=160*120&&pe&&Ot&&(this.log.warn(`resolution is ${t.width}*${t.height}, fallback to 240*180`),t.width=r?240:180,t.height=r?180:240,t.bitrate=Math.max(t.bitrate,150)),t.width*t.height>1280*720&&Yd&&(t.width=r?1280:720,t.height=r?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(k(v({},this.profile),{width:1920,height:1080})))}applyProfile(){return f(this,null,function*(){var r;if(!this.mediaTrack)return;let e=this.settings;if(!(!(e.height!==this.profile.height||e.width!==this.profile.width||e.frameRate!==this.profile.frameRate)||!this.deviceId)&&(at===16?yield this.recapture(this.deviceId):(yield(r=this.mediaTrack)==null?void 0:r.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth))return this.isNeedToSetBandwidth=!1,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:m.VIDEO,videoType:m.BIG})})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return zt&&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:Sn()&&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,retryWhenExactFailed:!1};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),E.emit(T.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(){be&&!be.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&be.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)}`),he(this.userId,{eventId:2003,param1:7,streamType:2});let t=yield ut();t[0]?this.recapture(t[0].deviceId):be.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){if(!this.manager)return e;let r=t?8:this.mediaType;return this.manager.encodePipeline.reduceRight((o,n)=>n?n({frame:o,mediaType:r}):o,e)}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}play(e,t){return g(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){be.off("videoInputAdded",this.handleCameraAdded,this),be.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return f(this,null,function*(){try{yield xe(yr.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield ut()).find(o=>o.deviceId!==e);if(r)yield xe(yr.prototype,this,"recapture").call(this,r.deviceId);else throw t}})}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info(`setContentHint ${e}`),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}};y([Qe(function(e){this.setContentHint(e.contentHint||"motion")})],yr.prototype,"capture",1);var $e=yr;var em=po();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:em,exposeOrigin:!0,permittedOrigins:["*"]})}catch(s){}var R_=function(s){return f(this,null,function*(){let i=null,e=N_(s);C.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);s.systemAudio&&t.getAudioTracks().length===0&&(as&&kt<74||Ve||ae)&&C.warn("Your browser not support capture system audio");let r=t.getVideoTracks()[0];if(r){if(s.frameRate)try{yield r.applyConstraints({frameRate:{min:s.frameRate,ideal:s.frameRate},width:s.width,height:s.height})}catch(o){C.warn(`screen applyConstraints failed: ${o}`)}s.captureElement&&(yield y_(r,s.captureElement))}if(s.audio){let o=b_(s);C.info(`getUserMedia with constraints: ${JSON.stringify(o)}`),i=yield navigator.mediaDevices.getUserMedia(o),t.addTrack(i.getAudioTracks()[0])}return t})};function y_(s,i){return f(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&oe(s.cropTo))try{if(!(((e=s.getCaptureHandle())==null?void 0:e.handle)===em))return;let r=yield CropTarget.fromElement(i);yield s.cropTo(r)}catch(t){C.warn(`cropTo target failed ${t}`)}})}function b_(s){let i={echoCancellation:s.echoCancellation,autoGainControl:s.autoGainControl,noiseSuppression:s.noiseSuppression,sampleRate:s.sampleRate,channelCount:s.channelCount};return g(s.microphoneId)||(i.deviceId=s.microphoneId),{audio:i,video:!1}}function N_(s){let i={preferCurrentTab:s.preferDisplaySurface==="current-tab"||!!s.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Ve?{max:s.width}:{ideal:s.width,max:s.width},height:Ve?{max:s.height}:{ideal:s.height,max:s.height},frameRate:s.frameRate,displaySurface:s.preferDisplaySurface||"monitor"};if(i.video=e,s.systemAudio){let{echoCancellation:t=!0,noiseSuppression:r=!1,autoGainControl:o=!1}=s;i.audio={echoCancellation:t,noiseSuppression:r,autoGainControl:o,sampleRate:48e3}}return i}var tm=R_;var st=class extends $e{constructor(e){super(e,2);d(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});d(this,"objectFit","contain");d(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(h){return f(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:r,noiseSuppression:o,audioTrack:n,videoTrack:a,captureElement:c,preferDisplaySurface:l}){try{let u;return a||n?(u=new MediaStream,a&&u.addTrack(a),n&&u.addTrack(n)):u=yield tm({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:r,noiseSuppression:o,captureElement:c,preferDisplaySurface:l}),yield this.setInputMediaStreamTrack(u.getVideoTracks()[0]),u}catch(u){throw this.log.error(`getDisplayMedia error observed ${u}`),u instanceof b?u:new b({code:S.INITIALIZE_FAILED,name:u.name,message:u.message})}})}switchDevice(e){return f(this,null,function*(){throw new Error("Method not implemented.")})}};y([Qe(function(e){this.setContentHint(e.contentHint||"detail")})],st.prototype,"capture",1);var si=class extends ht{constructor(i){super(i),this._log.id=`s-${this._log.id}`}};var v_="registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});",Wc;function Uo(s){return f(this,null,function*(){let i=Fe("dump");Wc||(Wc=bi(i,URL.createObjectURL(new Blob([v_],{type:"application/javascript"})))),yield Wc;let e=new AudioWorkletNode(i,"dumper",{numberOfInputs:s.length,numberOfOutputs:0});return s.forEach((t,r)=>t.connect(e,0,r)),new ReadableStream({start(t){e.port.onmessage=r=>{t.enqueue(r.data)}},cancel(){s.forEach(t=>t.disconnect(e)),e.port.close()}})})}var ga=class extends ra{constructor(e){super();this.room=e;d(this,"_localAudioTrack");d(this,"_localScreenAudioTrack");d(this,"log",C.createLogger({id:"am"}));d(this,"denoiser");d(this,"aec");d(this,"mixNode");d(this,"mixChangedDebounce");d(this,"encodePipeline",[]);d(this,"decodePipeline",[]);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 h,u;if(!this._localAudioTrack)return;let t=[],r=[];(h=this._localAudioPipline)!=null&&h.source.node&&(t.push(this._localAudioPipline.source.node),r.push("mic")),(u=this._localAudioPipline)!=null&&u.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),r.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),r.push("mix")),this.log.info(`dump audio track ${r}, duration: ${e}`);let o=new AbortController,n=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),o.abort("timeout")},e*1e3),c=()=>{for(let p=0;p<r.length;p++){let _=URL.createObjectURL(new Blob(n[p])),I=document.createElement("a");I.href=_,I.download=`${r[p]}.pcm`,I.style.display="none",document.body.appendChild(I),I.click(),URL.revokeObjectURL(_),I.remove()}clearTimeout(a),o.abort("download")},l=Uo(t).then(p=>p.pipeTo(new WritableStream({write(_){_.forEach((I,R)=>n[R]=n[R]?n[R].concat(I[0]):[I[0]])}}),o).catch(_=>c));return{then:l.then.bind(l),download:c}}getPCM(e){var n;if(g(WritableStream)){this.log.warn("getPCM failed: browser not support WritableStream");return}if(!((n=this._localAudioPipline)!=null&&n.source.node)){this.log.warn("getPCM failed: no local audio track");return}this.log.warn("getPCM");let t=new Float32Array(1920),r=0,o=new AbortController;return Uo([this._localAudioPipline.source.node]).then(a=>a.pipeTo(new WritableStream({write(c){c[0][0]&&(t.set(c[0][0],r),r+=c[0][0].length,r>=1920&&(r=0,e(t),t=new Float32Array(1920)))}}),o).catch(c=>this.log.warn(`stop getPCM reason:${c}`))),o}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return!g(this._localAudioTrack)}changeInput(e){var t,r,o;if(e instanceof si)return this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();if(e instanceof ht)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.aec&&this.mixNode&&(e.addAEC(this.aec,this.mixNode),(t=this.room)==null||t.remotePublishedUserMap.forEach(n=>e.mixPlayTrack(n.remoteAudioTrack.mediaTrack,n.userId)),(r=this._localAudioTrack)!=null&&r.pipeline.mixNode.node&&((o=this._localAudioTrack)!=null&&o.pipeline.aec.node)&&this._localAudioTrack.pipeline.mixNode.node.connect(this._localAudioTrack.pipeline.aec.node,0,1)),e.pipeline.connect(),this.mixOnChange();if(e instanceof Oi)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixPlayTrack(e,t){var r;if(!e){this.log.warn("mixPlayTrack failed. Reason: the play track is null.");return}if(!this._localAudioTrack){this.log.warn("mixPlayTrack failed. Reason: local audio is not started.");return}(r=this._localAudioTrack)==null||r.mixPlayTrack(e,t)}unMixPlayTrack(e){var t;(t=this._localAudioTrack)==null||t.unMixPlayTrack(e)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var e,t;return delete this.mixChangedDebounce,Promise.all([(e=this._localAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(e){e instanceof si?delete this._localScreenAudioTrack:e instanceof ht?delete this._localAudioTrack:e instanceof Oi}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}addAEC(e,t){var r,o,n,a;this.aec=e,this.mixNode=t,(r=this._localAudioTrack)==null||r.addAEC(e,t),(o=this.room)==null||o.remotePublishedUserMap.forEach(c=>{var l;return(l=this._localAudioTrack)==null?void 0:l.mixPlayTrack(c.remoteAudioTrack.mediaTrack,c.userId)}),(n=this._localAudioTrack)!=null&&n.pipeline.mixNode.node&&((a=this._localAudioTrack)!=null&&a.pipeline.aec.node)&&this._localAudioTrack.pipeline.mixNode.node.connect(this._localAudioTrack.pipeline.aec.node,0,1)}removeDenoiser(e){var t;delete this.denoiser,(t=this._localAudioTrack)==null||t.removeDenoiser(e)}removeAEC(e){var t;delete this.aec,(t=this._localAudioTrack)==null||t.removeAEC(e)}destroy(){this.close()}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};function Ta(s=30,i=2){return J((e,t)=>function(...r){return new Promise((o,n)=>{let a=setTimeout(()=>{let c=new b({code:S.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${s}s`});C.warn(c),i===2?n(c):i===1&&o()},s*1e3);e.apply(this,r).then(o,n).finally(()=>{clearTimeout(a)})})})}var ki=class ki extends Cr{constructor(e,t,r){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:r,room:e});this.room=e;this.user=t;d(this,"tinyId");d(this,"isRemote",!0);d(this,"jitterBufferDelay",0);d(this,"_decodeCheckTimeoutId",-1);this.tinyId=t.tinyId}setMute(e){this.isAvailable&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isAvailable&&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===ki.STATE_SUBSCRIBE}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){let r=this.kind===m.AUDIO;N[e?"addSuccessEvent":"addFailedEvent"]({key:r?504700:514702}),e||(N.addEnum({key:r?504701:514703,value:mo()}),ee.uploadEvent({log:`stat-decode-failed-${this.kind}-${_r()||Ei()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===m.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isAvailable||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isAvailable} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.updatePlayingState(this.isAvailable)}onTrackMuted(){this.isAvailable&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackMuted()}onTrackUnmuted(){this.isAvailable&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackUnmuted()}onTrackEnded(){this.isAvailable&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackEnded()}};d(ki,"STATE_SUBSCRIBE","subscribe"),y([Ta(5,1)],ki.prototype,"waitHasMediaTrack",1),y([le(Q.INIT,ki.STATE_SUBSCRIBE,{success(){var t,r;this.log.info("subscribed"),E.emit(T.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0),!((((r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState)&&(this._decodeCheckTimeoutId=setTimeout(()=>{var n,a;if(!((((a=(n=this.room)==null?void 0:n.networkQuality)==null?void 0:a.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState)&&this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived>0){let c=this.kind===m.AUDIO,l=this.player.isPlaying||(c?this.getAudioLevel()>0:this.stat.framesDecoded>0);this.reportDecodeResult(l)}},5e3),this.player.once(de.ERROR,o=>{o.code===MediaError.MEDIA_ERR_DECODE&&(clearTimeout(this._decodeCheckTimeoutId),this.reportDecodeResult(!1,3))}))},ignoreError:!0}),rt(521716,!1)],ki.prototype,"subscribe",1),y([le(ki.STATE_SUBSCRIBE,Q.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),E.emit(T.REMOTE_TRACK_UNSUBSCRIBED,{track:this}),clearTimeout(this._decodeCheckTimeoutId)}})],ki.prototype,"unsubscribe",1);var Ts=ki;var Oi=class extends Ts{constructor(e,t){super(e,t,1);d(this,"volume",0);d(this,"mediaType",1);d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}get dbVolume(){return Ar.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}decodeFrame(e){if(!this.manager)return e;let t=e;for(let r of this.manager.decodePipeline)if(r&&(t=r({frame:t,track:this}),!t))return;return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isAvailable(){return this.user.muteState.audioAvailable}};var O_=[-1,-1,1,-1,-1,1,1,1],k_=[0,0,1,0,0,1,1,1];var ze=class extends Q{constructor(e,t){super();this.context=e;d(this,"name");d(this,"input");d(this,"output");d(this,"texture");d(this,"ctx2d",null);d(this,"fbo");d(this,"width",0);d(this,"height",0);d(this,"x",0);d(this,"y",0);d(this,"program");d(this,"vertexShader");d(this,"fragmentShader");d(this,"totalFrames",0);d(this,"dropFrames",0);d(this,"matchInputSize",!0);d(this,"texCoordBuffer");d(this,"positionBuffer");d(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});d(this,"cost",0);d(this,"_canvas",null);d(this,"_image");d(this,"log");if(this.context.on("disconnect",this.close,this),this.name=t.name,this.log=t.logger,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof Ge){e.ctx&&t.create2d&&(typeof OffscreenCanvas=="function"&&at!==16?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);return}try{let r=e.ctx;this.texCoordBuffer=this.createBuffer(k_),this.positionBuffer=this.createBuffer(O_),t.createTexture!==!1&&(this.texture=r.createTexture(),this.useTexture(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.pixelStorei(r.PACK_ALIGNMENT,1),r.pixelStorei(r.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=r.createFramebuffer(),this.useBufferFrame(),this.useTexture(),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,this.width,this.height,0,r.RGBA,r.UNSIGNED_BYTE,null),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(r.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(r.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(r){this.context.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${r.message||r}`}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,r=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),r}connect(e,...t){return e.addInput(this,...t),this.output=e,e}addInput(e,...t){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();if(this.context instanceof ke&&this.render(e)||this.context instanceof Ge&&this.render2d(e))this.totalFrames++;else return!1;return this.cost=Date.now()-t,!0}render2d(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?this.draw2d(this.input.image,0,0,this.width,this.height):!1}update(e=0){var t;(t=this.output)==null||t.update(e)}disconnect(...e){var t;(t=this.output)==null||t.removeInput(this,...e),delete this.output}removeInput(e,...t){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),(e=this.output)==null||e.removeInput(this),delete this.output,(t=this.input)==null||t.disconnect(),this.context instanceof ke){let r=this.context.ctx;r.deleteBuffer(this.texCoordBuffer),r.deleteBuffer(this.positionBuffer),this.fbo&&r.deleteFramebuffer(this.fbo),this.texture&&r.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&r.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&r.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&r.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let t=this.context.ctx;e.forEach((r,o)=>{r&&(t.activeTexture(t.TEXTURE0+o),t.bindTexture(t.TEXTURE_2D,r))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,r=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,r),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),r}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,e),r.bufferData(r.ARRAY_BUFFER,new Float32Array(t),r.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((r,o)=>{t.enableVertexAttribArray(o),t.bindBuffer(t.ARRAY_BUFFER,r),t.vertexAttribPointer(o,2,t.FLOAT,!1,0,0)})}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(!(this.width===e&&this.height===t)){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let r=this.context.ctx;r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e,t,0,r.RGBA,r.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let r=this.context.ctx;r.drawArrays(r.TRIANGLE_STRIP,0,4)}draw2d(e,t,r,o,n){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,t,r):(this.ctx2d.drawImage(e,t,r,o,n),typeof VideoFrame!="undefined"&&e instanceof VideoFrame&&e.close()),!0):!1}getInfo(){var u;let{totalFrames:e,x:t,y:r,width:o,height:n,name:a,cost:c}=this,l=Date.now(),h=(e-this.lastInfo.totalFrames)/((l-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:o,height:n,timestamp:l,fps:h,name:a,cost:c},v({parent:(u=this.input)==null?void 0:u.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,r=t.createTexture();return this.useTextures(r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),r}};y([le(Q.INIT,"connected",{sync:!0})],ze.prototype,"connect",1),y([le("connected",Q.INIT,{ignoreError:!0,sync:!0})],ze.prototype,"disconnect",1),y([le([],"closed",{sync:!0})],ze.prototype,"close",1);var Dl={};ci(Dl,{Events:()=>fe,Inspect:()=>Tt,LastSink:()=>br,Sink:()=>F,Subscribe:()=>Nr,TimeoutError:()=>Vo,audit:()=>pg,bindCallback:()=>Z_,bindNodeCallback:()=>eg,buffer:()=>$_,bufferCount:()=>H_,bufferTime:()=>Lg,call:()=>rm,catchError:()=>Fo,combineLatest:()=>om,concat:()=>w_,concatMap:()=>yg,concatMapTo:()=>bg,count:()=>rg,create:()=>Z,debounce:()=>fg,debounceTime:()=>_g,defer:()=>nm,delay:()=>Pg,deliver:()=>$,dispose:()=>Ea,elementAt:()=>gg,empty:()=>Dr,every:()=>Ag,exhaustMap:()=>Dg,exhaustMapTo:()=>Og,filter:()=>Ra,find:()=>Tg,findIndex:()=>Eg,first:()=>Sg,fromAnimationFrame:()=>Y_,fromArray:()=>J_,fromEvent:()=>Ie,fromEventPattern:()=>q_,fromFetch:()=>j_,fromIterable:()=>X_,fromPromise:()=>cm,fromReadableStream:()=>z_,fromReader:()=>Q_,groupBy:()=>kg,identity:()=>M_,ignoreElements:()=>ag,iif:()=>V_,inspect:()=>sm,interval:()=>zc,last:()=>Ig,map:()=>yl,mapTo:()=>Rg,max:()=>sg,merge:()=>P_,mergeMap:()=>Ng,mergeMapTo:()=>vg,min:()=>og,never:()=>tg,nothing:()=>se,of:()=>W_,pairwise:()=>Cg,pipe:()=>_e,race:()=>x_,range:()=>K_,reduce:()=>Kc,retry:()=>Vg,scan:()=>Rl,share:()=>Mi,shareReplay:()=>U_,skip:()=>cg,skipUntil:()=>lg,skipWhile:()=>ya,startWith:()=>vr,subject:()=>ot,subscribe:()=>Ne,sum:()=>ng,switchMap:()=>tr,switchMapTo:()=>Bo,take:()=>Li,takeLast:()=>dg,takeUntil:()=>we,takeWhile:()=>lm,tap:()=>vl,throttle:()=>hg,throwError:()=>ig,timeInterval:()=>Mg,timeout:()=>Ug,timer:()=>Yc,toPromise:()=>xg,toReadableStream:()=>wg,withLatestFrom:()=>F_,zip:()=>B_});function se(...s){}var rm=s=>s(),M_=s=>s;function Ea(){this.dispose()}var sm=()=>typeof __FASTRX_DEVTOOLS__!="undefined",L_=1,Tt=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new qc(i,this,this.streamId++);return fe.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},br=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=se,this.error=se,this.next=se,this.dispose=se,this.subscribe=se,this.doDefer()}subscribe(i){return i instanceof Tt?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(rm),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 br{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)}},Nr=class extends br{constructor(i,e=se,t=se,r=se){if(super(),this._next=e,this._error=t,this._complete=r,this.then=se,i instanceof Tt){let o={toString:()=>"subscribe",id:0,source:i};this.defer(()=>{fe.defer(o,0)}),fe.create(o),fe.pipe(o),this.sourceId=o.id,this.subscribe(i),fe.subscribe({id:o.id,end:!0}),e==se?this._next=n=>fe.next(o,0,n):this.next=n=>{fe.next(o,0,n),e(n)},r==se?this._complete=()=>fe.complete(o,0):this.complete=()=>{this.dispose(),fe.complete(o,0),r()},t==se?this._error=n=>fe.complete(o,0,n):this.error=n=>{this.dispose(),fe.complete(o,0,n),t()}}else this.subscribe(i)}next(i){this._next(i)}complete(){this.dispose(),this._complete()}error(i){this.dispose(),this._error(i)}};function _e(s,...i){return i.reduce((e,t)=>t(e),s)}function Z(s,i,e){if(sm()){let t=Object.defineProperties(Object.setPrototypeOf(s,Tt.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}});fe.create(t);for(let r=0;r<e.length;r++){let o=e[r];typeof o=="function"&&o instanceof Tt&&fe.addSource(t,o)}return t}return s}function $(s,i){return function(...e){return t=>{if(t instanceof Tt){let r=Z(o=>{let n=new s(o,...e);n.sourceId=r.id,n.subscribe(t)},i,arguments);return r.source=t,fe.pipe(r),r}else return r=>t(new s(r,...e))}}}function er(s,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:s,payload:i}})}var qc=class extends F{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{fe.defer(this.source,this.id)})}next(i){fe.next(this.source,this.id,i),this.sink.next(i)}complete(){fe.complete(this.source,this.id),this.sink.complete()}error(i){fe.complete(this.source,this.id,i),this.sink.error(i)}},fe={addSource(s,i){er("addSource",{id:s.id,name:s.toString(),source:{id:i.id,name:i.toString()}})},next(s,i,e){er("next",{id:s.id,streamId:i,data:e&&e.toString()})},subscribe({id:s,end:i},e){er("subscribe",{id:s,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(s,i,e){er("complete",{id:s.id,streamId:i,err:e?e.toString():null})},defer(s,i){er("defer",{id:s.id,streamId:i})},pipe(s){er("pipe",{name:s.toString(),id:s.id,source:{id:s.source.id,name:s.source.toString()}})},update(s){er("update",{id:s.id,name:s.toString()})},create(s){s.id||(s.id=L_++),er("create",{name:s.toString(),id:s.id})}},Vo=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var Sa=class extends br{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 Mi(){return s=>{let i=new Sa(s);if(s instanceof Tt){let e=Z(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=s,fe.pipe(e),e}return Z(i.add.bind(i),"share",arguments)}}function P_(...s){return Z(i=>{let e=new F(i),t=s.length;e.complete=()=>{--t===0&&i.complete()},s.forEach(e.bindSubscribe)},"merge",arguments)}function x_(...s){return Z(i=>{let e=new Map;s.forEach(t=>{let r=new F(i);e.set(t,r),r.complete=()=>{e.delete(t),e.size===0?i.complete():r.dispose()},r.next=o=>{e.delete(t),e.forEach(n=>n.dispose()),r.resetNext(),r.resetComplete(),r.next(o)}}),s.forEach(t=>e.get(t).subscribe(t))},"race",arguments)}function w_(...s){return Z(i=>{let e=0,t=s.length,r=new F(i);r.complete=()=>{e<t&&!r.disposed?(r.doDefer(),r.subscribe(s[e++])):i.complete()},r.complete()},"concat",arguments)}function U_(s){return i=>{let e=new Sa(i),t=[];return e.next=function(r){t.push(r),t.length>s&&t.shift(),this.sinks.forEach(o=>o.next(r))},Z(r=>{r.defer(()=>e.remove(r)),t.forEach(o=>r.next(o)),e.add(r)},"shareReplay",arguments)}}function V_(s,i,e){return Z(t=>s()?i(t):e(t),"iif",arguments)}function om(...s){return Z(i=>{let e=s.length,t=e,r=e,o=new Array(e),n=()=>{--r===0&&i.complete()},a=(c,l)=>{let h=new F(i);h.next=u=>{--t===0?(h.next=p=>{o[l]=p,i.next(o)},h.next(u)):o[l]=u},h.complete=n,h.subscribe(c)};s.forEach(a)},"combineLatest",arguments)}function B_(...s){return Z(i=>{let e=s.length,t=e,r=new Array(e),o=()=>{--t===0&&i.complete()},n=(a,c)=>{let l=new F(i),h=[];r[c]=h,l.next=u=>{h.push(u),r.every(p=>p.length)&&i.next(r.map(p=>p.shift()))},l.complete=o,l.subscribe(a)};s.forEach(n)},"zip",arguments)}function vr(...s){return i=>Z((e,t=0,r=s.length)=>{for(;t<r&&!e.disposed;)e.next(s[t++]);e.disposed||e.subscribe(i)},"startWith",arguments)}var jc=class extends F{constructor(i,...e){super(i);let t=new F(this.sink);t.next=r=>this.buffer=r,t.complete=se,t.subscribe(om(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},F_=$(jc,"withLatestFrom"),Xc=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()}},H_=$(Xc,"bufferCount"),Qc=class extends F{constructor(i,e){super(i),this.buffer=[];let t=new F(i);t.next=r=>{i.next(this.buffer),this.buffer=[]},t.complete=se,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},$_=$(Qc,"buffer");var G_=function(s,i,e,t){function r(o){return o instanceof e?o:new e(function(n){n(o)})}return new(e||(e=Promise))(function(o,n){function a(h){try{l(t.next(h))}catch(u){n(u)}}function c(h){try{l(t.throw(h))}catch(u){n(u)}}function l(h){h.done?o(h.value):r(h.value).then(a,c)}l((t=t.apply(s,i||[])).next())})};function ot(s){let i=arguments,e=Mi()(Z(t=>{e.next=r=>t.next(r),e.complete=()=>t.complete(),e.error=r=>t.error(r),s&&t.subscribe(s)},"subject",i));return e.next=se,e.complete=se,e.error=se,e}function nm(s){return Z(i=>i.subscribe(s()),"defer",arguments)}var am=s=>i=>{setTimeout(()=>s(i))},dm=s=>am(i=>{for(let e=0;!i.disposed&&e<s.length;e++)i.next(s[e]);i.complete()});function W_(...s){return Z(dm(s),"of",arguments)}function J_(s){return Z(dm(s),"fromArray",arguments)}function zc(s){return Z(i=>{let e=0,t=setInterval(()=>i.next(e++),s);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}function Yc(s,i){return Z(e=>{let t=0,r=setTimeout(()=>{if(e.removeDefer(o),e.next(t++),i){let n=setInterval(()=>e.next(t++),i);e.defer(()=>{clearInterval(n)})}else e.complete()},s),o=()=>{clearTimeout(r)};e.defer(o)},"timer",arguments)}function Ia(s,i){return e=>{let t=r=>e.next(r);e.defer(()=>i(t)),s(t)}}function q_(s,i){return Z(Ia(s,i),"fromEventPattern",arguments)}function Ie(s,i){if("on"in s&&"off"in s)return Z(Ia(e=>s.on(i,e),e=>s.off(i,e)),"fromEvent",arguments);if("addListener"in s&&"removeListener"in s)return Z(Ia(e=>s.addListener(i,e),e=>s.removeListener(i,e)),"fromEvent",arguments);if("addEventListener"in s)return Z(Ia(e=>s.addEventListener(i,e),e=>s.removeEventListener(i,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function cm(s){return Z(i=>{s.then(i.next.bind(i),i.error.bind(i))},"fromPromise",arguments)}function j_(s,i){return Z(nm(()=>cm(fetch(s,i))),"fromFetch",arguments)}function X_(s){return Z(am(i=>{try{for(let e of s){if(i.disposed)return;i.next(e)}i.complete()}catch(e){i.error(e)}}),"fromIterable",arguments)}function Q_(s){let i=e=>G_(this,void 0,void 0,function*(){if(e.disposed)return;let{done:t,value:r}=yield s.read();if(t){e.complete();return}else e.next(r),i(e)});return Z(e=>{i(e)},"fromReader",arguments)}function z_(s){return Z(i=>{let e=new AbortController,t=e.signal;i.defer(()=>e.abort("cancelled")),s.pipeTo(new WritableStream({write(r){i.next(r)},close(){i.complete()},abort(r){i.error(r)}}),{signal:t}).then(()=>i.complete(),r=>i.error(r))},"fromReadableStream",arguments)}function Y_(){return Z(s=>{let i=requestAnimationFrame(function e(t){s.disposed||(s.next(t),i=requestAnimationFrame(e))});s.defer(()=>cancelAnimationFrame(i))},"fromAnimationFrame",arguments)}function K_(s,i){return Z((e,t=s,r=i+s)=>{for(;t<r&&!e.disposed;)e.next(t++);return e.complete(),"range"},"range",arguments)}function Z_(s,i,...e){return Z(t=>{let r=e.concat(o=>(t.next(o),t.complete()));s.apply(i,r)},"bindCallback",arguments)}function eg(s,i,...e){return Z(t=>{let r=e.concat((o,n)=>o?t.error(o):(t.next(n),t.complete()));s.apply(i,r)},"bindNodeCallback",arguments)}function tg(){return Z(()=>{},"never",arguments)}function ig(s){return Z(i=>i.error(s),"throwError",arguments)}function Dr(){return Z(s=>s.complete(),"empty",arguments)}var Or=class extends F{constructor(i,e,t){super(i),this.f=e;let r=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=o=>{this.acc=o,this.complete=r,this.resetNext()}:(this.acc=t,this.complete=r)}next(i){this.acc=this.f(this.acc,i)}},Kc=$(Or,"reduce"),rg=s=>$(Or,"count")((i,e)=>s(e)?i+1:i,0),sg=()=>$(Or,"max")(Math.max),og=()=>$(Or,"min")(Math.min),ng=()=>$(Or,"sum")((s,i)=>s+i,0);var Zc=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)}},Ra=$(Zc,"filter"),el=class extends F{next(i){}},ag=$(el,"ignoreElements"),tl=class extends F{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&this.complete()}},Li=$(tl,"take"),il=class extends F{constructor(i,e){super(i);let t=new F(i);t.next=()=>i.complete(),t.complete=Ea,t.subscribe(e)}},we=$(il,"takeUntil"),rl=class extends F{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):this.complete()}},lm=$(rl,"takeWhile"),dg=s=>Kc((i,e)=>(i.push(e),i.length>s&&i.shift(),i),[]),sl=class extends F{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},cg=$(sl,"skip"),ol=class extends F{constructor(i,e){super(i),i.next=se;let t=new F(i);t.next=()=>{t.dispose(),i.resetNext()},t.complete=Ea,t.subscribe(e)}},lg=$(ol,"skipUntil"),nl=class extends F{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},ya=$(nl,"skipWhile"),ug={leading:!0,trailing:!1},al=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)}},Aa=class extends F{constructor(i,e,t=ug){super(i),this.durationSelector=e,this.config=t,this._throttle=new al(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=se,this._throttle.complete(),super.complete()}},hg=$(Aa,"throttle"),mg={leading:!1,trailing:!0},pg=s=>$(Aa,"audit")(s,mg),dl=class extends F{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Ca=class extends F{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new dl(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()}},fg=$(Ca,"debounce"),_g=s=>$(Ca,"debounceTime")(i=>Yc(s)),cl=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()}},gg=$(cl,"elementAt"),Tg=s=>i=>Li(1)(ya(e=>!s(e))(i)),ll=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}},Eg=$(ll,"findIndex"),ul=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()}},Sg=$(ul,"first"),hl=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()}},Ig=$(hl,"last"),ml=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()}},Ag=$(ml,"every");var pl=class extends F{constructor(i,e,t){super(i),this.f=e,typeof t=="undefined"?this.next=r=>{this.acc=r,this.resetNext(),this.sink.next(this.acc)}:this.acc=t}next(i){this.sink.next(this.acc=this.f(this.acc,i))}},Rl=$(pl,"scan"),fl=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}},Cg=$(fl,"pairwise"),ba=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))}},yl=$(ba,"map"),Rg=s=>$(ba,"mapTo")(i=>s),Es=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()}},Ss=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()}},Na=class extends Es{},va=class extends Ss{next(i){this.subInner(i,Na),this.next=e=>{this.currentSink.dispose(),this.subInner(e,Na)}}},tr=$(va,"switchMap");function Ma(s){return(i,e)=>s(()=>i,e)}var Bo=Ma($(va,"switchMapTo")),_l=class extends Es{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},Da=class extends Ss{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(),_l),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},yg=$(Da,"concatMap"),bg=Ma($(Da,"concatMapTo")),gl=class extends Es{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Oa=class extends Ss{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,gl),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},Ng=$(Oa,"mergeMap"),vg=Ma($(Oa,"mergeMapTo")),Tl=class extends Es{dispose(){this.context.resetNext(),super.dispose()}},ka=class extends Ss{next(i){this.next=se,this.subInner(i,Tl)}},Dg=$(ka,"exhaustMap"),Og=Ma($(ka,"exhaustMapTo")),El=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=ot(),t.key=e,this.groups.set(e,t),super.next(t)),t.next(i)}complete(){this.groups.forEach(i=>i.complete()),super.complete()}error(i){this.groups.forEach(e=>e.error(i)),super.error(i)}},kg=$(El,"groupBy"),Sl=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}},Mg=$(Sl,"timeInterval"),Il=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()}},Lg=$(Il,"bufferTime"),Al=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:r}=e;super.next(r),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(t))}},i)}next(i){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:i})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},Pg=$(Al,"delay"),Cl=class extends F{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},Fo=$(Cl,"catchError");var xg=()=>s=>new Promise((i,e)=>{let t;new Nr(s,r=>t=r,e,()=>i(t))}),wg=()=>s=>{let i;return new ReadableStream({start(e){i=new Nr(s,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){i.dispose()}})},Ne=(s=se,i=se,e=se)=>t=>new Nr(t,s,i,e),bl=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)}))}},vl=$(bl,"tap"),Nl=class extends F{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new Vo(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},Ug=$(Nl,"timeout"),Vg=(s=1/0)=>i=>{if(i instanceof Tt){let e=Z(t=>{let r=s,o=new F(t);o.error=n=>{r-- >0?o.subscribe(i):t.error(n)},o.sourceId=e.id,o.subscribe(i)},"retry",[s]);return e.source=i,fe.pipe(e),e}else return e=>{let t=s,r=new F(e);r.error=o=>{t-- >0?i(r):e.error(o)},i(r)}};var Bg=_e(zc(250),yl(()=>performance.now()),Mi());var um=s=>i=>{let e=performance.now();_e(Bg,ya(t=>t-e<s),Li(1))(i)};var Hg=[0,1,1,1,0,0,1,0],kr=class extends ze{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));d(this,"_intervalId",0);d(this,"_sequence",0);d(this,"checkGLError",!1);d(this,"checkVisibilityChange");e instanceof Ge?this.ctx2d=e.ctx||null:e.available&&(t!=null&&t.mirrorUpAndDown)&&this.setTexBuffer(Hg)}start(e){this.log.info(`${this.name} start render ${e} fps`),re.clearTask(this._intervalId),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 ke){let r=this.context.ctx.getError();r&&this.context.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${r}`}))}},{fps:this.context.frameRate})}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}update(e=0){if(this._intervalId&&(re.clearTask(this._intervalId),this._intervalId=0,e===1)){this.log.info(`${this.name} use requestVideoFrameCallback`);let t=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",t))};document.addEventListener("visibilitychange",t)}this.requestFrame(this._sequence++)}removeInput(e){super.removeInput(e),re.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),re.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},Is=class extends kr{constructor(e,t){super(e,t);d(this,"_videoTrack");d(this,"_muteOb");d(this,"_closedOb",Ie(this,"closed"));d(this,"_subscription");d(this,"_canvasContainer");Number(qi)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=Ie(this._videoTrack,"mute"),_e(Ie(this._videoTrack,"ended"),we(this._closedOb),Ne(()=>{this.context.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=_e(this._muteOb,we(this._closedOb),Bo(um(5e3)),Ne(()=>{var e;(e=this._videoTrack)!=null&&e.muted&&this.context.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var e;(e=this._subscription)==null||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info(`${this.name} put canvas to body`),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,t;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack,(t=this._canvasContainer)==null||t.remove()}},La=class extends Is{render(i){var e;return!!((e=this.input)!=null&&e.requestFrame(i))}};var Pa=class extends Is{constructor(e,t,r){super(e,{name:"smallDestination",logger:r});this.resolution=t}resize(e,t){let r,o=e*t,n=this.resolution.width*this.resolution.height;this.log.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),o>n?r=o/n:(this.log.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${t} small: ${this.resolution.width} * ${this.resolution.height}`),r=o/(160*120)),super.resize(e/Math.sqrt(r),t/Math.sqrt(r))}};var Ho=class extends ze{constructor(e,t){super(e,v({name:"imageSource"},t));d(this,"_lastImage");d(this,"_totalFrames",0);d(this,"_autoResize",!1);d(this,"_canvasRendered");d(this,"_videoCallbackId",0);this._autoResize=(t==null?void 0:t.autoResize)!==!1,at===16&&(this._canvasRendered=ot(),_e(this._canvasRendered,vr(this._image),tr(r=>r instanceof HTMLCanvasElement?Ie(r,"rendered"):Dr()),we(Ie(this,"closed")),Ne(()=>{this.update()})))}tryVideoFrameCallback(e){this._videoCallbackId&&e.cancelVideoFrameCallback(this._videoCallbackId),Ir()&&!document.hidden&&(this._videoCallbackId=e.requestVideoFrameCallback((t,r)=>{document.hidden||(this._totalFrames=r.presentedFrames,this.update(1))}))}_render(e,t){var a;let{width:r,height:o}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(n),{videoWidth:r,videoHeight:o}=n,!r||!o)return!1;n.width=r,n.height=o}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if({width:r,height:o}=n,n!==this._lastImage)this._lastImage=n;else if(r===this.width&&o===this.height)return!1}else n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas?({width:r,height:o}=n,this._lastImage=n):typeof VideoFrame!="undefined"&&n instanceof VideoFrame&&({displayWidth:r,displayHeight:o}=n,(a=this._lastImage)==null||a.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===r&&this.height===o&&this.totalFrames){if(t){this.useTexture();let c=this.context.ctx;c.texSubImage2D(c.TEXTURE_2D,0,0,0,c.RGBA,c.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();let c=this.context.ctx;c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,n)}this.resize(r,o)}return!0}get image(){return this._image}set image(e){var t;(t=this._canvasRendered)==null||t.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},$o=class extends Ho{constructor(e,t,r){super(e,r);this._player=t;this.name="videoPlayerSource",_e(Ie(this._player,de.PLAYER_STATE_CHANGED),we(Ie(this,"closed")),Ra(({state:o})=>o==="PLAYING"),Ne(()=>{this.tryVideoFrameCallback(this._player.element)}))}get image(){return this._player.element}},Pi=class extends $o{constructor(i,e,t){super(i,new ct({id:t.name,track:e,muted:!0,container:null,objectFit:"contain",log:t.logger}),t),this.name="videoTrackSource",this._player.play()}replaceTrack(i){this._player.setTrack(i),this._player.play()}close(){super.close(),this._player.stop()}};var Gg=`
|
|
33
|
+
`,t.onclick=this.onQuestionClick.bind(this);let r=document.createElement("div");r.className=Pc,r.innerText=`${Rt()?"\u8BE6\u60C5 >":"Detail >"}`,r.onclick=this.onCollapseClick.bind(this);let o=i.content.firstChild,n=o.querySelector(`.${ea}`);return n.appendChild(r),n.appendChild(t),n.appendChild(e),o}addDiaLog(){Uc()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${ms}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",C.info("show autoplay dialog"),ee.uploadEvent({log:c_}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){C.warn("confirm clicked, try resume stream"),E.emit(T.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${Mh}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||ee.uploadEvent({log:l_}),this._isCollapseClicked=!0}onQuestionClick(){window.open(wh,"_blank"),this._isQuestionClicked||ee.uploadEvent({log:u_}),this._isQuestionClicked=!0}},Uh=xc;var ct=class extends ei{constructor(e){super(e,m.VIDEO);d(this,"stat",{});d(this,"_calculateTimeout",-1);d(this,"viewMirror",!1);d(this,"objectFit");d(this,"container");d(this,"canvas");d(this,"canvasTrack");this.mode=e.canvas?1:0,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(m.VIDEO);this.track&&this.mode!==2&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,(t=this.container)==null||t.appendChild(this.elementToRender),this.bindElementEvents(),this.calculateStat()}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.canvasTrack)&&this.elementToRender&&((t=this.container)==null||t.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(m.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(m.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleTrackEvent(e){var t;super.handleTrackEvent(e),e.type===m.MUTE&&((t=this.stat)!=null&&t.fps)&&(this.stat.fps=0)}handleElementEvent(e){var r;if(this.mode===2)return;super.handleElementEvent(e);let t=e.type;if(t===m.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn(`${this.kind} player has been remove, element ID: ${(r=this.container)==null?void 0:r.id}`),this._pausedRetryCount>0&&!Uc()&&(this._log.info(`${this.kind} player auto resume when paused`),this.resume(),this._pausedRetryCount--),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let o=this.element.style.transform;t===m.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=o.replace("scaleX(-1)",""):t===m.LEAVE_PICTURE_IN_PICTURE&&!o.includes("scaleX")&&(this.element.style.transform=`${o} scaleX(-1)`)}}setCanvas(e,t=1){var r,o,n,a;this.canvas!==e&&((r=this.canvas)==null||r.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?t:0,this.mode===2&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?((o=this.element)==null||o.remove(),(n=this.container)==null||n.appendChild(e)):this.element&&((a=this.container)==null||a.appendChild(this.element)))}setAttr(e){let t=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);t.style=Object.assign({width:"100%",height:"100%"},t.style),super.setAttr(t)}get mirror(){return this.viewMirror}setRect(e,t){this.elementToRender&&(this.elementToRender.style.width=`${e}px`,this.elementToRender.style.height=`${t}px`)}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit=`${e}`),this.objectFit=e}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(),this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(de.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this.elementToRender&&this.elementToRender.parentElement!==this.container&&this.container&&this.container.append(this.elementToRender)))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(Ir()&&this.element&&this._calculateTimeout<0){let e=0,t=null,r=(o,n)=>{this.stat.width=n.width,this.stat.height=n.height,t&&(this.stat.fps=Math.round((n.presentedFrames-t.presentedFrames)/(o-e)*1e3)),e=o,t=n,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var a;return(a=this.element)==null?void 0:a.requestVideoFrameCallback(r)},2e3))};this.element.requestVideoFrameCallback(r)}}catch(e){this._log.warn("init stat failed",e)}}};function bi(s,i){return f(this,null,function*(){if(!s.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield s.audioWorklet.addModule(i),C.info("worklet addModule success")}catch(e){throw C.info(`worklet addModule catch error. ${e.message}`),e}})}var ko;typeof AudioContext!="undefined"?ko=AudioContext:typeof webkitAudioContext!="undefined"?ko=webkitAudioContext:typeof mozAudioContext!="undefined"&&(ko=mozAudioContext);var xt,Vh=-1;Bh();function Bh(){try{if(xt)return;xt=new ko({sampleRate:48e3}),xt.onstatechange=()=>{C.info(`context state: ${xt.state}${xt.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),ps()},clearTimeout(Vh)}catch(s){C.error(`initAudioContext failed: ${s} typeof AudioContextClass: ${typeof ko}`),Vh=setTimeout(Bh,1e3)}}var ps=()=>{xt.state==="suspended"?(fs(),document.addEventListener("click",ps)):xt.state==="interrupted"?fs():(document.removeEventListener("visibilitychange",ps),document.removeEventListener("click",ps))},Vc=0,Bc=-1;function fs(){return new Promise((s,i)=>{if(xt.state==="running")return s();Date.now()-Vc<1e3?(clearTimeout(Bc),Bc=setTimeout(()=>{Vc=Date.now(),xt.resume().then(s,i)},1e3)):(clearTimeout(Bc),Vc=Date.now(),xt.resume().then(s,i))}).catch(s=>{C.warn(`context resume failed: ${s}`),document.addEventListener("visibilitychange",ps)})}document.addEventListener("click",ps);var He=s=>xt;var we=class{constructor(){d(this,"node");d(this,"pre",new Set);d(this,"next",new Set);d(this,"context");d(this,"connectedNodes",new Set);d(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(),N.addSuccessEvent({key:502701})}catch(t){C.error(t),N.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(),N.addSuccessEvent({key:502702})}catch(e){C.error(e),N.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}},ia=class extends we{constructor(e=256){super();this.fftSize=e;d(this,"dataArray",new Uint8Array(0))}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let e=this.getByteTimeDomainData(),t=1,r=0,o=0,n=`M${r},${o}`;for(let a=0;a<e.length;a++)o=e[a]/128*100/2,n+=`L${r},${o}`,r+=t;return n}},Mo=class{constructor(){d(this,"source",new we);d(this,"gain",new we);d(this,"destination",new we)}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(Lo(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}},_s=class extends Mo{constructor(e){super();this.context=e;d(this,"aec",new we);d(this,"mixNode",new we);d(this,"muteNode",new we);d(this,"denoiser",new we);this.source.pipeTo(this.aec.pipeTo(this.denoiser.pipeTo(this.gain.pipeTo(this.destination)))),this.muteNode.pipeTo(this.mixNode.pipeTo(this.aec))}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.aec.setContext(this.context),this.mixNode.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.aec.removeContext(),this.mixNode.removeContext(),this.denoiser.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.aec.deleteNode(),this.mixNode.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}},ra=class{constructor(){d(this,"audioContext",He("audio-mixer"));d(this,"destination",this.audioContext.createMediaStreamDestination());d(this,"inputs",new Set);d(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]}},Fh=new WeakMap;function Lo(s){let i=Fh.get(s);if(i)return i;let e=He();if(s instanceof HTMLAudioElement)i=e.createMediaElementSource(s);else if(s instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([s]));else return s;return Fh.set(s,i),i}var lt=class lt{constructor(i){d(this,"_volume",0);d(this,"_volumeDb",0);d(this,"_log");d(this,"_scriptProcessorNode",null);d(this,"_audioWorkletNode",null);d(this,"_interval",200);d(this,"ready",this.preload());let{log:e}=i;this._log=e,E.on(T.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-lt.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!lt.workletReady){let i='class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,s){t=t[0],s=s[0];if(t||s){if(this.isStop)return!1;var i=s&&s[0]?s[0].length:0,h=this.cache.length,a=(i<h?(s[0].set(this.cache.slice(0,i)),this.cache=this.cache.slice(i)):this.unmute&&s[0].set(t[0]),(i<h?s:t)[0]);if(a){let e=0;for(let t=0;t<a.length;++t)e=Math.max(Math.abs(a[t]),e);s=a.reduce((t,e)=>t+e*e,0)/a.length;this.volume=e,this.tick-=a.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,volumeDb:Math.max(10*Math.log10(s)+100,0)/100,cacheLen:h,outputLen:i}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';lt.workletReady=bi(lt.audioContext,URL.createObjectURL(new Blob([i],{type:"application/javascript"})))}return lt.workletReady.then(()=>this.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(lt.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{lt.lastMessageTime=Date.now(),this._volume=e.data.volume||0,this._volumeDb=e.data.volumeDb||0,!i&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),i=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(i){this._log.error(`volumeMeter init audio worklet error: ${i}`),ee.logFailedEvent({userId:this._log.userId,eventType:Ke.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=He("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{lt.lastMessageTime=Date.now();let e=i.inputBuffer.getChannelData(0),t=0;for(let r=0;r<e.length;++r)t+=e[r]*e[r];this._volume=Math.sqrt(t/e.length)||0}}catch(i){this._log.error(`volumeMeter init script processor error: ${i}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,E.off(T.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}getInternalAudioLevel(){return this._volume}getCalculatedVolume(){return parseFloat(this._volume.toFixed(2))}getVolumeDb(){return Math.floor(this._volumeDb*100)}handleAudioLevelInterval(i){var t;let{interval:e}=i;this._interval=e,(t=this._audioWorkletNode)==null||t.port.postMessage({name:"setIntervalTime",intervalTime:e})}};d(lt,"lastMessageTime",0),d(lt,"audioContext",He("volume-meter")),d(lt,"workletReady");var sa=lt,oa=class extends we{constructor(e){super();d(this,"_volumeMeter");this._volumeMeter=new sa(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()}getVolumeDb(){return this._volumeMeter.getVolumeDb()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),r=new Float32Array(t>>2);e.copyTo(r,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:r},[r.buffer]),e.close()}}},Ar=sa;var Wh=Pe(je(),1);var $h=s=>i=>i.deviceId===s;var Po=class{constructor(i,e="Input"){d(this,"kind");d(this,"type");d(this,"devices",[]);this.kind=i,this.type=e}update(i,e){let t=i.filter(r=>r.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&gs(this.devices[0])){this.devices=t;return}e&&(t.forEach(r=>{if(r.deviceId&&!this.devices.find($h(r.deviceId))){let o=`${this.kind}${this.type}Added`;C.warn(`${o}: ${JSON.stringify(r)}`),e.emit(o,r)}}),this.devices.forEach(r=>{if(r.deviceId&&!t.find($h(r.deviceId))){let o=`${this.kind}${this.type}Removed`;C.warn(`${o}: ${JSON.stringify(r)}`),e.emit(o,r)}})),this.devices=t}hasDevice(i){return!!this.devices.find(e=>e.deviceId===i)}},Fc=class extends Wh.EventEmitter{constructor(){super();d(this,"audioInputs",new Po(m.AUDIO));d(this,"videoInputs",new Po(m.VIDEO));d(this,"audioOutputs",new Po(m.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||re.run("interval",()=>{this.update()},{delay:1e4}))}init(){na().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 na(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}},be=$s||$r?null:new Fc;function gs(s){return s.deviceId===s.groupId&&s.groupId===""}function na(){return f(this,arguments,function*(s=0){if(Ci()||!Xn())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(s!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{gs(t)&&(t.kind===m.AUDIO_INPUT?e.audio=!0:t.kind===m.VIDEO_INPUT&&(e.video=!0))}),s===2&&(e.audio=!1),s===1&&(e.video=!1),e.audio||e.video){let t;try{t=yield navigator.mediaDevices.getUserMedia(e),e.audio&&fs()}catch(r){C.debug("capture before getDevices failed: ",r)}i=yield navigator.mediaDevices.enumerateDevices(),t==null||t.getTracks().forEach(r=>r.stop())}}return i.map((e,t)=>{let r={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${t}`};return e.deviceId.length>0&&Hc.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(r.getCapabilities=()=>e.getCapabilities()),r})})}function it(s=!1){return be.update(s?1:0).then(i=>i.audioInputs.devices)}function ut(s=!1){return be.update(s?2:0).then(i=>i.videoInputs.devices)}var Gh=!1;function Jh(){return f(this,null,function*(){try{Gh||(Gh=!0,C.info(`speakers:${(yield Zi()).map(s=>` ${s.deviceId.slice(0,8)}: ${s.label}`)}`))}catch(s){}})}function Zi(s=!1){return f(this,null,function*(){return(ve||Be)&&(s=!1),be.update(s?1:0).then(i=>i.audioOutputs.devices)})}var Hc=new Set;function qh(s){if(s instanceof CanvasCaptureMediaStreamTrack||!(s instanceof MediaStreamTrack))return!1;let i=s.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;let t=`${((s==null?void 0:s.getSettings())||{}).deviceId}_${m.VIDEO_INPUT}`;return!!Hc.has(t)}function jh(s){if(s instanceof CanvasCaptureMediaStreamTrack||!(s instanceof MediaStreamTrack))return!1;let i=s.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("\u9EA6\u514B\u98CE"))return!0;let t=`${((s==null?void 0:s.getSettings())||{}).deviceId}_${m.AUDIO_INPUT}`;return!!Hc.has(t)}function $c(s,i){return f(this,null,function*(){let t=(yield it()).find(r=>r.deviceId===cr);return!i&&(t==null?void 0:t.groupId)===s||(t==null?void 0:t.groupId)===s&&t.label===i})}function Xh(o){return f(this,arguments,function*({newDeviceId:s,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:r}){return s!==i?!1:r===m.AUDIO&&s===cr?yield $c(e,t):!0})}var aa,Gc=class extends Mo{constructor(e){super();this.log=e;d(this,"volumeMeter");d(this,"volumeDestination");d(this,"analyser",new ia);this.volumeMeter=new oa({log:this.log}),this.volumeDestination=new we,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},da=class s extends ei{constructor(e){super(e,m.AUDIO);d(this,"_outputDeviceId");d(this,"_volume",1);d(this,"_destination",He("player").createMediaStreamDestination());d(this,"pipeline");d(this,"volumeMeterMode","worklet");this.mode=0,this.pipeline=new Gc(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((ji==="15.2"||ji==="15.3"||ji==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let r=aa||new Audio;r.setAttribute("autoplay","autoplay"),r.srcObject=this.getMediaStream(),r.muted=this.muted,this.element=r,Y(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),r===aa&&(aa=void 0),this.bindElementEvents()}play(e){return f(this,null,function*(){if(this.track)return this.pipeline.source.node||this.pipeline.replaceSource(this.track),this.element||this.initializeElement(e==null?void 0:e.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?this.pipeline.volumeMeter.init():this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(He("player").createAnalyser()),Jh(),xe(s.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(e)}setSinkId(e){return f(this,null,function*(){var t,r;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(r=(t=this.element).setSinkId)==null?void 0:r.call(t,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){this.element&&(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}},ca=class extends da{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(de.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)}},la=class extends da{constructor(e){super(e);d(this,"_sourceElement");d(this,"_output",new we);this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter.pipeTo(this._output),this.pipeline.destination))}setOutput(){this.mode=1,this._output.setNode(He("player").destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var t,r,o;((r=(t=this.element)==null?void 0:t.error)==null?void 0:r.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(de.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=((o=e.getSettings())==null?void 0:o.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){this._volume=e,this.useDestination?(this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`)):e<=1?this.element?(this._log.info(`set element volume: ${e}`),this.element.volume=e):this._log.info("set element volume: no element"):ve||(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),Se(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(e=0){this.pipeline.destroy();let t=this._sourceElement||this.element;t&&Ji&&(aa=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var Cr=class extends Q{constructor({userId:e,sdkAppId:t,mediaType:r,room:o,PlayerClass:n=r===1?la:ct}){var a;super();d(this,"id",po());d(this,"userId","");d(this,"isRemote");d(this,"mediaType");d(this,"room");d(this,"user");d(this,"_log");d(this,"_inputTrack");d(this,"_outputTrack");d(this,"isPlayCalled");d(this,"container",null);d(this,"player");d(this,"subVideoPlayerMap");d(this,"muted",!1);d(this,"abortCtrl");d(this,"objectFit","cover");d(this,"mirror");d(this,"isScreen",!1);d(this,"manager");d(this,"trackSettings");d(this,"isFirstVideoFrameEmitted",!1);this.userId=e||"",this.mediaType=r,this._log=C.createLogger({id:`${this.kind[0]}t`,userId:(a=o||this.room)==null?void 0:a.userId,remoteUserId:this instanceof Ni?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof Ni}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(de.PLAYER_STATE_CHANGED,c=>{E.emit(T.PLAYER_STATE_CHANGED,v({track:this},c)),this.emit("player-state-changed",c)}),this.kind===m.VIDEO&&(this.player.on(de.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(de.LOADED_DATA),E.emit(T.VIDEO_LOADED_DATA,{track:this})}),this.player.on(de.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(de.LOADED_META_DATA)}),this.player.on(de.MEDIA_TRACK_CHANGED,c=>{var l;(l=this.subVideoPlayerMap)==null||l.forEach(h=>h.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(de.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||C}get kind(){return this.mediaType===1?m.AUDIO:m.VIDEO}get strMediaType(){return this.mediaType===4?m.VIDEO:this.mediaType===2?m.SCREEN:m.AUDIO}get streamType(){return(this.mediaType&2)===0?"main":"auxiliary"}get isMediaTrackActive(){return this.mediaTrack?!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled:!1}play(e,t){return f(this,null,function*(){let r=Te(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 ct&&(this.player.setObjectFit(this.objectFit),this.container!==r&&r&&(this.container=r,this.player.setContainer(r)),Te(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===m.VIDEO)&&this.setPlayerMute(!0),t&&!g(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof ct&&this.player.setObjectFit(this.objectFit),this.isPlayCalled=!0,r&&(this.container=r,this.player instanceof ct&&this.player.setContainer(r)),E.emit(T.PLAY_TRACK_START,{track:this}),!this._outputTrack){this.log.info("play has not mediaTrack, abort");return}this._log.info(`play with options: ${JSON.stringify(t)}`);try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(t),Te(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),t))}catch(o){throw this.handleAutoPlayFailed(o),o}})}setMirror(e,t){if(this.isScreen||this.kind!==m.VIDEO||g(e)||e===this.mirror)return;this.mirror=e;let r=this.player;t&&(r=t);let o=this.manager;if(me(this.mirror)){r.setViewMirror(this.mirror),o&&(o.mirror=!1);return}switch(this.mirror){case"view":{o&&(o.mirror=!1),r.setViewMirror(!0);break}case"publish":{o&&(o.mirror=!0),r.setViewMirror(!0);break}case"both":o&&(o.mirror=!0),r.setViewMirror(!1)}}playSubContainer(e,t){return f(this,null,function*(){if(!this._outputTrack||this.kind===m.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((o,n)=>{var a;e.find(c=>n===c)||(o.stop(),(a=this.subVideoPlayerMap)==null||a.delete(n))});for(let[o,n]of e.entries()){let a=this.subVideoPlayerMap.get(n);a?t&&(g(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new ct({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${o+1}`})}))}let r=[...this.subVideoPlayerMap.values()];for(let o of r)o.setViewMirror(this.player.mirror),yield o.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(e=!1){this.isPlayCalled&&(this.isPlayCalled=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(Vd(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(t=>{t.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(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),E.emit(e?T.TRACK_MUTED:T.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){Fe(e,e).add(m.MUTE,this.onTrackMuted).add(m.UNMUTE,this.onTrackUnmuted).add(m.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===m.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){Se(e)}setInputMediaStreamTrack(e){var r;let t=this._inputTrack;if(e!==t)return this._inputTrack=e,this.trackSettings=(r=e.getSettings)==null?void 0:r.call(e),e.enabled=!this.muted,t&&this.uninstallTrackEvent(t),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,t||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var r;let t=this._outputTrack;e!==t&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(r=e.getSettings)==null?void 0:r.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped){this.player.play().catch(t=>this.handleAutoPlayFailed(t)),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(Vd(this)?this.jitterBufferDelay:0),this.log.info(`playing state updated, stop ${this.kind}`);return}}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}handleAutoPlayFailed(e){if(this.room&&this.room.enableAutoPlayDialog)new Uh;else{let t=()=>{this.resume().then(()=>{document.removeEventListener("click",t,!0)})};document.addEventListener("click",t,!0)}this.emit("error",e)}getVideoFrame(){return this.player instanceof ct?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var n,a,c;if(this.isFirstVideoFrameEmitted)return;let t=(n=this.mediaTrack)==null?void 0:n.getSettings(),r=(t==null?void 0:t.width)||((a=this.player.element)==null?void 0:a.videoWidth)||0,o=(t==null?void 0:t.height)||((c=this.player.element)==null?void 0:c.videoHeight)||0;e===de.LOADED_META_DATA&&!r&&!o||(e===de.LOADED_DATA&&!r&&!o&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,this.emit("first-video-frame",{width:r,height:o,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};y([le([],Q.INIT,{sync:!0})],Cr.prototype,"close",1);var m_=Object.prototype.hasOwnProperty,{toString:XA}=Object.prototype;function p_(s){if(s==null)return!0;if(typeof s=="boolean")return!1;if(typeof s=="number")return s===0;if(typeof s=="string"||typeof s=="function"||Array.isArray(s))return s.length===0;if(s instanceof Error)return s.message==="";if(Ze(s))switch(Object.prototype.toString.call(s)){case"[object File]":case"[object Map]":case"[object Set]":return s.size===0;case"[object Object]":{for(let i in s)if(m_.call(s,i))return!1;return!0}}return!1}var ti=p_;var f_=function(s){return f(this,null,function*(){let i=g_(s);C.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],r=["label","deviceId","groupId"];i.audio&&(e=yield it(),C.info(`microphones: ${ft(e.map(o=>k(v({},o),{groupId:o.groupId.substring(0,8)})),{keysToInclude:r})}`)),i.video&&(t=yield ut(),C.info(`cameras: ${ft(t,{keysToInclude:r})}`));try{let o=yield navigator.mediaDevices.getUserMedia(i);return yc&&o.getTracks().forEach(n=>{C.info(`${n.kind} capabilities: ${ft(n.getCapabilities(),{keysToInclude:gn})}`)}),i.audio&&fs(),o}catch(o){let{message:n}=o;throw o.name==="NotFoundError"&&(s.video&&t&&t.length===0&&(n=V({key:w.CAMERA_NOT_FOUND})),s.audio&&e&&e.length===0&&(n=V({key:w.MICROPHONE_NOT_FOUND}))),new b({code:S.INITIALIZE_FAILED,name:o.name,message:n,constraint:o.constraint})}})},__=Jt({retryFunction:f_,settings:{retries:3,timeout:500},onError:({error:s,retry:i,reject:e,retryFuncArgs:t,retriedCount:r})=>{let o=r+1;s.name==="NotReadableError"||s.name==="OverconstrainedError"?(o===1?(t[0].video&&(t[0].maxResolution=!1,(!Be||t[0].width*t[0].height<=1920*1080)&&t[0].frameRate&&(t[0].frameRate=t[0].frameRate>10?10:5)),t[0].retryWhenExactFailed&&t[0].useExactDeviceId&&(t[0].useExactDeviceId=!1)):o===2?t[0].useDeviceIdOnly=!0:o===3&&!t[0].useExactDeviceId&&(t[0].useTrueAsConstraint=!0),i()):e(s),t[0].microphoneId&&Qh(t[0].microphoneId,!1),t[0].cameraId&&Qh(t[0].cameraId,!0)},onRetrying:s=>{C.warn(`getUserMedia NotReadableError observed, retrying [${s}/3]`)},onRetryFailed:s=>{ee.logFailedEvent({eventType:Ke.GET_USER_MEDIA_RETRY,error:s})},onRetrySuccess:s=>{ee.logSuccessEvent({eventType:Ke.GET_USER_MEDIA_RETRY}),ee.uploadEvent({log:`stat-${Ke.GET_USER_MEDIA_RETRY}-success-${s}`})}});function Qh(s,i){return f(this,null,function*(){let t=(i?yield ut():yield it()).find(r=>r.deviceId===s);t&&oe(t.getCapabilities)&&C.warn(ft(t.getCapabilities(),{keysToInclude:gn}))})}function g_(s){return{audio:T_(s),video:E_(s)}}function T_(s){if(!s.audio)return!1;if(s.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:s.sampleRate};return!ti(s.microphoneId)&&(i.deviceId=s.useExactDeviceId?{exact:s.microphoneId}:s.microphoneId,s.useDeviceIdOnly)?i:(Y(s.channelCount)&&(i.channelCount=s.channelCount),me(s.echoCancellation)&&!s.echoCancellation&&(i.echoCancellation=!1),me(s.noiseSuppression)&&!s.noiseSuppression&&(i.noiseSuppression=!1),me(s.autoGainControl)&&!s.autoGainControl&&(i.autoGainControl=!1),ti(i)?!0:i)}function E_(s){if(!s.video)return!1;if(s.useTrueAsConstraint)return!0;let{maxResolution:i=!0}=s,e={};return s.cameraId?e.deviceId=s.useExactDeviceId?{exact:s.cameraId}:s.cameraId:s.facingMode&&(e.facingMode=s.facingMode),s.useDeviceIdOnly&&!ti(e)?e:(s.width&&(e.width={ideal:s.width},i&&!ae&&(e.width.max=s.width)),s.height&&(e.height={ideal:s.height},i&&!ae&&(e.height.max=s.height)),ae&&Dt&&s.width&&s.height&&s.width*s.height<352*288&&(e.width=s.width,e.height=s.height),s.frameRate&&(e.frameRate=s.frameRate),ti(e)?!0:e)}var zh=__;function ua(s){return J((i,e)=>function(...t){return f(this,null,function*(){return yield s.apply(this,t),i.apply(this,t)})})}function Qe(s){return J((i,e)=>function(...t){return f(this,null,function*(){let r=yield i.apply(this,t);return yield s.call(this,...t),r})})}function ha(s){return J((i,e)=>function(...t){return f(this,null,function*(){try{return yield i.apply(this,t)}catch(r){s.call(this,r)}})})}function J(s){return function(i,e,t){return t.value=s(t.value,e),t}}var Yh=(()=>{let s=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&C.info(`visibility change: ${document.visibilityState}`),!s&&(document.addEventListener("visibilitychange",()=>{C.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),s=!0)}})();var S_=0,ma=class{constructor(){d(this,"log",C.createLogger({id:`fq${++S_}`}));d(this,"isRunning",!1);d(this,"queue",[])}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(i,e=!1){var o,n;let t=v({},i),r=new Promise((a,c)=>{t.resolve=a,t.reject=c});return t.promise=r,e?this.length<=1?this.queue.push(t):(n=(o=this.lastQueueItem)==null?void 0:o.promise)==null||n.then(t.resolve,t.reject):this.queue.push(t),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),r}shift(){let i=this.queue.shift();return this.log.debug(`shift ${this.length}`),i}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:i,args:e,context:t,resolve:r,reject:o}=this.queue[0];this.isRunning=!0,i.apply(t,e).then(r,o).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},xo=new WeakMap,pa=new WeakMap;function ii(s=!1){return function(i,e,t){let r=t.value;return t.value=function(...o){let n=xo.get(this)||new ma;return xo.set(this,n),n.push({fn:r,args:o,context:this},s)},t}}function Kh(s){return function(i,e,t){let r=t.value;return t.value=function(...o){let n=xo.get(this);if(n){let a=n.queue.filter((c,l)=>{if(l===0)return!0;let h=!0;return c.args.forEach(u=>{o.find(p=>p===u)||(h=!1)}),h?(c.reject(new b({code:S.API_CALL_ABORTED,message:s})),!1):!0});n.queue=a}return r.apply(this,o)},t}}function fa(s){return function(i,e,t){let r=t.value;return t.value=function(...o){var a,c,l;let n=[];return(c=(a=xo.get(this))==null?void 0:a.queue)==null||c.forEach(h=>n.push(h)),(l=pa.get(this))==null||l.forEach(h=>h==null?void 0:h.queue.forEach(u=>n.push(u))),n.forEach(h=>{h.reject(new b({code:S.API_CALL_ABORTED,message:s}))}),xo.delete(this),pa.delete(this),r.apply(this,o)},t}}function vi(s){return function(i,e,t){let r=t.value,o=n=>s(...n);return t.value=function(...n){let a=pa.get(this)||new Map,c=a.get(o(n))||new ma;return a.set(o(n),c),pa.set(this,a),c.push({fn:r,args:n,context:this})},t}}function rt(s,i){return J((e,t)=>function(...r){let o=s;try{let n=e.apply(this,r),a=L();return Wi(n)?n.then(c=>(i?N.addSuccessEvent({key:o,cost:L()-a}):N.addSuccessEvent({key:o}),c)).catch(c=>{throw N.addFailedEvent({key:o,error:c}),c}):(N.addSuccessEvent({key:o}),n)}catch(n){throw N.addFailedEvent({key:o,error:n}),n}})}var Rr=class Rr extends Cr{constructor(e,t){super({mediaType:e,PlayerClass:t});d(this,"isRemote",!1);d(this,"deviceId");d(this,"groupId","");d(this,"label","");d(this,"_isRecapturing",!1);d(this,"_lastRecaptureTime",0);d(this,"_onMuteTimeoutId",-1);d(this,"_encodeCheckTimeoutId",-1);d(this,"profile")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}encodeFrame(e,t){throw new Error("Method not implemented.")}installTrackEvent(e){Fe(e,e).add(m.MUTE,this.onTrackMuted).add(m.UNMUTE,this.onTrackUnmuted).add(m.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===m.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){Se(e)}setStateToCapture(){}capture(e){return f(this,null,function*(){var t;try{let r=L();E.emit(T.LOCAL_TRACK_CAPTURE_START,{track:this});let o;e.customSource?(o=new MediaStream,o.addTrack(e.customSource)):((t=this.mediaTrack)==null||t.stop(),o=yield zh(e));let n=o.getTracks()[0];return yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),E.emit(T.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:L()-r}),o}catch(r){throw E.emit(T.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:r}),this.log.error(`getUserMedia error observed ${r}`),r}})}setInputMediaStreamTrack(e){return this.state===Q.INIT&&this.setStateToCapture(),super.setInputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var t;if(super.setOutputMediaStreamTrack(e),this.isPublishing||this.isPublished)return(t=this.room)==null?void 0:t.replaceTrack(this)}publish(e,t){return this.room=e,this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),t}unpublish(){this.room&&this.room.localTracks.delete(this),E.emit(T.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return f(this,null,function*(){if(this.mediaTrack&&zt){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:r}=this.mediaTrack;(yield Xh({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=r,t&&(this.groupId=t),na().then(n=>{let a=n.find(c=>c.deviceId===e);a&&this.emit("2",a)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.mediaTrack||this.kind===m.AUDIO&&!jh(this.mediaTrack)||this.kind===m.VIDEO&&!qh(this.mediaTrack)||this._isRecapturing||e&&Dt&&Be)}onTrackMuted(){if(super.onTrackMuted(),Yh(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<Jr){setTimeout(()=>this.onTrackMuted(),Jr);return}this._onMuteTimeoutId=setTimeout(()=>f(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((ve||pe)&&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(xe(Rr.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<Jr){setTimeout(()=>this.onTrackEnded(),Jr);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return f(this,null,function*(){var r;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),(r=this._inputTrack)==null||r.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let t={useExactDeviceId:!0};if(e==="user"||e==="environment")t.facingMode=e;else{let o;(this.kind==="audio"?yield it():yield ut()).find(a=>a.deviceId===e)&&(o=e),t.deviceId=o}return this.capture(t).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),E.emit(T.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(o=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${o.message}`),this.emit("5",o),E.emit(T.LOCAL_TRACK_RECAPTURE,{track:this,error:o})})})}getRecoverCaptureDeviceId(){return f(this,null,function*(){let e=this instanceof $e;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let r=(wo.get(t)||0)+1;if(wo.set(t,r),r>=3){let o=e?(yield ut()).find(n=>!wo.has(n.deviceId)):(yield it()).find(n=>!wo.has(n.deviceId));o&&(this.log.warn(`${t} capture fail ${r} times, change new ${o.deviceId}`),t=o.deviceId)}}return t})}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),(e=this.manager)==null||e.removeInput(this)}};y([le(Q.INIT,"capture",{ignoreError:!0,sync:!0})],Rr.prototype,"setStateToCapture",1),y([ii()],Rr.prototype,"capture",1),y([le("capture","publish",{ignoreError:!0,success(){var t,r;this.room.localTracks.add(this),E.emit(T.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),!((((r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.uplinkNetworkQuality)||0)>3)&&(this._encodeCheckTimeoutId=setTimeout(()=>{var n,a;if(!((((a=(n=this.room)==null?void 0:n.networkQuality)==null?void 0:a.uplinkNetworkQuality)||0)>3)&&this.isPublished&&this.isMediaTrackActive){let c=this.kind===m.AUDIO,l=this.stat.bytesSent>0;N[l?"addSuccessEvent":"addFailedEvent"]({key:c?503700:513702}),l||(N.addEnum({key:c?503701:513703,value:mo()}),ee.uploadEvent({log:`stat-encode-failed-${this.kind}-${_r()||Ei()}`,userId:this.userId}),this.log.warn("encode failed"),this.emit("6",this))}},5e3))},fail(e){let t="error";if(e.cause instanceof RTCError){let r=e.cause;r.message.includes("timeout")?t="timeout":r.code===S.API_CALL_ABORTED&&(t="api-call")}this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:e.cause||e})}}),rt(521714,!1)],Rr.prototype,"publish",1),y([J(e=>function(){return f(this,null,function*(){let t=this.state==="publish"?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),le([],"capture",{sync:!0})],Rr.prototype,"unpublish",1);var Ni=Rr,wo=new Map;E.on(T.SWITCH_DEVICE_SUCCESS,s=>{s.track.deviceId&&wo.delete(s.track.deviceId)});var ht=class s extends Ni{constructor(e){super(1,ca);d(this,"mediaType",1);d(this,"volume",0);d(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});d(this,"playerMuted",!0);d(this,"pipeline");d(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});d(this,"mixedUsersMap",new Map);this.manager=e,this.pipeline=new _s(e),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}get dbVolume(){return Ar.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}get playerMediaTrack(){return this.mediaTrack}setInputMediaStreamTrack(e){return f(this,null,function*(){let t=this.trackSettings||{};N.addEnum({key:501701,value:t.channelCount||0,useUV:!1}),N.addEnum({key:501702,value:t.sampleRate||0,useUV:!1}),N.addEnum({key:502700,value:0});let{sampleRate:r,channelCount:o}=t;this._log.info(`local audio track input ${JSON.stringify({sampleRate:r,channelCount:o})}`),this.pipeline.source.channelCount=o||1,this.pipeline.replaceSource(e),yield xe(s.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture({deviceId:e,customSource:t,useExactDeviceId:r=!0,retryWhenExactFailed:o=!0}){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:r,retryWhenExactFailed:o,customSource:t})}switchDevice(e){return f(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e)if(e===cr){if(yield $c(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,retryWhenExactFailed:!1}),E.emit(T.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(t){throw this.log.error(`switch microphone failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}}})}listenDeviceChange(){be&&!be.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&be.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return f(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current microphone is lost: ${JSON.stringify(e)}`),he(this.userId,{eventId:2003,param1:6,streamType:1});let t=yield it();t[0]?this.recapture(t[0].deviceId):be.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(o){return f(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:r}){let n=!1;!g(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,n=!0),!g(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,n=!0),!g(r)&&r!==this.profile.autoGainControl&&(this.profile.autoGainControl=r,n=!0),n&&this.deviceId&&(yield this.recapture(this.deviceId))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&N.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(r=>this._log.warn(`${e?"enable":"disable"} ANS failed `,r))}enableTrackAEC(e){if(!this._inputTrack)return;let t=this._inputTrack.getConstraints();return t.echoCancellation=e,this._inputTrack.applyConstraints(t).catch(r=>this._log.warn(`${e?"enable":"disable"} AEC failed `,r))}addDenoiser(e){var t;if(kt<=92&&((t=this.trackSettings)==null?void 0:t.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}N.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.resetPlayerSource(),this.enableTrackANS(!1)}mixPlayTrack(e,t){if(!e){this.log.warn("[aec] mixPlayTrack failed. reason: remote audio track is null");return}if(this.mixedUsersMap.has(t))return;this.log.warn("[aec] mixPlayTrack()",t===""?"*local":t);let r=Lo(e),o=new we;o.pipeTo(this.pipeline.mixNode),o.setNode(r),this.mixedUsersMap.set(t,o)}unMixPlayTrack(e){let t=this.mixedUsersMap.get(e);t&&(this.log.warn("[aec] unMixPlayTrack()",e===""?"\u2191":e),t.deleteNode(),this.mixedUsersMap.delete(e))}addAEC(e,t,r){this.pipeline.muteNode.setNode(r),this.pipeline.mixNode.setNode(t),this.pipeline.aec.setNode(e),this.resetPlayerSource(),this.enableTrackAEC(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.resetPlayerSource(),this.enableTrackANS(!0))}removeAEC(e){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.resetPlayerSource(),this.enableTrackAEC(!0))}resetPlayerSource(){this.player.setSourceNode(this.pipeline.gain.node||this.pipeline.denoiser.node||this.pipeline.aec.node||this.pipeline.source.node)}close(){this.pipeline.remove(),be.off("audioInputAdded",this.handleMicrophoneAdded,this),be.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return f(this,null,function*(){try{yield xe(s.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield it()).find(o=>o.deviceId!==e);if(r)yield xe(s.prototype,this,"recapture").call(this,r.deviceId);else throw t}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((t,r)=>r?r({frame:t}):t,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}};var Di=class{constructor(i,e=!1){this.dataView=i;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-2,t=[],r=0;for(let n=i;n<=e;n++){let a=this.dataView.getInt8(n);switch(a){case 0:case 1:case 2:case 3:r===2&&(t.push(3),r=0),a==0?r++:r=0,t.push(a);break;default:r=0,t.push(a);break}}t.push(this.dataView.getInt8(this.dataView.byteLength-1));let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=o}removePreventionByte(){let i=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,t=[],r=0;for(let n=i;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:r++,t.push(this.dataView.getInt8(n));break;case 3:r!==2&&t.push(this.dataView.getInt8(n)),r=0;break;default:t.push(this.dataView.getInt8(n)),r=0;break}let o=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,i),...t]).buffer);this.dataView=o}get isSEI(){return this.dataView.getUint8(4)===6}get seiPayloadStartIndex(){let i=6;for(let e=6;e<this.dataView.buffer.byteLength&&(i++,this.dataView.getUint8(e)===255);e++);return i}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let i=0,e=6;for(let o=6;o<this.dataView.buffer.byteLength;o++){let n=this.dataView.getUint8(o);if(e++,n===255)i+=255;else{i+=n;break}}let t=new ArrayBuffer(i),r=new DataView(t);for(let o=0;o<t.byteLength;o++,e++)r.setInt8(o,this.dataView.getInt8(e));return r}};var _a=class{constructor(){d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_seiPayloadType",243)}encodeSEINalu(i){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,o=[];o.push(0,0,0,1,6,this._seiPayloadType);for(let a=0;a<t;a++)o.push(255);o.push(r);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Di(new DataView(new Uint8Array(o).buffer),!0)}sendSEI(i,e){e!=null&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(i),e!=null&&e.small&&this._smallSeiMessageList.push(i)}isEmpty(){return!this._seiMessageList.length}getNaluCount(i){let e=0,t=0,r=new DataView(i);for(let o=0;o<i.byteLength;o++)switch(r.getUint8(o)){case 0:e++;break;case 1:(e===2||e===3)&&t++,e=0;break;default:e=0;break}return t}encode(i,e){let t=e?this._smallSeiMessageList:this._seiMessageList;if(t.length>0&&i.data.byteLength>0){let o=9-this.getNaluCount(i.data);if(o<=0)return 0;let n=t.splice(0,o).reverse().map(this.encodeSEINalu.bind(this)),a=n.reduce((p,_)=>p+_.dataView.byteLength,0),c=new ArrayBuffer(a+i.data.byteLength),l=new DataView(c),h=new DataView(i.data),u=0;for(let p=0;p<n.length;p++)for(let _=0;_<n[p].dataView.byteLength;_++)l.setInt8(u++,n[p].dataView.getInt8(_));for(let p=0;p<i.data.byteLength;p++)l.setInt8(u++,h.getInt8(p));return i.data=c,n.length}return 0}};var yr=class yr extends Ni{constructor(e,t=4){super(t,ct);d(this,"profile",{width:640,height:480,frameRate:15,bitrate:500});d(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0});d(this,"small");d(this,"isNeedToSetBandwidth");d(this,"muteImage");d(this,"manager");d(this,"_seiCodec",new _a);this.manager=e;let r=()=>{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(k(v({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",r),this.on("publish",r),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!zt||!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,r,o;if(K(e)){if(this.muteImage===e)return;yield(t=this.manager)==null?void 0:t.deleteWatermark("mute"),yield(r=this.manager)==null?void 0:r.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e}),this.muteImage=e,xe(yr.prototype,this,"setMute").call(this,!1)}else yield(o=this.manager)==null?void 0:o.deleteWatermark("mute"),this.muteImage=void 0,xe(yr.prototype,this,"setMute").call(this,e)})}capture({deviceId:e,facingMode:t,useExactDeviceId:r=!0,customSource:o,retryWhenExactFailed:n=!0}){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:r,retryWhenExactFailed:n,customSource:o})}setProfile(e){let t=v({},e),r=t.width>t.height;t.width*t.height<=160*120&&pe&&Ot&&(this.log.warn(`resolution is ${t.width}*${t.height}, fallback to 240*180`),t.width=r?240:180,t.height=r?180:240,t.bitrate=Math.max(t.bitrate,150)),t.width*t.height>1280*720&&Yd&&(t.width=r?1280:720,t.height=r?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(k(v({},this.profile),{width:1920,height:1080})))}applyProfile(){return f(this,null,function*(){var r;if(!this.mediaTrack)return;let e=this.settings;if(!(!(e.height!==this.profile.height||e.width!==this.profile.width||e.frameRate!==this.profile.frameRate)||!this.deviceId)&&(at===16?yield this.recapture(this.deviceId):(yield(r=this.mediaTrack)==null?void 0:r.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth))return this.isNeedToSetBandwidth=!1,this.room.setBandWidth({bandwidth:this.profile.bitrate,type:m.VIDEO,videoType:m.BIG})})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return zt&&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:Sn()&&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,retryWhenExactFailed:!1};e==="user"||e==="environment"?t.facingMode=e:t.deviceId=e,this.mediaTrack.stop(),yield this.capture(t),E.emit(T.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(){be&&!be.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&be.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)}`),he(this.userId,{eventId:2003,param1:7,streamType:2});let t=yield ut();t[0]?this.recapture(t[0].deviceId):be.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){if(!this.manager)return e;let r=t?8:this.mediaType;return this.manager.encodePipeline.reduceRight((o,n)=>n?n({frame:o,mediaType:r}):o,e)}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}play(e,t){return g(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){be.off("videoInputAdded",this.handleCameraAdded,this),be.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return f(this,null,function*(){try{yield xe(yr.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield ut()).find(o=>o.deviceId!==e);if(r)yield xe(yr.prototype,this,"recapture").call(this,r.deviceId);else throw t}})}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info(`setContentHint ${e}`),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}};y([Qe(function(e){this.setContentHint(e.contentHint||"motion")})],yr.prototype,"capture",1);var $e=yr;var em=po();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:em,exposeOrigin:!0,permittedOrigins:["*"]})}catch(s){}var R_=function(s){return f(this,null,function*(){let i=null,e=N_(s);C.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);s.systemAudio&&t.getAudioTracks().length===0&&(as&&kt<74||Be||ae)&&C.warn("Your browser not support capture system audio");let r=t.getVideoTracks()[0];if(r){if(s.frameRate)try{yield r.applyConstraints({frameRate:{min:s.frameRate,ideal:s.frameRate},width:s.width,height:s.height})}catch(o){C.warn(`screen applyConstraints failed: ${o}`)}s.captureElement&&(yield y_(r,s.captureElement))}if(s.audio){let o=b_(s);C.info(`getUserMedia with constraints: ${JSON.stringify(o)}`),i=yield navigator.mediaDevices.getUserMedia(o),t.addTrack(i.getAudioTracks()[0])}return t})};function y_(s,i){return f(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&oe(s.cropTo))try{if(!(((e=s.getCaptureHandle())==null?void 0:e.handle)===em))return;let r=yield CropTarget.fromElement(i);yield s.cropTo(r)}catch(t){C.warn(`cropTo target failed ${t}`)}})}function b_(s){let i={echoCancellation:s.echoCancellation,autoGainControl:s.autoGainControl,noiseSuppression:s.noiseSuppression,sampleRate:s.sampleRate,channelCount:s.channelCount};return g(s.microphoneId)||(i.deviceId=s.microphoneId),{audio:i,video:!1}}function N_(s){let i={preferCurrentTab:s.preferDisplaySurface==="current-tab"||!!s.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Be?{max:s.width}:{ideal:s.width,max:s.width},height:Be?{max:s.height}:{ideal:s.height,max:s.height},frameRate:s.frameRate,displaySurface:s.preferDisplaySurface||"monitor"};if(i.video=e,s.systemAudio){let{echoCancellation:t=!0,noiseSuppression:r=!1,autoGainControl:o=!1}=s;i.audio={echoCancellation:t,noiseSuppression:r,autoGainControl:o,sampleRate:48e3}}return i}var tm=R_;var st=class extends $e{constructor(e){super(e,2);d(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});d(this,"objectFit","contain");d(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(h){return f(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:r,noiseSuppression:o,audioTrack:n,videoTrack:a,captureElement:c,preferDisplaySurface:l}){try{let u;return a||n?(u=new MediaStream,a&&u.addTrack(a),n&&u.addTrack(n)):u=yield tm({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:r,noiseSuppression:o,captureElement:c,preferDisplaySurface:l}),yield this.setInputMediaStreamTrack(u.getVideoTracks()[0]),u}catch(u){throw this.log.error(`getDisplayMedia error observed ${u}`),u instanceof b?u:new b({code:S.INITIALIZE_FAILED,name:u.name,message:u.message})}})}switchDevice(e){return f(this,null,function*(){throw new Error("Method not implemented.")})}};y([Qe(function(e){this.setContentHint(e.contentHint||"detail")})],st.prototype,"capture",1);var si=class extends ht{constructor(i){super(i),this._log.id=`s-${this._log.id}`}};var v_="registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});",Wc;function Uo(s){return f(this,null,function*(){let i=He("dump");Wc||(Wc=bi(i,URL.createObjectURL(new Blob([v_],{type:"application/javascript"})))),yield Wc;let e=new AudioWorkletNode(i,"dumper",{numberOfInputs:s.length,numberOfOutputs:0});return s.forEach((t,r)=>t.connect(e,0,r)),new ReadableStream({start(t){e.port.onmessage=r=>{t.enqueue(r.data)}},cancel(){s.forEach(t=>t.disconnect(e)),e.port.close()}})})}var ga=class extends ra{constructor(e){super();this.room=e;d(this,"_localAudioTrack");d(this,"_localScreenAudioTrack");d(this,"log",C.createLogger({id:"am"}));d(this,"denoiser");d(this,"aec");d(this,"mixNode");d(this,"muteNode");d(this,"mixChangedDebounce");d(this,"encodePipeline",[]);d(this,"decodePipeline",[]);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 h,u;if(!this._localAudioTrack)return;let t=[],r=[];(h=this._localAudioPipline)!=null&&h.source.node&&(t.push(this._localAudioPipline.source.node),r.push("mic")),(u=this._localAudioPipline)!=null&&u.denoiser.node&&(t.push(this._localAudioPipline.denoiser.node),r.push("mic-processed")),this.mixWeight>1&&(t.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),r.push("mix")),this.log.info(`dump audio track ${r}, duration: ${e}`);let o=new AbortController,n=[],a=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),o.abort("timeout")},e*1e3),c=()=>{for(let p=0;p<r.length;p++){let _=URL.createObjectURL(new Blob(n[p])),I=document.createElement("a");I.href=_,I.download=`${r[p]}.pcm`,I.style.display="none",document.body.appendChild(I),I.click(),URL.revokeObjectURL(_),I.remove()}clearTimeout(a),o.abort("download")},l=Uo(t).then(p=>p.pipeTo(new WritableStream({write(_){_.forEach((I,R)=>n[R]=n[R]?n[R].concat(I[0]):[I[0]])}}),o).catch(_=>c));return{then:l.then.bind(l),download:c}}getPCM(e){var n;if(g(WritableStream)){this.log.warn("getPCM failed: browser not support WritableStream");return}if(!((n=this._localAudioPipline)!=null&&n.source.node)){this.log.warn("getPCM failed: no local audio track");return}this.log.warn("getPCM");let t=new Float32Array(1920),r=0,o=new AbortController;return Uo([this._localAudioPipline.source.node]).then(a=>a.pipeTo(new WritableStream({write(c){c[0][0]&&(t.set(c[0][0],r),r+=c[0][0].length,r>=1920&&(r=0,e(t),t=new Float32Array(1920)))}}),o).catch(c=>this.log.warn(`stop getPCM reason:${c}`))),o}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return!g(this._localAudioTrack)}changeInput(e){var t,r,o;if(e instanceof si)return this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();if(e instanceof ht)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),this.aec&&this.mixNode&&this.muteNode&&(e.addAEC(this.aec,this.mixNode,this.muteNode),(t=this.room)==null||t.remotePublishedUserMap.forEach(n=>e.mixPlayTrack(n.remoteAudioTrack.mediaTrack,n.userId)),(r=this._localAudioTrack)!=null&&r.pipeline.mixNode.node&&((o=this._localAudioTrack)!=null&&o.pipeline.aec.node)&&this._localAudioTrack.pipeline.mixNode.node.connect(this._localAudioTrack.pipeline.aec.node,0,1)),e.pipeline.connect(),this.mixOnChange();if(e instanceof Oi)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixPlayTrack(e,t){var r;if(!e){this.log.warn("mixPlayTrack failed. Reason: the play track is null.");return}if(!this._localAudioTrack){this.log.warn("mixPlayTrack failed. Reason: local audio is not started.");return}(r=this._localAudioTrack)==null||r.mixPlayTrack(e,t)}unMixPlayTrack(e){var t;(t=this._localAudioTrack)==null||t.unMixPlayTrack(e)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var e,t;return delete this.mixChangedDebounce,Promise.all([(e=this._localAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(e){e instanceof si?delete this._localScreenAudioTrack:e instanceof ht?delete this._localAudioTrack:e instanceof Oi}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}addAEC(e,t,r){var o,n,a,c;this.aec=e,this.mixNode=t,this.muteNode=r,(o=this._localAudioTrack)==null||o.addAEC(e,t,r),(n=this.room)==null||n.remotePublishedUserMap.forEach(l=>{var h;return(h=this._localAudioTrack)==null?void 0:h.mixPlayTrack(l.remoteAudioTrack.mediaTrack,l.userId)}),(a=this._localAudioTrack)!=null&&a.pipeline.mixNode.node&&((c=this._localAudioTrack)!=null&&c.pipeline.aec.node)&&this._localAudioTrack.pipeline.mixNode.node.connect(this._localAudioTrack.pipeline.aec.node,0,1)}removeDenoiser(e){var t;delete this.denoiser,(t=this._localAudioTrack)==null||t.removeDenoiser(e)}removeAEC(e){var t;delete this.aec,(t=this._localAudioTrack)==null||t.removeAEC(e)}destroy(){this.close()}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};function Ta(s=30,i=2){return J((e,t)=>function(...r){return new Promise((o,n)=>{let a=setTimeout(()=>{let c=new b({code:S.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${s}s`});C.warn(c),i===2?n(c):i===1&&o()},s*1e3);e.apply(this,r).then(o,n).finally(()=>{clearTimeout(a)})})})}var ki=class ki extends Cr{constructor(e,t,r){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:r,room:e});this.room=e;this.user=t;d(this,"tinyId");d(this,"isRemote",!0);d(this,"jitterBufferDelay",0);d(this,"_decodeCheckTimeoutId",-1);this.tinyId=t.tinyId}setMute(e){this.isAvailable&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isAvailable&&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===ki.STATE_SUBSCRIBE}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(e,t){let r=this.kind===m.AUDIO;N[e?"addSuccessEvent":"addFailedEvent"]({key:r?504700:514702}),e||(N.addEnum({key:r?504701:514703,value:mo()}),ee.uploadEvent({log:`stat-decode-failed-${this.kind}-${_r()||Ei()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===m.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:t}))}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isAvailable||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isAvailable} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.updatePlayingState(this.isAvailable)}onTrackMuted(){this.isAvailable&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackMuted()}onTrackUnmuted(){this.isAvailable&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackUnmuted()}onTrackEnded(){this.isAvailable&&(this.isSubscribed||this.isSubscribing)&&this.isPlayCalled&&super.onTrackEnded()}};d(ki,"STATE_SUBSCRIBE","subscribe"),y([Ta(5,1)],ki.prototype,"waitHasMediaTrack",1),y([le(Q.INIT,ki.STATE_SUBSCRIBE,{success(){var t,r;this.log.info("subscribed"),E.emit(T.REMOTE_TRACK_SUBSCRIBED,{track:this}),this.updatePlayingState(!0),!((((r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState)&&(this._decodeCheckTimeoutId=setTimeout(()=>{var n,a;if(!((((a=(n=this.room)==null?void 0:n.networkQuality)==null?void 0:a.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState)&&this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived>0){let c=this.kind===m.AUDIO,l=this.player.isPlaying||(c?this.getAudioLevel()>0:this.stat.framesDecoded>0);this.reportDecodeResult(l)}},5e3),this.player.once(de.ERROR,o=>{o.code===MediaError.MEDIA_ERR_DECODE&&(clearTimeout(this._decodeCheckTimeoutId),this.reportDecodeResult(!1,3))}))},ignoreError:!0}),rt(521716,!1)],ki.prototype,"subscribe",1),y([le(ki.STATE_SUBSCRIBE,Q.INIT,{sync:!0,success(){this.log.info("unsubscribed"),this.updatePlayingState(!1),E.emit(T.REMOTE_TRACK_UNSUBSCRIBED,{track:this}),clearTimeout(this._decodeCheckTimeoutId)}})],ki.prototype,"unsubscribe",1);var Ts=ki;var Oi=class extends Ts{constructor(e,t){super(e,t,1);d(this,"volume",0);d(this,"mediaType",1);d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}get dbVolume(){return Ar.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}decodeFrame(e){if(!this.manager)return e;let t=e;for(let r of this.manager.decodePipeline)if(r&&(t=r({frame:t,track:this}),!t))return;return t}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isAvailable(){return this.user.muteState.audioAvailable}};var O_=[-1,-1,1,-1,-1,1,1,1],k_=[0,0,1,0,0,1,1,1];var ze=class extends Q{constructor(e,t){super();this.context=e;d(this,"name");d(this,"input");d(this,"output");d(this,"texture");d(this,"ctx2d",null);d(this,"fbo");d(this,"width",0);d(this,"height",0);d(this,"x",0);d(this,"y",0);d(this,"program");d(this,"vertexShader");d(this,"fragmentShader");d(this,"totalFrames",0);d(this,"dropFrames",0);d(this,"matchInputSize",!0);d(this,"texCoordBuffer");d(this,"positionBuffer");d(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});d(this,"cost",0);d(this,"_canvas",null);d(this,"_image");d(this,"log");if(this.context.on("disconnect",this.close,this),this.name=t.name,this.log=t.logger,this.matchInputSize=t.matchInputSize!==!1,this.width=t.width||e.width,this.height=t.height||e.height,this._image=t.image,e instanceof Ge){e.ctx&&t.create2d&&(typeof OffscreenCanvas=="function"&&at!==16?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);return}try{let r=e.ctx;this.texCoordBuffer=this.createBuffer(k_),this.positionBuffer=this.createBuffer(O_),t.createTexture!==!1&&(this.texture=r.createTexture(),this.useTexture(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.pixelStorei(r.PACK_ALIGNMENT,1),r.pixelStorei(r.UNPACK_ALIGNMENT,1)),t.useFbo&&(this.fbo=r.createFramebuffer(),this.useBufferFrame(),this.useTexture(),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,this.width,this.height,0,r.RGBA,r.UNSIGNED_BYTE,null),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,this.texture,0)),t.useDefaultProgram?this.program=e.defaultProgam:(t.vertexShaderSource||t.fragmentShaderSource)&&(this.vertexShader=t.vertexShaderSource?e.createShader(r.VERTEX_SHADER,t.vertexShaderSource):e.defaultVShader,this.fragmentShader=t.fragmentShaderSource?e.createShader(r.FRAGMENT_SHADER,t.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(r){this.context.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${r.message||r}`}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,r=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),r}connect(e,...t){return e.addInput(this,...t),this.output=e,e}addInput(e,...t){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();if(this.context instanceof ke&&this.render(e)||this.context instanceof Ge&&this.render2d(e))this.totalFrames++;else return!1;return this.cost=Date.now()-t,!0}render2d(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?this.draw2d(this.input.image,0,0,this.width,this.height):!1}update(e=0){var t;(t=this.output)==null||t.update(e)}disconnect(...e){var t;(t=this.output)==null||t.removeInput(this,...e),delete this.output}removeInput(e,...t){delete this.input}close(){var e,t;if(this.context.off("disconnect",this.close,this),(e=this.output)==null||e.removeInput(this),delete this.output,(t=this.input)==null||t.disconnect(),this.context instanceof ke){let r=this.context.ctx;r.deleteBuffer(this.texCoordBuffer),r.deleteBuffer(this.positionBuffer),this.fbo&&r.deleteFramebuffer(this.fbo),this.texture&&r.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&r.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&r.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&r.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var e;this.useTextures((e=this.input)==null?void 0:e.texture)}useTextures(...e){let t=this.context.ctx;e.forEach((r,o)=>{r&&(t.activeTexture(t.TEXTURE0+o),t.bindTexture(t.TEXTURE_2D,r))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let t=this.context.ctx,r=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,r),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW),r}setTexBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}setPosBuffer(e){let t=this.context.ctx;t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,new Float32Array(e),t.STATIC_DRAW)}changeBufferData(e,t){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,e),r.bufferData(r.ARRAY_BUFFER,new Float32Array(t),r.STATIC_DRAW)}setAttributes(...e){let t=this.context.ctx;e.forEach((r,o)=>{t.enableVertexAttribArray(o),t.bindBuffer(t.ARRAY_BUFFER,r),t.vertexAttribPointer(o,2,t.FLOAT,!1,0,0)})}getVertexPoint(e,t){return[e/this.width*2-1,t/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,t){if(!(this.width===e&&this.height===t)){if(this.width=e,this.height=t,this._canvas&&(this._canvas.width=e,this._canvas.height=t),this.texture&&this.fbo){this.useTexture();let r=this.context.ctx;r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e,t,0,r.RGBA,r.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,t)}}draw(e,t){this.setAttributes(e||this.positionBuffer,t||this.texCoordBuffer);let r=this.context.ctx;r.drawArrays(r.TRIANGLE_STRIP,0,4)}draw2d(e,t,r,o,n){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,t,r):(this.ctx2d.drawImage(e,t,r,o,n),typeof VideoFrame!="undefined"&&e instanceof VideoFrame&&e.close()),!0):!1}getInfo(){var u;let{totalFrames:e,x:t,y:r,width:o,height:n,name:a,cost:c}=this,l=Date.now(),h=(e-this.lastInfo.totalFrames)/((l-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:o,height:n,timestamp:l,fps:h,name:a,cost:c},v({parent:(u=this.input)==null?void 0:u.getInfo()},this.lastInfo)}createTexture(e){let t=this.context.ctx,r=t.createTexture();return this.useTextures(r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),r}};y([le(Q.INIT,"connected",{sync:!0})],ze.prototype,"connect",1),y([le("connected",Q.INIT,{ignoreError:!0,sync:!0})],ze.prototype,"disconnect",1),y([le([],"closed",{sync:!0})],ze.prototype,"close",1);var Dl={};ci(Dl,{Events:()=>fe,Inspect:()=>Tt,LastSink:()=>br,Sink:()=>F,Subscribe:()=>Nr,TimeoutError:()=>Vo,audit:()=>pg,bindCallback:()=>Z_,bindNodeCallback:()=>eg,buffer:()=>$_,bufferCount:()=>H_,bufferTime:()=>Lg,call:()=>rm,catchError:()=>Fo,combineLatest:()=>om,concat:()=>w_,concatMap:()=>yg,concatMapTo:()=>bg,count:()=>rg,create:()=>Z,debounce:()=>fg,debounceTime:()=>_g,defer:()=>nm,delay:()=>Pg,deliver:()=>$,dispose:()=>Ea,elementAt:()=>gg,empty:()=>Dr,every:()=>Ag,exhaustMap:()=>Dg,exhaustMapTo:()=>Og,filter:()=>Ra,find:()=>Tg,findIndex:()=>Eg,first:()=>Sg,fromAnimationFrame:()=>Y_,fromArray:()=>J_,fromEvent:()=>Ie,fromEventPattern:()=>q_,fromFetch:()=>j_,fromIterable:()=>X_,fromPromise:()=>cm,fromReadableStream:()=>z_,fromReader:()=>Q_,groupBy:()=>kg,identity:()=>M_,ignoreElements:()=>ag,iif:()=>V_,inspect:()=>sm,interval:()=>zc,last:()=>Ig,map:()=>yl,mapTo:()=>Rg,max:()=>sg,merge:()=>P_,mergeMap:()=>Ng,mergeMapTo:()=>vg,min:()=>og,never:()=>tg,nothing:()=>se,of:()=>W_,pairwise:()=>Cg,pipe:()=>_e,race:()=>x_,range:()=>K_,reduce:()=>Kc,retry:()=>Vg,scan:()=>Rl,share:()=>Mi,shareReplay:()=>U_,skip:()=>cg,skipUntil:()=>lg,skipWhile:()=>ya,startWith:()=>vr,subject:()=>ot,subscribe:()=>Ne,sum:()=>ng,switchMap:()=>tr,switchMapTo:()=>Bo,take:()=>Li,takeLast:()=>dg,takeUntil:()=>Ue,takeWhile:()=>lm,tap:()=>vl,throttle:()=>hg,throwError:()=>ig,timeInterval:()=>Mg,timeout:()=>Ug,timer:()=>Yc,toPromise:()=>xg,toReadableStream:()=>wg,withLatestFrom:()=>F_,zip:()=>B_});function se(...s){}var rm=s=>s(),M_=s=>s;function Ea(){this.dispose()}var sm=()=>typeof __FASTRX_DEVTOOLS__!="undefined",L_=1,Tt=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new qc(i,this,this.streamId++);return fe.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},br=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=se,this.error=se,this.next=se,this.dispose=se,this.subscribe=se,this.doDefer()}subscribe(i){return i instanceof Tt?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(rm),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 br{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)}},Nr=class extends br{constructor(i,e=se,t=se,r=se){if(super(),this._next=e,this._error=t,this._complete=r,this.then=se,i instanceof Tt){let o={toString:()=>"subscribe",id:0,source:i};this.defer(()=>{fe.defer(o,0)}),fe.create(o),fe.pipe(o),this.sourceId=o.id,this.subscribe(i),fe.subscribe({id:o.id,end:!0}),e==se?this._next=n=>fe.next(o,0,n):this.next=n=>{fe.next(o,0,n),e(n)},r==se?this._complete=()=>fe.complete(o,0):this.complete=()=>{this.dispose(),fe.complete(o,0),r()},t==se?this._error=n=>fe.complete(o,0,n):this.error=n=>{this.dispose(),fe.complete(o,0,n),t()}}else this.subscribe(i)}next(i){this._next(i)}complete(){this.dispose(),this._complete()}error(i){this.dispose(),this._error(i)}};function _e(s,...i){return i.reduce((e,t)=>t(e),s)}function Z(s,i,e){if(sm()){let t=Object.defineProperties(Object.setPrototypeOf(s,Tt.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}});fe.create(t);for(let r=0;r<e.length;r++){let o=e[r];typeof o=="function"&&o instanceof Tt&&fe.addSource(t,o)}return t}return s}function $(s,i){return function(...e){return t=>{if(t instanceof Tt){let r=Z(o=>{let n=new s(o,...e);n.sourceId=r.id,n.subscribe(t)},i,arguments);return r.source=t,fe.pipe(r),r}else return r=>t(new s(r,...e))}}}function er(s,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:s,payload:i}})}var qc=class extends F{constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{fe.defer(this.source,this.id)})}next(i){fe.next(this.source,this.id,i),this.sink.next(i)}complete(){fe.complete(this.source,this.id),this.sink.complete()}error(i){fe.complete(this.source,this.id,i),this.sink.error(i)}},fe={addSource(s,i){er("addSource",{id:s.id,name:s.toString(),source:{id:i.id,name:i.toString()}})},next(s,i,e){er("next",{id:s.id,streamId:i,data:e&&e.toString()})},subscribe({id:s,end:i},e){er("subscribe",{id:s,end:i,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(s,i,e){er("complete",{id:s.id,streamId:i,err:e?e.toString():null})},defer(s,i){er("defer",{id:s.id,streamId:i})},pipe(s){er("pipe",{name:s.toString(),id:s.id,source:{id:s.source.id,name:s.source.toString()}})},update(s){er("update",{id:s.id,name:s.toString()})},create(s){s.id||(s.id=L_++),er("create",{name:s.toString(),id:s.id})}},Vo=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var Sa=class extends br{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 Mi(){return s=>{let i=new Sa(s);if(s instanceof Tt){let e=Z(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=s,fe.pipe(e),e}return Z(i.add.bind(i),"share",arguments)}}function P_(...s){return Z(i=>{let e=new F(i),t=s.length;e.complete=()=>{--t===0&&i.complete()},s.forEach(e.bindSubscribe)},"merge",arguments)}function x_(...s){return Z(i=>{let e=new Map;s.forEach(t=>{let r=new F(i);e.set(t,r),r.complete=()=>{e.delete(t),e.size===0?i.complete():r.dispose()},r.next=o=>{e.delete(t),e.forEach(n=>n.dispose()),r.resetNext(),r.resetComplete(),r.next(o)}}),s.forEach(t=>e.get(t).subscribe(t))},"race",arguments)}function w_(...s){return Z(i=>{let e=0,t=s.length,r=new F(i);r.complete=()=>{e<t&&!r.disposed?(r.doDefer(),r.subscribe(s[e++])):i.complete()},r.complete()},"concat",arguments)}function U_(s){return i=>{let e=new Sa(i),t=[];return e.next=function(r){t.push(r),t.length>s&&t.shift(),this.sinks.forEach(o=>o.next(r))},Z(r=>{r.defer(()=>e.remove(r)),t.forEach(o=>r.next(o)),e.add(r)},"shareReplay",arguments)}}function V_(s,i,e){return Z(t=>s()?i(t):e(t),"iif",arguments)}function om(...s){return Z(i=>{let e=s.length,t=e,r=e,o=new Array(e),n=()=>{--r===0&&i.complete()},a=(c,l)=>{let h=new F(i);h.next=u=>{--t===0?(h.next=p=>{o[l]=p,i.next(o)},h.next(u)):o[l]=u},h.complete=n,h.subscribe(c)};s.forEach(a)},"combineLatest",arguments)}function B_(...s){return Z(i=>{let e=s.length,t=e,r=new Array(e),o=()=>{--t===0&&i.complete()},n=(a,c)=>{let l=new F(i),h=[];r[c]=h,l.next=u=>{h.push(u),r.every(p=>p.length)&&i.next(r.map(p=>p.shift()))},l.complete=o,l.subscribe(a)};s.forEach(n)},"zip",arguments)}function vr(...s){return i=>Z((e,t=0,r=s.length)=>{for(;t<r&&!e.disposed;)e.next(s[t++]);e.disposed||e.subscribe(i)},"startWith",arguments)}var jc=class extends F{constructor(i,...e){super(i);let t=new F(this.sink);t.next=r=>this.buffer=r,t.complete=se,t.subscribe(om(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},F_=$(jc,"withLatestFrom"),Xc=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()}},H_=$(Xc,"bufferCount"),Qc=class extends F{constructor(i,e){super(i),this.buffer=[];let t=new F(i);t.next=r=>{i.next(this.buffer),this.buffer=[]},t.complete=se,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},$_=$(Qc,"buffer");var G_=function(s,i,e,t){function r(o){return o instanceof e?o:new e(function(n){n(o)})}return new(e||(e=Promise))(function(o,n){function a(h){try{l(t.next(h))}catch(u){n(u)}}function c(h){try{l(t.throw(h))}catch(u){n(u)}}function l(h){h.done?o(h.value):r(h.value).then(a,c)}l((t=t.apply(s,i||[])).next())})};function ot(s){let i=arguments,e=Mi()(Z(t=>{e.next=r=>t.next(r),e.complete=()=>t.complete(),e.error=r=>t.error(r),s&&t.subscribe(s)},"subject",i));return e.next=se,e.complete=se,e.error=se,e}function nm(s){return Z(i=>i.subscribe(s()),"defer",arguments)}var am=s=>i=>{setTimeout(()=>s(i))},dm=s=>am(i=>{for(let e=0;!i.disposed&&e<s.length;e++)i.next(s[e]);i.complete()});function W_(...s){return Z(dm(s),"of",arguments)}function J_(s){return Z(dm(s),"fromArray",arguments)}function zc(s){return Z(i=>{let e=0,t=setInterval(()=>i.next(e++),s);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}function Yc(s,i){return Z(e=>{let t=0,r=setTimeout(()=>{if(e.removeDefer(o),e.next(t++),i){let n=setInterval(()=>e.next(t++),i);e.defer(()=>{clearInterval(n)})}else e.complete()},s),o=()=>{clearTimeout(r)};e.defer(o)},"timer",arguments)}function Ia(s,i){return e=>{let t=r=>e.next(r);e.defer(()=>i(t)),s(t)}}function q_(s,i){return Z(Ia(s,i),"fromEventPattern",arguments)}function Ie(s,i){if("on"in s&&"off"in s)return Z(Ia(e=>s.on(i,e),e=>s.off(i,e)),"fromEvent",arguments);if("addListener"in s&&"removeListener"in s)return Z(Ia(e=>s.addListener(i,e),e=>s.removeListener(i,e)),"fromEvent",arguments);if("addEventListener"in s)return Z(Ia(e=>s.addEventListener(i,e),e=>s.removeEventListener(i,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function cm(s){return Z(i=>{s.then(i.next.bind(i),i.error.bind(i))},"fromPromise",arguments)}function j_(s,i){return Z(nm(()=>cm(fetch(s,i))),"fromFetch",arguments)}function X_(s){return Z(am(i=>{try{for(let e of s){if(i.disposed)return;i.next(e)}i.complete()}catch(e){i.error(e)}}),"fromIterable",arguments)}function Q_(s){let i=e=>G_(this,void 0,void 0,function*(){if(e.disposed)return;let{done:t,value:r}=yield s.read();if(t){e.complete();return}else e.next(r),i(e)});return Z(e=>{i(e)},"fromReader",arguments)}function z_(s){return Z(i=>{let e=new AbortController,t=e.signal;i.defer(()=>e.abort("cancelled")),s.pipeTo(new WritableStream({write(r){i.next(r)},close(){i.complete()},abort(r){i.error(r)}}),{signal:t}).then(()=>i.complete(),r=>i.error(r))},"fromReadableStream",arguments)}function Y_(){return Z(s=>{let i=requestAnimationFrame(function e(t){s.disposed||(s.next(t),i=requestAnimationFrame(e))});s.defer(()=>cancelAnimationFrame(i))},"fromAnimationFrame",arguments)}function K_(s,i){return Z((e,t=s,r=i+s)=>{for(;t<r&&!e.disposed;)e.next(t++);return e.complete(),"range"},"range",arguments)}function Z_(s,i,...e){return Z(t=>{let r=e.concat(o=>(t.next(o),t.complete()));s.apply(i,r)},"bindCallback",arguments)}function eg(s,i,...e){return Z(t=>{let r=e.concat((o,n)=>o?t.error(o):(t.next(n),t.complete()));s.apply(i,r)},"bindNodeCallback",arguments)}function tg(){return Z(()=>{},"never",arguments)}function ig(s){return Z(i=>i.error(s),"throwError",arguments)}function Dr(){return Z(s=>s.complete(),"empty",arguments)}var Or=class extends F{constructor(i,e,t){super(i),this.f=e;let r=()=>{this.sink.next(this.acc),this.sink.complete()};typeof t=="undefined"?this.next=o=>{this.acc=o,this.complete=r,this.resetNext()}:(this.acc=t,this.complete=r)}next(i){this.acc=this.f(this.acc,i)}},Kc=$(Or,"reduce"),rg=s=>$(Or,"count")((i,e)=>s(e)?i+1:i,0),sg=()=>$(Or,"max")(Math.max),og=()=>$(Or,"min")(Math.min),ng=()=>$(Or,"sum")((s,i)=>s+i,0);var Zc=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)}},Ra=$(Zc,"filter"),el=class extends F{next(i){}},ag=$(el,"ignoreElements"),tl=class extends F{constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&this.complete()}},Li=$(tl,"take"),il=class extends F{constructor(i,e){super(i);let t=new F(i);t.next=()=>i.complete(),t.complete=Ea,t.subscribe(e)}},Ue=$(il,"takeUntil"),rl=class extends F{constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):this.complete()}},lm=$(rl,"takeWhile"),dg=s=>Kc((i,e)=>(i.push(e),i.length>s&&i.shift(),i),[]),sl=class extends F{constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},cg=$(sl,"skip"),ol=class extends F{constructor(i,e){super(i),i.next=se;let t=new F(i);t.next=()=>{t.dispose(),i.resetNext()},t.complete=Ea,t.subscribe(e)}},lg=$(ol,"skipUntil"),nl=class extends F{constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},ya=$(nl,"skipWhile"),ug={leading:!0,trailing:!1},al=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)}},Aa=class extends F{constructor(i,e,t=ug){super(i),this.durationSelector=e,this.config=t,this._throttle=new al(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=se,this._throttle.complete(),super.complete()}},hg=$(Aa,"throttle"),mg={leading:!1,trailing:!0},pg=s=>$(Aa,"audit")(s,mg),dl=class extends F{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Ca=class extends F{constructor(i,e){super(i),this.durationSelector=e,this._debounce=new dl(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()}},fg=$(Ca,"debounce"),_g=s=>$(Ca,"debounceTime")(i=>Yc(s)),cl=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()}},gg=$(cl,"elementAt"),Tg=s=>i=>Li(1)(ya(e=>!s(e))(i)),ll=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}},Eg=$(ll,"findIndex"),ul=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()}},Sg=$(ul,"first"),hl=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()}},Ig=$(hl,"last"),ml=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()}},Ag=$(ml,"every");var pl=class extends F{constructor(i,e,t){super(i),this.f=e,typeof t=="undefined"?this.next=r=>{this.acc=r,this.resetNext(),this.sink.next(this.acc)}:this.acc=t}next(i){this.sink.next(this.acc=this.f(this.acc,i))}},Rl=$(pl,"scan"),fl=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}},Cg=$(fl,"pairwise"),ba=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))}},yl=$(ba,"map"),Rg=s=>$(ba,"mapTo")(i=>s),Es=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()}},Ss=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()}},Na=class extends Es{},va=class extends Ss{next(i){this.subInner(i,Na),this.next=e=>{this.currentSink.dispose(),this.subInner(e,Na)}}},tr=$(va,"switchMap");function Ma(s){return(i,e)=>s(()=>i,e)}var Bo=Ma($(va,"switchMapTo")),_l=class extends Es{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},Da=class extends Ss{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(),_l),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},yg=$(Da,"concatMap"),bg=Ma($(Da,"concatMapTo")),gl=class extends Es{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Oa=class extends Ss{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,gl),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},Ng=$(Oa,"mergeMap"),vg=Ma($(Oa,"mergeMapTo")),Tl=class extends Es{dispose(){this.context.resetNext(),super.dispose()}},ka=class extends Ss{next(i){this.next=se,this.subInner(i,Tl)}},Dg=$(ka,"exhaustMap"),Og=Ma($(ka,"exhaustMapTo")),El=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=ot(),t.key=e,this.groups.set(e,t),super.next(t)),t.next(i)}complete(){this.groups.forEach(i=>i.complete()),super.complete()}error(i){this.groups.forEach(e=>e.error(i)),super.error(i)}},kg=$(El,"groupBy"),Sl=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}},Mg=$(Sl,"timeInterval"),Il=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()}},Lg=$(Il,"bufferTime"),Al=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:r}=e;super.next(r),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(t))}},i)}next(i){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:i})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},Pg=$(Al,"delay"),Cl=class extends F{constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},Fo=$(Cl,"catchError");var xg=()=>s=>new Promise((i,e)=>{let t;new Nr(s,r=>t=r,e,()=>i(t))}),wg=()=>s=>{let i;return new ReadableStream({start(e){i=new Nr(s,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){i.dispose()}})},Ne=(s=se,i=se,e=se)=>t=>new Nr(t,s,i,e),bl=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)}))}},vl=$(bl,"tap"),Nl=class extends F{constructor(i,e){super(i),this.timeout=e,this.id=setTimeout(()=>this.error(new Vo(this.timeout)),this.timeout)}next(i){super.next(i),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},Ug=$(Nl,"timeout"),Vg=(s=1/0)=>i=>{if(i instanceof Tt){let e=Z(t=>{let r=s,o=new F(t);o.error=n=>{r-- >0?o.subscribe(i):t.error(n)},o.sourceId=e.id,o.subscribe(i)},"retry",[s]);return e.source=i,fe.pipe(e),e}else return e=>{let t=s,r=new F(e);r.error=o=>{t-- >0?i(r):e.error(o)},i(r)}};var Bg=_e(zc(250),yl(()=>performance.now()),Mi());var um=s=>i=>{let e=performance.now();_e(Bg,ya(t=>t-e<s),Li(1))(i)};var Hg=[0,1,1,1,0,0,1,0],kr=class extends ze{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));d(this,"_intervalId",0);d(this,"_sequence",0);d(this,"checkGLError",!1);d(this,"checkVisibilityChange");e instanceof Ge?this.ctx2d=e.ctx||null:e.available&&(t!=null&&t.mirrorUpAndDown)&&this.setTexBuffer(Hg)}start(e){this.log.info(`${this.name} start render ${e} fps`),re.clearTask(this._intervalId),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 ke){let r=this.context.ctx.getError();r&&this.context.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${r}`}))}},{fps:this.context.frameRate})}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}addInput(e,...t){super.addInput(e,...t),this.start(this.context.frameRate)}update(e=0){if(this._intervalId&&(re.clearTask(this._intervalId),this._intervalId=0,e===1)){this.log.info(`${this.name} use requestVideoFrameCallback`);let t=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",t))};document.addEventListener("visibilitychange",t)}this.requestFrame(this._sequence++)}removeInput(e){super.removeInput(e),re.clearTask(this._intervalId)}resize(e,t){super.resize(e,t),this.context.setSize(e,t)}close(){super.close(),re.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},Is=class extends kr{constructor(e,t){super(e,t);d(this,"_videoTrack");d(this,"_muteOb");d(this,"_closedOb",Ie(this,"closed"));d(this,"_subscription");d(this,"_canvasContainer");Number(qi)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=Ie(this._videoTrack,"mute"),_e(Ie(this._videoTrack,"ended"),Ue(this._closedOb),Ne(()=>{this.context.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=_e(this._muteOb,Ue(this._closedOb),Bo(um(5e3)),Ne(()=>{var e;(e=this._videoTrack)!=null&&e.muted&&this.context.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var e;(e=this._subscription)==null||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info(`${this.name} put canvas to body`),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,t;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack,(t=this._canvasContainer)==null||t.remove()}},La=class extends Is{render(i){var e;return!!((e=this.input)!=null&&e.requestFrame(i))}};var Pa=class extends Is{constructor(e,t,r){super(e,{name:"smallDestination",logger:r});this.resolution=t}resize(e,t){let r,o=e*t,n=this.resolution.width*this.resolution.height;this.log.info(`big res: ${e}*${t} small res: ${this.resolution.width}*${this.resolution.height} `),o>n?r=o/n:(this.log.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${t} small: ${this.resolution.width} * ${this.resolution.height}`),r=o/(160*120)),super.resize(e/Math.sqrt(r),t/Math.sqrt(r))}};var Ho=class extends ze{constructor(e,t){super(e,v({name:"imageSource"},t));d(this,"_lastImage");d(this,"_totalFrames",0);d(this,"_autoResize",!1);d(this,"_canvasRendered");d(this,"_videoCallbackId",0);this._autoResize=(t==null?void 0:t.autoResize)!==!1,at===16&&(this._canvasRendered=ot(),_e(this._canvasRendered,vr(this._image),tr(r=>r instanceof HTMLCanvasElement?Ie(r,"rendered"):Dr()),Ue(Ie(this,"closed")),Ne(()=>{this.update()})))}tryVideoFrameCallback(e){this._videoCallbackId&&e.cancelVideoFrameCallback(this._videoCallbackId),Ir()&&!document.hidden&&(this._videoCallbackId=e.requestVideoFrameCallback((t,r)=>{document.hidden||(this._totalFrames=r.presentedFrames,this.update(1))}))}_render(e,t){var a;let{width:r,height:o}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(n),{videoWidth:r,videoHeight:o}=n,!r||!o)return!1;n.width=r,n.height=o}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if({width:r,height:o}=n,n!==this._lastImage)this._lastImage=n;else if(r===this.width&&o===this.height)return!1}else n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas?({width:r,height:o}=n,this._lastImage=n):typeof VideoFrame!="undefined"&&n instanceof VideoFrame&&({displayWidth:r,displayHeight:o}=n,(a=this._lastImage)==null||a.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===r&&this.height===o&&this.totalFrames){if(t){this.useTexture();let c=this.context.ctx;c.texSubImage2D(c.TEXTURE_2D,0,0,0,c.RGBA,c.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();let c=this.context.ctx;c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,n)}this.resize(r,o)}return!0}get image(){return this._image}set image(e){var t;(t=this._canvasRendered)==null||t.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},$o=class extends Ho{constructor(e,t,r){super(e,r);this._player=t;this.name="videoPlayerSource",_e(Ie(this._player,de.PLAYER_STATE_CHANGED),Ue(Ie(this,"closed")),Ra(({state:o})=>o==="PLAYING"),Ne(()=>{this.tryVideoFrameCallback(this._player.element)}))}get image(){return this._player.element}},Pi=class extends $o{constructor(i,e,t){super(i,new ct({id:t.name,track:e,muted:!0,container:null,objectFit:"contain",log:t.logger}),t),this.name="videoTrackSource",this._player.play()}replaceTrack(i){this._player.setTrack(i),this._player.play()}close(){super.close(),this._player.stop()}};var Gg=`
|
|
34
34
|
// \u9876\u70B9\u7740\u8272\u5668
|
|
35
35
|
attribute vec4 a_position;
|
|
36
36
|
attribute vec2 a_texCoord;
|
|
@@ -48,16 +48,16 @@ uniform sampler2D u_texture;
|
|
|
48
48
|
|
|
49
49
|
void main() {
|
|
50
50
|
gl_FragColor = texture2D(u_texture, v_texCoord);
|
|
51
|
-
} `;var Mr=class extends Q{constructor(e){super();d(this,"frameRate");d(this,"_canvas");d(this,"log");d(this,"hasAlpha",!1);d(this,"name");d(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}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 Pi(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new Is(this,e)}createVideoImageSource(e,t){return new Ho(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new $o(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};d(Mr,"_ids",0);var Jg={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},As=class As extends Mr{constructor(){super(...arguments);d(this,"defaultProgam");d(this,"defaultVShader");d(this,"defaultFShader");d(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Mr._ids++}`),this.ctx=this._canvas.getContext("webgl2",Jg),!this.ctx)throw new b({code:S.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,Gg),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,Wg),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))}),this.log.info("video context created use webgl")}destroy(e){let t="";return e&&(t=e.message,this.error=e,N.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info(`video context destroy${t}`?`: ${t}`:""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;(t=this.ctx)==null||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let r=this.ctx,o=r.createShader(e);return r.shaderSource(o,t),r.compileShader(o),o}createProgram(e,t){let r=this.ctx,o=r.createProgram();return r.attachShader(o,e),r.attachShader(o,t),r.linkProgram(o),r.getProgramParameter(o,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(o)),o}};d(As,"UNAVAILABLE","unavailable"),y([le(Q.INIT,"created",{sync:!0,fail(e){N.addFailedEvent({key:512700,error:e.cause||e})},success(){N.addSuccessEvent({key:512700})}})],As.prototype,"create",1),y([le("created",Q.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(As.UNAVAILABLE,e),this.removeAllListeners()}})],As.prototype,"destroy",1);var ke=As,Ge=class extends Mr{constructor(){super(...arguments);d(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Mr._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new b({code:S.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this.log.info("video context created use 2d")}destroy(e){let t="";e&&(t=e.message,this.error=e,N.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info(`video context destroy ${t?`: ${t}`:""}`),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),N.addSuccessEvent({key:512703})}};y([le(Q.INIT,"created",{sync:!0,fail(e){N.addFailedEvent({key:512701,error:e.cause||e})},success(){N.addSuccessEvent({key:512701})}})],Ge.prototype,"create",1),y([le("created",Q.INIT,{ignoreError:!0,sync:!0})],Ge.prototype,"destroy",1);function qg(s){return[15,30,45,60].reduce((e,t)=>Math.abs(t-s)<Math.abs(e-s)?t:e)}var oi=class extends Ts{constructor(e,t,r=4){super(e,t,r);d(this,"mediaType",4);d(this,"source");d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager,this.once("first-video-frame",o=>{this.room.emit("first-video-frame",o)})}play(e,t){return(me(t==null?void 0:t.canvasRender)?t.canvasRender:at===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat()})}useCanvasPlayer(){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let e=new Ge({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=new kr(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(t),this.player.setCanvas(e._canvas),Ir()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=qg(t);if(!Y(t)||t<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${t} `);return}if(r===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${r} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${t}, closest: ${r}, current: ${e.frameRate}`),e.frameRate=r}get decodeFPS(){var n;let{msg_video_status:e}=((n=this.room.heartbeatReport)==null?void 0:n.msg_down_stream_info.find(a=>a.msg_user_info.str_identifier===this.userId))||{},t=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let r=e.find(a=>a.uint32_video_stream_type===t);return(r==null?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&(e=t({frame:e,track:this}),!e))return;return e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get isAvailable(){return this.user.muteState.videoAvailable}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},Cs=class extends oi{constructor(e,t){super(e,t,2);d(this,"mediaType",2);d(this,"objectFit","contain")}get isAvailable(){return this.user.muteState.hasAuxiliary}};var Rs=new Map;E.on(T.JOIN_SUCCESS,({room:s})=>{he(s.userId,{eventId:32788})});E.on(T.LEAVE_START,({room:s})=>{he(s.userId,{eventId:32789})});E.on(T.LOCAL_TRACK_PUBLISHED,({track:s})=>{if(s.room){let i=32769;s.mediaType===4?i=32768:s.mediaType===2&&(i=32805),he(s.room.userId,{eventId:i})}});E.on(T.LOCAL_TRACK_UNPUBLISHED,({track:s})=>{if(s.room){let i=32771;s.mediaType===4?i=32770:s.mediaType===2&&(i=32806),he(s.room.userId,{eventId:i})}});E.on(T.TRACK_MUTED,({track:s})=>{s.room&&(s.kind===m.AUDIO?he(s.room.userId,{eventId:s.isRemote?32785:32772,remoteUserId:s.isRemote?s.userId:void 0}):he(s.room.userId,{eventId:s.isRemote?32784:32773,remoteUserId:s.isRemote?s.userId:void 0}))});E.on(T.TRACK_UNMUTED,({track:s})=>{s.room&&(s.kind===m.AUDIO?he(s.room.userId,{eventId:s.isRemote?32787:32774,remoteUserId:s.isRemote?s.userId:void 0}):he(s.room.userId,{eventId:s.isRemote?32786:32775,remoteUserId:s.isRemote?s.userId:void 0}))});E.on(T.REMOTE_TRACK_SUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&he(s.room.userId,{eventId:32777,remoteUserId:s.userId}),s.mediaType===4&&he(s.room.userId,{eventId:32776,remoteUserId:s.userId}),s.mediaType===8&&he(s.room.userId,{eventId:32803,remoteUserId:s.userId}))});E.on(T.REMOTE_TRACK_UNSUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&he(s.room.userId,{eventId:32779,remoteUserId:s.userId}),s.mediaType===4&&he(s.room.userId,{eventId:32778,remoteUserId:s.userId}),s.mediaType===8&&he(s.room.userId,{eventId:32804,remoteUserId:s.userId}))});E.on(T.SWITCH_DEVICE_SUCCESS,({track:s})=>{s.room&&he(s.room.userId,{eventId:s.kind===m.VIDEO?32780:32781})});E.on(T.LOCAL_TRACK_REPLACED,({track:s})=>{s.room&&he(s.room.userId,{eventId:s.kind===m.VIDEO?32782:32783})});E.on(T.SIGNAL_CONNECTION_STATE_CHANGED,({room:s,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&&he(s.userId,{eventId:t})});E.on(T.PEER_CONNECTION_STATE_CHANGED,({room:s,prevState:i,state:e,remoteUserId:t})=>{let r=!!t,o;switch(e){case"CONNECTED":i==="RECONNECTING"?o=r?32801:32798:o=r?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(o=r?32802:32799);break;case"RECONNECTING":o=r?32800:32797;break}o&&he(s.userId,{eventId:o,remoteUserId:t})});E.on(T.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:s,userId:i,remoteUserId:e,codec:t,isHWCodec:r,prevImplementation:o,streamType:n})=>{let a=r?1:0;o||(a=r?3:2);let c=t==="h264"?0:2,l={eventId:4004,param1:a,param2:c,streamType:n||2};e&&(l.remoteUserId=e,l.eventId=4005),he(i,l),N.addEnum({key:e?514701:513701,value:a}),N.addEnum({key:e?514700:513700,value:c})});E.on(T.LOCAL_TRACK_RECAPTURE,({track:s,error:i})=>{if(s.userId){let e={eventId:2003,param1:0};s.kind===m.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=s.streamType==="auxiliary"?7:2,i&&(e.param1=8)),he(s.userId,e)}});function he(s,i){let e=k(v({},i),{timestamp:Fs()});Rs.has(s)?Rs.get(s).push(e):Rs.set(s,[e])}function hm(s){if(Rs.has(s)){let i=Rs.get(s).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 Rs.delete(s),i}return[]}var mm=Pe(je(),1);var xa=class extends mm.EventEmitter{constructor(e,t,r="userId"){super();this.mySelfId=e;this._log=t;this.key=r;d(this,"userMap",new Map);d(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(e=>e.isRobot)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:r,tinyId:o,role:n}=e;if(this.userMap.has(t))return;let a={userId:r,tinyId:o,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let r=this.userMap.get(e);if(!r)return;let o=`peer leave [${e}]`;g(t)||(o+=`:${kd[t]}`),this._log.info(o);let n=this.remotePublishedUserMap.get(e);if(n){let a=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",r.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(r=>r[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){this.remotePublishedUserMap.has(e)&&this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let r=t[this.key];if(e.findIndex(o=>o[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let o=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:o,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var h;let r=t[this.key];if(r===this.mySelfId)return;let{flag:o,userId:n,tinyId:a}=t,c=pi(o,n),l=(h=this.remotePublishedUserMap.get(r))==null?void 0:h.muteState;if(l){let u=this.remotePublishedUserMap.get(r);u&&u.flag!==o&&(u.flag=o,this._log.info(`remote publish updated: ${JSON.stringify(u.muteState)}`),this.emit("6",{prevMuteState:l,muteState:c,flag:o}))}else this._log.info(`remote publish. state: ${JSON.stringify(c)}`),this.addUser({userId:n,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:pi(0,n),muteState:c,flag:o})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function Ol({timesInSecond:s,maxSizeInSecond:i,getSize:e}){return J((t,r)=>{let o=new WeakMap;return E.on(T.ROOM_DESTROY,({room:n})=>o.delete(n)),function(...n){let a=o.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=s||a.totalSizeInSecond>i))throw new b({code:S.INVALID_OPERATION,message:V({key:w.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=s,isSize:a.totalSizeInSecond>i,name:r,timesInSecond:s,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var jg="2025-04-08 19:42:05",pm=!0,fm=function(){var s;pm&&(pm=!1,C.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Ft}/en/index.html`),console.info(`* Changelog: ${Ft}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),C.info("TRTC Web SDK Version:",Re),Mt||C.debug("Build Time:",jg),C.info("UA:",navigator.userAgent),C.info(`URL: ${location.href}${((s=self.frameElement)==null?void 0:s.tagName)==="IFRAME"?" in iframe":""}`),ho().then(i=>{i&&C.info(bt)}))};var Et={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"};var U={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},St=(A=>(A[A.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",A[A.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",A[A.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",A[A.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",A[A.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",A[A.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",A[A.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",A[A.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",A[A.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",A[A.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",A[A.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",A[A.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",A[A.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",A[A.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",A[A.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",A[A.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",A[A.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",A[A.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",A[A.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",A[A.INVALID_OPERATION=5100]="INVALID_OPERATION",A[A.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",A[A.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",A[A.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",A[A.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",A[A.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",A[A.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",A[A.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",A[A.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",A[A.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",A[A.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",A[A.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",A[A.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",A[A.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",A[A.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",A[A.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",A[A.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",A[A.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",A[A.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",A[A.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",A[A.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",A[A.DEVICE_ERROR=5300]="DEVICE_ERROR",A[A.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",A[A.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",A[A.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",A[A.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",A[A.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",A[A.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",A[A.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",A[A.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",A[A.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",A[A.SERVER_ERROR=5400]="SERVER_ERROR",A[A.NEED_TO_BUY=5401]="NEED_TO_BUY",A[A.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",A[A.OPERATION_FAILED=5500]="OPERATION_FAILED",A[A.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",A[A.REJOIN_FAILED=5502]="REJOIN_FAILED",A[A.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",A[A.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",A[A.VIDEO_DECODE_ERROR=5505]="VIDEO_DECODE_ERROR",A[A.OPERATION_ABORT=5998]="OPERATION_ABORT",A[A.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",A))(St||{});function gm({code:s,params:i,enableDocLink:e=!1}){let t="",r,o=St[s];try{r=_m[o]}catch(n){r=_m.UNKNOWN_ERROR}return oe(r)?t=r(i):K(r)&&(t=r),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var _m=k(v({},Oe),{INVALID_PARAMETER({fnName:s}){return`the parameters of the '${s}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:s,rule:i,fnName:e,value:t}){let r=`${s||i.name}`,o="";return Array.isArray(i.type)?o=i.type.join("|"):o=i.type,`'${r}' must be type of ${o} when calling ${e}(), received type: ${Ae(t)}.`},INVALID_PARAMETER_EMPTY({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:s,rule:i,fnName:e,value:t}){let r=`${s||i.name}`,o=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${o} when calling ${e}(), received type: ${Ae(t)}.`},INVALID_PARAMETER_RANGE({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:s,rule:i,fnName:e}){return`'${s||i.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:s,rule:i,value:e}){return`the min value of ${s||i.name} is ${i.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:s,rule:i,value:e}){return`the max value of ${s||i.name} is ${i.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:s,fnName:i}){return`'${s}' is not found in the document object when calling ${i}().`},INVALID_ELEMENT_ID_TYPE({key:s,fnName:i,type:e}){return`the element corresponding to '${s}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`},INVALID_STREAM_ID({key:s}){return`'${s}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:s}){return`'${s}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:s}){return`'${s}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:s}){return`'${s}' 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:s})=>`'streamType' is required when 'userId' is not '*', calling ${s}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:s}){return`the API '${s}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:s}){return`cannot ${s} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:s,value:i}){return`cannot ${s} because remote user(userId: ${i.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:s,value:i}){return`cannot ${s} because remote user(userId: ${i.userId}) does not publishing ${i.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:s}){return`you are already ${s}(), cannot repeated call '${s}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:s}){return`cannot call '${s}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:s}){return`cannot call '${s}' because the microphone is not turned on.`},INVALID_BUFFER_EMPTY:({key:s})=>`the buffer size of paramerter '${s}' 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:s})=>`you need to call ${s}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:s}){return`the current browser does not support the capability of the function '${s}' 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:s}){return`cannot call ${s} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:s,error:i}){return`'${s}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:s,deviceType:i=Lr(s),error:e}){return`NotFoundError, no ${i} detected, please check your device and the configuration on '${s}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:s,deviceType:i=Lr(s),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:s,deviceType:i=Lr(s),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:s,deviceType:i=Lr(s),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:s,deviceType:i=Lr(s),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:s,deviceType:i=Lr(s),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:s,deviceType:i=Lr(s),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:s}){return`camera recover capture failed ${(s==null?void 0:s.name)||""}: ${(s==null?void 0:s.originMessage)||(s==null?void 0:s.message)}`},MICROPHONE_RECOVER_FAILED({error:s}){return`microphone recover capture failed ${(s==null?void 0:s.name)||""}: ${(s==null?void 0:s.originMessage)||(s==null?void 0:s.message)}`},OPERATION_FAILED({fnName:s,error:i}){return`'${s}' 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:s}){return`an error was caught on trtc.on('${s}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:s,error:i}){return`video context error ${s} ${(i==null?void 0:i.name)||""} ${(i==null?void 0:i.message)||""}`},SERVER_ERROR({fnName:s,error:i}){return`'${s}' got server error: ${i==null?void 0:i.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:s,url:i}){return`You need to buy packages for ${s}. Refer to: ${i}`},ACCOUNT_NO_MONEY:({fnParams:s})=>`your TRTC account run out of credit, please recharge.${s.sdkAppId?` SDKAppId: ${s.sdkAppId}`:""}`,OPERATION_ABORT({fnName:s}){return`'${s}' abort`},UNKNOWN_ERROR({fnName:s,error:i}){return`'${s}' throw unknown exception${i?`, error: ${i.toString()}.`:"."}`}});function Lr(s){if(!s)return"camera";let i=s.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var kl=class s extends Error{constructor({code:e,extraCode:t,message:r="",messageParams:o,fnName:n="",originError:a}){var l;let c;r?c=r:c=gm({code:e===U.SERVER_ERROR?e:t||e,params:v({fnName:n,error:a},o)});super(c);d(this,"name","RtcError");d(this,"code");d(this,"extraCode");d(this,"functionName");d(this,"message");d(this,"handler");d(this,"originError");this.name=St[e],this.code=e,this.extraCode=t,this.functionName=n,this.originError=a,this.message=c,this.extraCode===5302&&((l=this.originError)!=null&&l.message.includes("system"))&&(this.handler=()=>{let h={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},u={startLocalVideo:"webcam",startLocalAudio:"microphone"},p=document.createElement("a");pr?p.href=`ms-settings:privacy-${u[this.functionName]}`:Dt&&(p.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${h[this.functionName]}`),p.href.length>0&&p.click()})}static convertFrom(e,t,r){let o=e;if(e instanceof b){let{stack:n}=e,a={code:U.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case S.INVALID_PARAMETER:a.code=U.INVALID_PARAMETER,a.message=e.message;break;case S.INVALID_OPERATION:a.code=U.INVALID_OPERATION;break;case S.NOT_SUPPORTED:case S.NOT_SUPPORTED_H264:a.code=U.ENV_NOT_SUPPORTED,e.getCode()===S.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(Oe.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case S.JOIN_ROOM_FAILED:a.messageParams={fnParams:r};case S.SERVER_TIMEOUT:case S.SWITCH_ROLE_FAILED:a.code=U.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case S.API_CALL_ABORTED:a.code=U.OPERATION_ABORT;break;case S.DEVICE_NOT_FOUND:case S.DEVICE_AUTO_RECOVER_FAILED:case S.INITIALIZE_FAILED:a.code=5300,e.name&&(a.extraCode=Xg(e.name));break;case S.UNKNOWN:break;default:a.code=U.OPERATION_FAILED}o=new s(a),n&&(o.stack+=n.substr(n.indexOf(`
|
|
51
|
+
} `;var Mr=class extends Q{constructor(e){super();d(this,"frameRate");d(this,"_canvas");d(this,"log");d(this,"hasAlpha",!1);d(this,"name");d(this,"error");this.name=e.name,this.log=e.logger.createChild({id:`vc-${this.name}`}),this.frameRate=e.frameRate}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 Pi(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new Is(this,e)}createVideoImageSource(e,t){return new Ho(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new $o(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};d(Mr,"_ids",0);var Jg={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},As=class As extends Mr{constructor(){super(...arguments);d(this,"defaultProgam");d(this,"defaultVShader");d(this,"defaultFShader");d(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Mr._ids++}`),this.ctx=this._canvas.getContext("webgl2",Jg),!this.ctx)throw new b({code:S.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,Gg),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,Wg),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new b({code:S.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))}),this.log.info("video context created use webgl")}destroy(e){let t="";return e&&(t=e.message,this.error=e,N.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info(`video context destroy${t}`?`: ${t}`:""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var t;(t=this.ctx)==null||t.viewport(0,0,e,this.height),super.width=e}set height(e){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,e),super.height=e}setSize(e,t){var r;(r=this.ctx)==null||r.viewport(0,0,e,t),super.setSize(e,t)}createShader(e,t){let r=this.ctx,o=r.createShader(e);return r.shaderSource(o,t),r.compileShader(o),o}createProgram(e,t){let r=this.ctx,o=r.createProgram();return r.attachShader(o,e),r.attachShader(o,t),r.linkProgram(o),r.getProgramParameter(o,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(o)),o}};d(As,"UNAVAILABLE","unavailable"),y([le(Q.INIT,"created",{sync:!0,fail(e){N.addFailedEvent({key:512700,error:e.cause||e})},success(){N.addSuccessEvent({key:512700})}})],As.prototype,"create",1),y([le("created",Q.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(As.UNAVAILABLE,e),this.removeAllListeners()}})],As.prototype,"destroy",1);var ke=As,Ge=class extends Mr{constructor(){super(...arguments);d(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Mr._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new b({code:S.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this.log.info("video context created use 2d")}destroy(e){let t="";e&&(t=e.message,this.error=e,N.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info(`video context destroy ${t?`: ${t}`:""}`),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),N.addSuccessEvent({key:512703})}};y([le(Q.INIT,"created",{sync:!0,fail(e){N.addFailedEvent({key:512701,error:e.cause||e})},success(){N.addSuccessEvent({key:512701})}})],Ge.prototype,"create",1),y([le("created",Q.INIT,{ignoreError:!0,sync:!0})],Ge.prototype,"destroy",1);function qg(s){return[15,30,45,60].reduce((e,t)=>Math.abs(t-s)<Math.abs(e-s)?t:e)}var oi=class extends Ts{constructor(e,t,r=4){super(e,t,r);d(this,"mediaType",4);d(this,"source");d(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager,this.once("first-video-frame",o=>{this.room.emit("first-video-frame",o)})}play(e,t){return(me(t==null?void 0:t.canvasRender)?t.canvasRender:at===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,t).then(()=>{this.player.calculateStat()})}useCanvasPlayer(){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let e=new Ge({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=new kr(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(t),this.player.setCanvas(e._canvas),Ir()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=qg(t);if(!Y(t)||t<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${t} `);return}if(r===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${r} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${t}, closest: ${r}, current: ${e.frameRate}`),e.frameRate=r}get decodeFPS(){var n;let{msg_video_status:e}=((n=this.room.heartbeatReport)==null?void 0:n.msg_down_stream_info.find(a=>a.msg_user_info.str_identifier===this.userId))||{},t=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let r=e.find(a=>a.uint32_video_stream_type===t);return(r==null?void 0:r.uint32_video_dec_fps)||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),super.stop()}decodeFrame(e){if(!this.manager)return e;for(let t of this.manager.decodePipeline)if(t&&(e=t({frame:e,track:this}),!e))return;return e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get isAvailable(){return this.user.muteState.videoAvailable}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},Cs=class extends oi{constructor(e,t){super(e,t,2);d(this,"mediaType",2);d(this,"objectFit","contain")}get isAvailable(){return this.user.muteState.hasAuxiliary}};var Rs=new Map;E.on(T.JOIN_SUCCESS,({room:s})=>{he(s.userId,{eventId:32788})});E.on(T.LEAVE_START,({room:s})=>{he(s.userId,{eventId:32789})});E.on(T.LOCAL_TRACK_PUBLISHED,({track:s})=>{if(s.room){let i=32769;s.mediaType===4?i=32768:s.mediaType===2&&(i=32805),he(s.room.userId,{eventId:i})}});E.on(T.LOCAL_TRACK_UNPUBLISHED,({track:s})=>{if(s.room){let i=32771;s.mediaType===4?i=32770:s.mediaType===2&&(i=32806),he(s.room.userId,{eventId:i})}});E.on(T.TRACK_MUTED,({track:s})=>{s.room&&(s.kind===m.AUDIO?he(s.room.userId,{eventId:s.isRemote?32785:32772,remoteUserId:s.isRemote?s.userId:void 0}):he(s.room.userId,{eventId:s.isRemote?32784:32773,remoteUserId:s.isRemote?s.userId:void 0}))});E.on(T.TRACK_UNMUTED,({track:s})=>{s.room&&(s.kind===m.AUDIO?he(s.room.userId,{eventId:s.isRemote?32787:32774,remoteUserId:s.isRemote?s.userId:void 0}):he(s.room.userId,{eventId:s.isRemote?32786:32775,remoteUserId:s.isRemote?s.userId:void 0}))});E.on(T.REMOTE_TRACK_SUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&he(s.room.userId,{eventId:32777,remoteUserId:s.userId}),s.mediaType===4&&he(s.room.userId,{eventId:32776,remoteUserId:s.userId}),s.mediaType===8&&he(s.room.userId,{eventId:32803,remoteUserId:s.userId}))});E.on(T.REMOTE_TRACK_UNSUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&he(s.room.userId,{eventId:32779,remoteUserId:s.userId}),s.mediaType===4&&he(s.room.userId,{eventId:32778,remoteUserId:s.userId}),s.mediaType===8&&he(s.room.userId,{eventId:32804,remoteUserId:s.userId}))});E.on(T.SWITCH_DEVICE_SUCCESS,({track:s})=>{s.room&&he(s.room.userId,{eventId:s.kind===m.VIDEO?32780:32781})});E.on(T.LOCAL_TRACK_REPLACED,({track:s})=>{s.room&&he(s.room.userId,{eventId:s.kind===m.VIDEO?32782:32783})});E.on(T.SIGNAL_CONNECTION_STATE_CHANGED,({room:s,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&&he(s.userId,{eventId:t})});E.on(T.PEER_CONNECTION_STATE_CHANGED,({room:s,prevState:i,state:e,remoteUserId:t})=>{let r=!!t,o;switch(e){case"CONNECTED":i==="RECONNECTING"?o=r?32801:32798:o=r?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(o=r?32802:32799);break;case"RECONNECTING":o=r?32800:32797;break}o&&he(s.userId,{eventId:o,remoteUserId:t})});E.on(T.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:s,userId:i,remoteUserId:e,codec:t,isHWCodec:r,prevImplementation:o,streamType:n})=>{let a=r?1:0;o||(a=r?3:2);let c=t==="h264"?0:2,l={eventId:4004,param1:a,param2:c,streamType:n||2};e&&(l.remoteUserId=e,l.eventId=4005),he(i,l),N.addEnum({key:e?514701:513701,value:a}),N.addEnum({key:e?514700:513700,value:c})});E.on(T.LOCAL_TRACK_RECAPTURE,({track:s,error:i})=>{if(s.userId){let e={eventId:2003,param1:0};s.kind===m.AUDIO?(e.streamType=1,i&&(e.param1=2)):(e.streamType=s.streamType==="auxiliary"?7:2,i&&(e.param1=8)),he(s.userId,e)}});function he(s,i){let e=k(v({},i),{timestamp:Fs()});Rs.has(s)?Rs.get(s).push(e):Rs.set(s,[e])}function hm(s){if(Rs.has(s)){let i=Rs.get(s).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 Rs.delete(s),i}return[]}var mm=Pe(je(),1);var xa=class extends mm.EventEmitter{constructor(e,t,r="userId"){super();this.mySelfId=e;this._log=t;this.key=r;d(this,"userMap",new Map);d(this,"remotePublishedUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(e=>e.isRobot)}getPublishedUser(e){return this.remotePublishedUserMap.get(e)}addUser(e){let t=e[this.key],{userId:r,tinyId:o,role:n}=e;if(this.userMap.has(t))return;let a={userId:r,tinyId:o,role:n===20?"anchor":"audience"};this.userMap.set(t,a),this.emit("1",a)}deleteUser(e,t){let r=this.userMap.get(e);if(!r)return;let o=`peer leave [${e}]`;g(t)||(o+=`:${kd[t]}`),this._log.info(o);let n=this.remotePublishedUserMap.get(e);if(n){let a=n.muteState;n.flag=0,this.emit("5",n.userId),this.deleteRemotePublishedUser(e),this.emit("6",{prevMuteState:a,muteState:n.muteState,flag:0})}this.userMap.delete(e),this.emit("2",r.userId)}setUserList(e){this.userMap.forEach(t=>{e.findIndex(r=>r[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),e.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(e){this.remotePublishedUserMap.has(e[this.key])||this.remotePublishedUserMap.set(e[this.key],e)}deleteRemotePublishedUser(e){this.remotePublishedUserMap.has(e)&&this.remotePublishedUserMap.delete(e)}setRemotePublishedUserList(e){this.remotePublishedUserMap.forEach(t=>{let r=t[this.key];if(e.findIndex(o=>o[this.key]===t[this.key])<0){this._log.info(`remote [${r}] unpublish`);let o=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(r),this.emit("6",{prevMuteState:o,muteState:t.muteState,flag:0})}}),e.forEach(t=>{var h;let r=t[this.key];if(r===this.mySelfId)return;let{flag:o,userId:n,tinyId:a}=t,c=pi(o,n),l=(h=this.remotePublishedUserMap.get(r))==null?void 0:h.muteState;if(l){let u=this.remotePublishedUserMap.get(r);u&&u.flag!==o&&(u.flag=o,this._log.info(`remote publish updated: ${JSON.stringify(u.muteState)}`),this.emit("6",{prevMuteState:l,muteState:c,flag:o}))}else this._log.info(`remote publish. state: ${JSON.stringify(c)}`),this.addUser({userId:n,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:pi(0,n),muteState:c,flag:o})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function Ol({timesInSecond:s,maxSizeInSecond:i,getSize:e}){return J((t,r)=>{let o=new WeakMap;return E.on(T.ROOM_DESTROY,({room:n})=>o.delete(n)),function(...n){let a=o.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=s||a.totalSizeInSecond>i))throw new b({code:S.INVALID_OPERATION,message:V({key:w.CALL_FREQUENCY_LIMIT,data:{isTimes:a.callCountInSecond>=s,isSize:a.totalSizeInSecond>i,name:r,timesInSecond:s,maxSizeInSecond:i}})});a.callCountInSecond++,t.call(this,...n)}})}var jg="2025-04-08 21:22:23",pm=!0,fm=function(){var s;pm&&(pm=!1,C.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Ft}/en/index.html`),console.info(`* Changelog: ${Ft}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),C.info("TRTC Web SDK Version:",Re),Mt||C.debug("Build Time:",jg),C.info("UA:",navigator.userAgent),C.info(`URL: ${location.href}${((s=self.frameElement)==null?void 0:s.tagName)==="IFRAME"?" in iframe":""}`),ho().then(i=>{i&&C.info(bt)}))};var Et={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"};var U={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},St=(A=>(A[A.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",A[A.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",A[A.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",A[A.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",A[A.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",A[A.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",A[A.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",A[A.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",A[A.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",A[A.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",A[A.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",A[A.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",A[A.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",A[A.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",A[A.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",A[A.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",A[A.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",A[A.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",A[A.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",A[A.INVALID_OPERATION=5100]="INVALID_OPERATION",A[A.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",A[A.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",A[A.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",A[A.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",A[A.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",A[A.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",A[A.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",A[A.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",A[A.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",A[A.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",A[A.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",A[A.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",A[A.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",A[A.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",A[A.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",A[A.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",A[A.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",A[A.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",A[A.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",A[A.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",A[A.DEVICE_ERROR=5300]="DEVICE_ERROR",A[A.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",A[A.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",A[A.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",A[A.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",A[A.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",A[A.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",A[A.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",A[A.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",A[A.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",A[A.SERVER_ERROR=5400]="SERVER_ERROR",A[A.NEED_TO_BUY=5401]="NEED_TO_BUY",A[A.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",A[A.OPERATION_FAILED=5500]="OPERATION_FAILED",A[A.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",A[A.REJOIN_FAILED=5502]="REJOIN_FAILED",A[A.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",A[A.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",A[A.VIDEO_DECODE_ERROR=5505]="VIDEO_DECODE_ERROR",A[A.OPERATION_ABORT=5998]="OPERATION_ABORT",A[A.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",A))(St||{});function gm({code:s,params:i,enableDocLink:e=!1}){let t="",r,o=St[s];try{r=_m[o]}catch(n){r=_m.UNKNOWN_ERROR}return oe(r)?t=r(i):K(r)&&(t=r),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var _m=k(v({},Oe),{INVALID_PARAMETER({fnName:s}){return`the parameters of the '${s}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' is a required param when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_TYPE({key:s,rule:i,fnName:e,value:t}){let r=`${s||i.name}`,o="";return Array.isArray(i.type)?o=i.type.join("|"):o=i.type,`'${r}' must be type of ${o} when calling ${e}(), received type: ${Ae(t)}.`},INVALID_PARAMETER_EMPTY({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' cannot be '${t}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:s,rule:i,fnName:e,value:t}){let r=`${s||i.name}`,o=`${i.instanceOf.name||i.instanceOf}`;return`'${r}' must be instanceof ${o} when calling ${e}(), received type: ${Ae(t)}.`},INVALID_PARAMETER_RANGE({key:s,rule:i,fnName:e,value:t}){return`'${s||i.name}' must be one of ${i.values.join("|")} when calling ${e}(), received: ${t}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:s,rule:i,fnName:e}){return`'${s||i.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:s,rule:i,value:e}){return`the min value of ${s||i.name} is ${i.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:s,rule:i,value:e}){return`the max value of ${s||i.name} is ${i.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:s,fnName:i}){return`'${s}' is not found in the document object when calling ${i}().`},INVALID_ELEMENT_ID_TYPE({key:s,fnName:i,type:e}){return`the element corresponding to '${s}' must be instanceof HTMLElement when calling ${i}(), received: ${e}.`},INVALID_STREAM_ID({key:s}){return`'${s}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:s}){return`'${s}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:s}){return`'${s}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:s}){return`'${s}' 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:s})=>`'streamType' is required when 'userId' is not '*', calling ${s}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:s}){return`the API '${s}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:s}){return`cannot ${s} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:s,value:i}){return`cannot ${s} because remote user(userId: ${i.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:s,value:i}){return`cannot ${s} because remote user(userId: ${i.userId}) does not publishing ${i.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:s}){return`you are already ${s}(), cannot repeated call '${s}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:s}){return`cannot call '${s}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:s}){return`cannot call '${s}' because the microphone is not turned on.`},INVALID_BUFFER_EMPTY:({key:s})=>`the buffer size of paramerter '${s}' 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:s})=>`you need to call ${s}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:s}){return`the current browser does not support the capability of the function '${s}' 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:s}){return`cannot call ${s} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:s,error:i}){return`'${s}' got device exception${i?`, error: ${i.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:s,deviceType:i=Lr(s),error:e}){return`NotFoundError, no ${i} detected, please check your device and the configuration on '${s}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:s,deviceType:i=Lr(s),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:s,deviceType:i=Lr(s),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:s,deviceType:i=Lr(s),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:s,deviceType:i=Lr(s),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:s,deviceType:i=Lr(s),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:s,deviceType:i=Lr(s),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:s}){return`camera recover capture failed ${(s==null?void 0:s.name)||""}: ${(s==null?void 0:s.originMessage)||(s==null?void 0:s.message)}`},MICROPHONE_RECOVER_FAILED({error:s}){return`microphone recover capture failed ${(s==null?void 0:s.name)||""}: ${(s==null?void 0:s.originMessage)||(s==null?void 0:s.message)}`},OPERATION_FAILED({fnName:s,error:i}){return`'${s}' 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:s}){return`an error was caught on trtc.on('${s}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:s,error:i}){return`video context error ${s} ${(i==null?void 0:i.name)||""} ${(i==null?void 0:i.message)||""}`},SERVER_ERROR({fnName:s,error:i}){return`'${s}' got server error: ${i==null?void 0:i.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:s,url:i}){return`You need to buy packages for ${s}. Refer to: ${i}`},ACCOUNT_NO_MONEY:({fnParams:s})=>`your TRTC account run out of credit, please recharge.${s.sdkAppId?` SDKAppId: ${s.sdkAppId}`:""}`,OPERATION_ABORT({fnName:s}){return`'${s}' abort`},UNKNOWN_ERROR({fnName:s,error:i}){return`'${s}' throw unknown exception${i?`, error: ${i.toString()}.`:"."}`}});function Lr(s){if(!s)return"camera";let i=s.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var kl=class s extends Error{constructor({code:e,extraCode:t,message:r="",messageParams:o,fnName:n="",originError:a}){var l;let c;r?c=r:c=gm({code:e===U.SERVER_ERROR?e:t||e,params:v({fnName:n,error:a},o)});super(c);d(this,"name","RtcError");d(this,"code");d(this,"extraCode");d(this,"functionName");d(this,"message");d(this,"handler");d(this,"originError");this.name=St[e],this.code=e,this.extraCode=t,this.functionName=n,this.originError=a,this.message=c,this.extraCode===5302&&((l=this.originError)!=null&&l.message.includes("system"))&&(this.handler=()=>{let h={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},u={startLocalVideo:"webcam",startLocalAudio:"microphone"},p=document.createElement("a");pr?p.href=`ms-settings:privacy-${u[this.functionName]}`:Dt&&(p.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${h[this.functionName]}`),p.href.length>0&&p.click()})}static convertFrom(e,t,r){let o=e;if(e instanceof b){let{stack:n}=e,a={code:U.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case S.INVALID_PARAMETER:a.code=U.INVALID_PARAMETER,a.message=e.message;break;case S.INVALID_OPERATION:a.code=U.INVALID_OPERATION;break;case S.NOT_SUPPORTED:case S.NOT_SUPPORTED_H264:a.code=U.ENV_NOT_SUPPORTED,e.getCode()===S.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(Oe.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case S.JOIN_ROOM_FAILED:a.messageParams={fnParams:r};case S.SERVER_TIMEOUT:case S.SWITCH_ROLE_FAILED:a.code=U.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case S.API_CALL_ABORTED:a.code=U.OPERATION_ABORT;break;case S.DEVICE_NOT_FOUND:case S.DEVICE_AUTO_RECOVER_FAILED:case S.INITIALIZE_FAILED:a.code=5300,e.name&&(a.extraCode=Xg(e.name));break;case S.UNKNOWN:break;default:a.code=U.OPERATION_FAILED}o=new s(a),n&&(o.stack+=n.substr(n.indexOf(`
|
|
52
52
|
`)))}else{if(e instanceof s)return e;o=new s({code:U.UNKNOWN_ERROR,fnName:t,originError:e})}return o}};function Xg(s){let i;switch(s){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 P=kl;var Tm={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}}},Em={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}}},ys={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(s,i,e){if(K(s)&&!document.getElementById(s))throw new P({code:U.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},Sm={name:"userId",required:!0,type:"string"},Im={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[Et.AUDIO_PROFILE_STANDARD,Et.AUDIO_PROFILE_STANDARD_STEREO,Et.AUDIO_PROFILE_HIGH,Et.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function Go(s,i){if(!s)throw new P({code:U.INVALID_OPERATION,extraCode:5101,fnName:i})}function Am(s,i,e){if(!s)throw new P({code:U.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}var PD={type:"number",notLessThanZero:!0},Qg={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(s,i,e){if(this._room.isJoined)throw new P({code:U.INVALID_OPERATION,extraCode:5104,fnName:e});if(s.roomId){if(K(s.roomId))throw new P({code:U.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});if(!(/^[1-9]\d*$/.test(String(s.roomId))&&s.roomId<4294967295))throw new P({code:U.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:i}})}else if(s.strRoomId){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(s.strRoomId))throw new P({code:U.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:i}})}else throw new P({code:U.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:ys,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:Tm},validate(s){var i;if(!((i=s==null?void 0:s.option)!=null&&i.videoTrack)&&Ci())throw new P({code:U.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:k(v({},ys),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:Tm}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:Im},validate(s){var i;if(!((i=s==null?void 0:s.option)!=null&&i.audioTrack)&&Ci())throw new P({code:U.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:Im}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:ys,publish:{type:"boolean"},option:Em},validate(s,i,e,t,r){var o;if(!((o=s==null?void 0:s.option)!=null&&o.videoTrack)&&Ci())throw new P({code:U.ENV_NOT_SUPPORTED,extraCode:5201});if(!So())throw new P({code:U.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:ys,publish:{type:"boolean"},option:Em}},muteRemoteAudio:[Sm,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[Sm,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:ys,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(s,i,e){Go(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(s.userId);if(Am(!!t,e,s),t&&(s.streamType==="main"&&!t.muteState.videoAvailable||s.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new P({code:U.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:s}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:k(v({},ys),{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(s,i,e){Go(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(s.userId);if(Am(!!t,e,s),t&&(s.streamType==="main"&&!t.muteState.videoAvailable||s.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new P({code:U.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:s}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(s,i,e){if(s.userId!=="*"&&g(s.streamType))throw new P({code:U.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(s,i,e){Go(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(s,i,e,t){if(!Ro)throw new P({code:U.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new P({code:U.INVALID_OPERATION,fnName:e,extraCode:5108});if(s.byteLength>1e3)throw new P({code:U.INVALID_PARAMETER,extraCode:5018,fnName:e});if(s.byteLength===0)throw new P({code:U.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});Go(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(s,i,e){if(!s&&!this._room.isMainStreamPublished||s&&!this._room.isAuxStreamPublished)throw new P({code:U.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(s,i,e,t){if(s.byteLength>1e3)throw new P({code:U.INVALID_PARAMETER,extraCode:5018,fnName:e});if(s.byteLength===0)throw new P({code:U.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(s,i,e){if(Go(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new P({code:U.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}}},Me={TRTC:Qg};var We=class extends Error{};function zg(s,i){let e=lr(s);for(let t=0;t<i.length;t++)Gt(e[t],i[t]);return e}function Yg(s){this._resolve=Promise.resolve(s)}function Kg(s){this._reject=Promise.reject(s)}var ir=class ir{constructor(i,e){this.instance=i;this.group=e;d(this,"started",!1);d(this,"ops",[]);d(this,"startSame",()=>!0);d(this,"mergeUpdate",zg);let t=ir.instances.get(i);t?t.set(e,this):ir.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=ir.instances.get(i);return t&&t.get(e)||new ir(i,e)}static gets(i,e){let t=ir.instances.get(i),r=[];return t&&t.forEach((o,n)=>{e.test(n)&&r.push(o)}),r}action(i,e,t){let r=a=>{var c;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(c=this.currentOp)==null||c.action(),a},o=a=>{var c,l;throw this.ops.shift(),i===0&&((c=this.currentOp)==null?void 0:c.type)===2&&this.ops.shift().reject(new We("start failed")),(l=this.currentOp)==null||l.action(),a},n={type:i,action:()=>e(...n.args).then(r,o),args:t,resolve:Yg,reject:Kg};try{switch(this.state){case 1:if(i===0)throw new We("already started");break;case 4:if(i===2)throw new We("not started");break;default:return this.cacheOp(n)}}catch(a){return Promise.reject(a)}return this.ops.push(n),n.promise=e(...n.args).then(r,o)}cacheOp(i){if(this.ops.length===1)switch(this.state){case 0:case 2:if(i.type===0)throw new We("already start");break;case 3:switch(i.type){case 2:throw new We("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new We("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new We("keep stop");if(this.ops.slice(1).forEach(r=>r.reject(t)),this.ops=this.ops.slice(0,1),this.state===3)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,i.args),this.lastOp.promise;case 3:throw new We("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new We("start not allowed after update");case 0:throw new We("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new We("keep start")),new We("already start")}}i.promise=new Promise((t,r)=>{i._resolve?i._resolve.then(t):i.resolve=t,i._reject?i._reject.catch(r):i.reject=r});let{action:e}=i;return i.action=()=>e().then(i.resolve,i.reject),this.ops.push(i),i.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}};d(ir,"instances",new WeakMap);var xi=ir;var wa=new WeakMap,Ua=(s,i)=>{if(i instanceof We){let{stack:e}=i;i=new P({code:U.OPERATION_ABORT,message:`${s} abort: ${i.message}`,fnName:s}),e&&(i.stack+=e.substr(e.indexOf(`
|
|
53
53
|
`)))}throw i};function rr(s,i){return J((e,t)=>function(...r){let o=xi.get(this,typeof s=="string"?s:s.call(this,...r));return o?(i&&(o.startSame=i.bind(this)),o.action(0,e.bind(this),r).catch(Ua.bind(null,t))):e.apply(this,r)})}function Pr(s,i){let{merge:e,debounce:t}=i||{};return J((r,o)=>function(...n){let a=xi.get(this,typeof s=="string"?s:s.call(this,...n));if(!a)return r.apply(this,n);if(e&&(a.mergeUpdate=e.bind(this)),t&&t.isNeedToDebounce.apply(this,n)){let{delay:c,getKey:l}=t;return new Promise((h,u)=>{var I,R;let p=(I=wa.get(this))==null?void 0:I.get(l(...n));if(p){let{timeoutId:D,resolve:G}=p;clearTimeout(D),G()}let _=setTimeout(()=>{if(a.state===3||a.state===4)return h();a.action(2,r.bind(this),n).catch(Ua.bind(null,o)).then(h,u)},c);wa.has(this)?(R=wa.get(this))==null||R.set(l(...n),{timeoutId:_,resolve:h}):wa.set(this,new Map([[l(...n),{timeoutId:_,resolve:h}]]))})}return a.action(2,r.bind(this),n).catch(Ua.bind(null,o))})}function sr(s){return J((i,e)=>function(...t){let r=typeof s=="function"?s.call(this,...t):s;if(r instanceof RegExp)return Promise.all(xi.gets(this,r).map(n=>n.action(3,()=>Promise.resolve(),t))).then(()=>i.call(this,...t));let o=xi.get(this,r);return o?o.action(3,i.bind(this),t).catch(Ua.bind(null,e)):i.apply(this,t)})}var M={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame"},Cm=new Set([M.ERROR,M.AUTOPLAY_FAILED,M.KICKED_OUT,M.REMOTE_USER_ENTER,M.REMOTE_USER_EXIT,M.REMOTE_AUDIO_AVAILABLE,M.REMOTE_AUDIO_UNAVAILABLE,M.REMOTE_VIDEO_AVAILABLE,M.REMOTE_VIDEO_UNAVAILABLE,M.CONNECTION_STATE_CHANGED,M.PUBLISH_STATE_CHANGED,M.SCREEN_SHARE_STOPPED,M.DEVICE_CHANGED,M.FIRST_VIDEO_FRAME]);function or(s){return s==="sub"?"auxiliary":s==="auxiliary"?"sub":"main"}function Wo(s){return s===Et.QOS_PREFERENCE_CLEAR?"detail":s===Et.QOS_PREFERENCE_SMOOTH?"motion":""}var Ll={};ci(Ll,{bytes2ms:()=>xu,convertObjectNumberToInt:()=>Zs,copyProperties:()=>Pu,deepClone:()=>lr,deepMerge:()=>Gt,delay:()=>fi,fibonacci:()=>hr,formatedTime:()=>Gu,getConstructorName:()=>Ys,getContainerFromElement:()=>$u,getEnv:()=>Mu,getInternalVersion:()=>Fu,getLoggerUrl:()=>mi,getMuteStateFromFlag:()=>pi,getNetworkType:()=>Ld,getNumNetworkType:()=>ur,getReconnectionTimeout:()=>yt,getStringByteLength:()=>Ks,getTurnServer:()=>Hu,getUint32Version:()=>In,getValueType:()=>Ae,getViewListFromView:()=>zr,glog:()=>wd,ipv4ToUint32:()=>Qr,isArray:()=>Te,isAudioWorkletSupported:()=>Bu,isBoolean:()=>me,isConstructor:()=>qr,isEmpty:()=>Xr,isFunction:()=>oe,isLangChinese:()=>Rt,isMediaStreamTrack:()=>Uu,isNumber:()=>Y,isObject:()=>$t,isOverseaSdkAppId:()=>zs,isPlainObject:()=>Ze,isPortrait:()=>Sn,isPromise:()=>Wi,isRemoteTrack:()=>Vu,isString:()=>K,isUndefined:()=>g,loadImage:()=>Yr,ms2bytes:()=>wu,ms2samples:()=>xd,performanceNow:()=>L,promiseAny:()=>jr,samples2ms:()=>Pd,setNetworkType:()=>Tn,stringify:()=>ft,stringifyIncludeValue:()=>En,throttlePromise:()=>An});var wl={};ci(wl,{getAbilityConfigUrl:()=>eT,getScheduleDomain:()=>xr,isNeedToSchedule:()=>Va,scheduleProxy:()=>mt,sendScheduleRequest:()=>xl,setIsNeedToSchedule:()=>wt,setScheduleProxy:()=>Ba});var Pl=null,Va=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values(hi).map(s=>`<link rel="dns-prefetch" href="https://${s}">`).join(`\r
|
|
54
54
|
`));function wt(s){me(s)&&s!==Va&&(Va=s,C.info(`setIsNeedToSchedule ${s}`))}E.on("28",()=>wt(!0));E.on("63",()=>wt(!0));E.on("84",()=>wt(!0));E.on("201",s=>{s.state==="RECONNECTING"&&wt(!0)});E.on("202",s=>{s.state==="RECONNECTING"&&wt(!0)});function Zg(s,i,e){let t={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let r=performance.getEntriesByType("resource"),o=bs(s,m.MAIN),n=bs(s,m.BACKUP);for(let a of r)if(a.startTime>=e&&(a.name===o||a.name===n)&&a.transferSize>0){let c=a.name===o?m.MAIN:m.BACKUP,l=Math.round(a.duration),h=Math.round(a.domainLookupStart-a.startTime),u=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),I=Math.round(a.requestStart-a.secureConnectionStart),R=Math.round(a.secureConnectionStart-a.connectStart),D=Math.round(a.responseStart-a.requestStart),G=Math.round(a.responseEnd-a.responseStart),te=[_,I,R,D,G];ee.uploadEvent({log:`stat-schedule-net:${l}(${h}(${u}->${p})->${te.join("->")}) ${c}`,userId:i}),t=k(v({},t),{totalCost:l,local:h,dns:_,tcp:R,tls:I,request:D,response:G});break}}catch(r){C.error("getScheduleDetailCost error",r)}return t}function xl(l){return f(this,arguments,function*({userId:s,sdkAppId:i,useStringRoomId:e,roomId:t,userSig:r,version:o,frameWorkType:n,role:a,latencyLevel:c}){if(!Va&&Pl)return{isCached:!0,result:Pl};let h={delta:0,count:[1,1],msg:[],detail:[]};try{let u=new FormData;u.append("userId",String(s)),u.append("sdkAppId",String(i)),u.append("isStrGroupId",String(e)),u.append("groupId",String(t)),u.append("sdkVersion",o),u.append("userSig",String(r)),a&&u.append("role",String(a)),c&&u.append("latencyLevel",String(c)),n&&u.append("frameWorkType",String(n));let p=L(),_=yield iT(u,h,i);_.config&&(_.config.loggerDomain&&nr(_.config.loggerDomain),me(_.config.scheduleCache)&&wt(!_.config.scheduleCache)),h.delta=L()-p;let I=Zg(Number(i),s,p);return Pl=_,{isCached:!1,result:_,detailCost:I}}catch(u){let p=Te(u)?u[0]:u,_=Y(p.code)?p.code:0,I=`schedule failed${p.message?`: ${p.message}`:""}`,R=new b({code:S.SCHEDULE_FAILED,extraCode:_,message:V({key:w.JOIN_ROOM_FAILED,data:{error:I,code:_}})});throw C.error(I,_),R}})}var mt={main:"",backup:""};function Ba(s){Te(s)?(mt.main=s[0],mt.backup=s[1]):mt.main=s}function bs(s,i=m.MAIN,e=!1){return`https://${mt[i]||xr(s,i,e)}/api/v1/config`}function eT(s,i=m.MAIN){return`https://${mt[i]||xr(s,i)}/api/v1/trtcAutoConf`}function xr(s,i=m.MAIN,e=!1){let t;return zs(s)?e?t=i===m.MAIN?hi.MAIN_OVERSEA_BACKUP:hi.BACKUP_OVERSEA:t=i===m.MAIN?hi.MAIN_OVERSEA:hi.BACKUP_OVERSEA:t=i===m.MAIN?hi.MAIN:hi.BACKUP,t}function tT(s,i,e){return new Promise((t,r)=>{_i({url:s,body:i,timeout:e.timeout,priority:"high"}).then(o=>{o.data.code===0?t(o.data.data):r({code:o.data.code,message:o.data.msg})}).catch(r)})}var Rm=(s,i)=>Jt({retryFunction:tT,settings:{retries:3,timeout:0},onError:i,onRetrying:s});function iT(s,i,e){return new Promise((t,r)=>{let o=null;jr([Rm(n=>i.count[0]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:l})=>{i.msg[0]=n.message,o||(c>=1&&(l[0]=bs(e,m.MAIN,!0)),a())})(bs(e,m.MAIN),s,{get timeout(){return hr(2+i.count[0])*1e3}}),Rm(n=>i.count[1]=n+1,({error:n,retry:a,retriedCount:c,retryFuncArgs:l})=>{i.msg[1]=n.message,o||(c>=2&&(l[0]=bs(e,m.BACKUP,!0)),a())})(bs(e,m.BACKUP),s,{get timeout(){return hr(2+i.count[1])*1e3}})]).then(n=>{o=n,t(o)}).catch(r)})}var rT=s=>s.startsWith("data:application/octet-stream;base64,"),sT=s=>s.startsWith("file://"),Fa=class{constructor(){d(this,"_log");this._log=C.createLogger({id:"fd"})}download(i,e){return f(this,null,function*(){let{type:t="blob"}=e||{};try{let r=L(),o;if(oe(fetch)?o=yield this.downloadWithFetch(i,t):o=yield this.downloadWithXHR(i,t),!o||!o.data)throw new Error("data is empty");let n=L()-r;return this._log.info(`downloaded: ${i}, return type: ${t}, cost: ${n}ms`),N.addSuccessEvent({key:522700,cost:L()-r}),o.data}catch(r){throw this._log.error(`failed to download: ${i}, error: ${r}`),N.addFailedEvent({key:522700,error:r}),r}})}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 r;return e==="arraybuffer"?r=yield t.arrayBuffer():r=yield t.blob(),{data:r}}catch(t){throw t}})}downloadWithXHR(i,e){return this._log.info(`download with xhr: ${i}, return type: ${e}`),new Promise((t,r)=>{let o=new XMLHttpRequest;o.open("GET",i,!0),o.responseType=e,o.onload=()=>{o.status===200||o.status===0&&o.response?t({data:o.response}):r(new Error("XHR failed"))},o.onerror=r,o.send(null)})}loadWasm(i,e){return f(this,null,function*(){this._log.info(`loadWasm ${i}, importObject: ${JSON.stringify(e)}`);let t=L(),r=null,o=null;if(oe(WebAssembly.instantiateStreaming)&&!rT(i)&&!sT(i)&&oe(fetch))try{let n=fetch(i);r=(yield WebAssembly.instantiateStreaming(n,e)).instance}catch(n){o=n}if(!r)try{let n=yield this.download(i,{type:"arraybuffer"});r=(yield WebAssembly.instantiate(n,e)).instance}catch(n){o=n}if(r){let n=L()-t;return this._log.info(`loadedWasm ${i}, cost: ${n}ms`),N.addSuccessEvent({key:522701,cost:n}),r}throw this._log.error(`failed to loadWasm ${i}, error: ${o}`),N.addFailedEvent({key:522701,error:o}),o})}};y([tt({settings:{timeout:0,retries:3},onRetrying(i){this._log.warn(`download retrying: ${i}`)}})],Fa.prototype,"download",1);var ym=new Fa;function bm({TRTC:s,room:i,errorModule:e,assetsPath:t}){return{TRTC:s,room:i,assetsPath:t,fileDownloader:ym,innerEmitter:E,constants:Md,environment:ds,utils:Ll,eventLogger:ee,log:this.room.getLogger(),loggerManager:C,errorModule:e,kvStatManager:N,rtcDectection:Yt,trtc:this,rx:Dl,enums:mc,schedule:wl,clearStarted:(r,o)=>{let n=r.getAlias(),a=xi.instances.get(this);if(a)if(o){let c=a.get(n+o);if(!c)return;c.started=!1}else a.forEach((c,l)=>{l.startsWith(n)&&(c.started=!1)})},startGetPCM:Uo,createAudioNode:Lo}}var Nm=(s,i)=>{let{emit:e}=s;return s.emit=(...t)=>{try{return e.apply(s,t)}catch(r){let o=V({key:w.CATCH_HANDLER_ERROR,data:{name:i,event:t[0]},addDocLink:!1});return C.warn(`${o}
|
|
55
55
|
|
|
56
|
-
${r.stack}`),!1}},s};var Ns=new WeakMap;function vm(s){let i=Ns.get(s);i&&(i.forEach(e=>clearTimeout(e)),Ns.delete(s))}function Dm(s,i){return J((e,t)=>function(...r){let o=Ns.get(this);o||(o=new Map,Ns.set(this,o));let n=i(...r),a=o.get(n);if(!a||a<=0){e.apply(this,r);let c=setTimeout(()=>{var l;(l=Ns.get(this))==null||l.delete(n)},s);o.set(n,c)}else{clearTimeout(a);let c=window.setTimeout(()=>{var l;e.apply(this,r),(l=Ns.get(this))==null||l.delete(n)},s);o.set(n,c)}})}var Om="5.9.2-beta.14";function Je(...s){return J((i,e)=>function(...t){try{$a.call(this,s,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function Ul(...s){return J((i,e)=>function(...t){try{$a.call(this,s,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function $a(s,i,e,t){if(Te(s))for(let r=0;r<s.length;r++)Ha.call(this,{rule:s[r],value:i[r],key:s[r].name,fnName:e,className:t});else Ha.call(this,{rule:s,value:i[0],key:s.name,fnName:e,className:t})}function Ha({rule:s,value:i,key:e,fnName:t,className:r}){function o(c){return{code:U.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:s,value:i}}}if(g(i)){if(s.required)throw new P(o(5001));if(g(s.defaultValue)){oe(s.validate)&&s.validate.call(this,i,e,t,r,this);return}i=s.defaultValue}if(Array.isArray(s.type)){let c=!1;for(let l=0;l<s.type.length;l++)s.type[l]===null&&i===null&&(c=!0),oe(s.type[l])&&i instanceof s.type[l]&&(c=!0),K(s.type[l])&&Ae(i)===s.type[l].toLowerCase()&&(c=!0);if(!c)throw new P({code:U.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:s.type.map(l=>qr(l)?Ys(l):K(l)?l:Ae(l))},value:i}})}else if(!g(s.type)&&Ae(i)!==s.type)throw new P(o(5002));if(s.allowEmpty===!1){let c=Y(i)&&(i===0||Number.isNaN(i)),l=K(i)&&i.trim()==="";if(c||l)throw new P(o(5003))}if(s.notLessThanZero&&Y(i)&&i<0)throw new P(o(5006));if(!g(s.min)&&Y(i)&&i<s.min)throw new P(o(5007));if(!g(s.max)&&Y(i)&&i>s.max)throw new P(o(5008));if(K(s.instanceOf)){if(!i||i._name!==s.instanceOf)throw new P(o(5004))}else if(oe(s.instanceOf)&&!(i instanceof s.instanceOf))throw new P(o(5004));if(Array.isArray(s.values)&&!s.values.includes(i))throw new P(o(5005));let{properties:n}=s;Ze(n)&&$t(i)&&Object.keys(n).forEach(c=>{Ha.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:r})});let{arrayItem:a}=s;Ze(a)&&Te(i)&&i.forEach((c,l)=>{Ha.call(this,{rule:a,value:c,key:`${e}[${l}]`,fnName:t,className:r})}),oe(s.validate)&&s.validate.call(this,i,e,t,r,this)}function ue(s={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r}=s;return J((o,n)=>function(...a){var u;function c(p,_,I){if(I&&I.includes(p))return"hided";if(e){let R=e(...a);if(a[R.argIndex]===_)return R.value}if(_===a||p in a)return _;try{return _ instanceof HTMLElement?`id: ${_.id} type:${Ae(_)}`:(JSON.stringify(_),_)}catch(R){return`type:${Ae(_)}`}}let l=this._log||C;if(r!=null&&r(...a))return o.apply(this,a);a.length>0?l.info(`${n}() ${JSON.stringify(a,(p,_)=>c(p,_,["userSig","privateMapKey"]))}`):l.info(`${n}()`);let h=t?t(...a):qn[n];try{let p=o.apply(this,a),_=L();return Wi(p)?p.then(I=>(l.info(`${n}() success ${i.call(this,...a)}`),N.addSuccessEvent({key:h,cost:L()-_}),I)).catch(I=>{var G;I=P.convertFrom.call(this,I,n,a.length===1?a[0]:a);let R=I.extraCode||I.code,D=(G=I.message)!=null&&G.includes(R)?"":` code:${R}`;throw l.error(`${n}() failed ${i.call(this,...a)} ${I}${D} params: ${JSON.stringify(a,c)}`),N.addFailedEvent({key:h,error:I}),I}):(N.addSuccessEvent({key:h}),p)}catch(p){p=P.convertFrom.call(this,p,n);let _=p.extraCode||p.code,I=(u=p.message)!=null&&u.includes(_)?"":` code:${_}`;throw l.error(`${n}() failed ${p}${I} params: ${JSON.stringify(a,c)}`),N.addFailedEvent({key:h,error:p}),p}})}var Ga=s=>J((i,e)=>function(t,r){return f(this,null,function*(){let o=this._plugins.get(t);if(!o)throw this._log.error(`plugin ${String(t)} is not found`),new P({code:U.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(oe(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new P({code:U.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return $a.call(this,o.getValidateRule(s),[r],e,"TRTC"),i.call(this,o,r)})});var Wa=0,Vl=class{constructor(i,e){d(this,"player");d(this,"publisher");d(this,"mixInput");this.mixInput=new _s(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 vs(s,i){if(i&&typeof i!="function")throw new P({code:U.INVALID_PARAMETER,message:`start audioMixer plugin: param ${s} should be a function.`})}var ni=class ni{constructor(i){this.core=i;d(this,"log");d(this,"mixedMusicMap",new Map);d(this,"cacheMusicMap",new Map);Wa=Wa+1,this.log=i.log.createChild({id:`${this.getAlias()}${Wa}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Wa}`),this.core=i}getName(){return ni.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return ni.startValidateRule;case"update":return ni.updateValidateRule;case"stop":return ni.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:r}=i;if(this.mixedMusicMap.has(t))return;let o=this.cacheMusicMap.get(t);o?i.url?o.reset():(o.mixInput.replaceSource(i.track),o.mixInput.connect()):(o=new Vl(i,e.audioManager),this.cacheMusicMap.set(t,o)),o.updateListener(i),o.updateSettings(i),yield o.play(),this.mixedMusicMap.set(t,o),this.log.info(`start mix audio track ${t} success.`),N.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return f(this,null,function*(){let{id:e,operation:t,seekFrom:r,playbackRate:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),g(t)||n.setOperation(t),g(r)||n.seek(r),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:r,playbackRate:o,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:l,onEnded:h}=i;e&&N.addCount({key:502711}),t&&N.addCount({key:502703}),r&&N.addCount({key:502704}),o&&N.addCount({key:502705}),n&&N.addCount({key:502706}),a&&N.addCount({key:502707}),typeof c!="function"&&N.addCount({key:502709}),typeof h!="function"&&N.addCount({key:502710}),typeof l!="function"&&N.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()}};d(ni,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let r=i.url.split("?")[0],o=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=o.indexOf(n)>=0,c=r.startsWith("blob"),l=r.startsWith("data");if(!(a||c||l))throw new P({code:U.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new P({code:U.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});vs("onTimeUpdate",i.onTimeUpdate),vs("onEnded",i.onEnded),vs("onDurationChange",i.onDurationChange)}}),d(ni,"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){vs("onTimeUpdate",i.onTimeUpdate),vs("onEnded",i.onEnded),vs("onDurationChange",i.onDurationChange)}}),d(ni,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),d(ni,"Name","AudioMixer");var Ja=ni;var qa=0,Bl,wi=class wi{constructor(i){this.core=i;d(this,"log");d(this,"audioContext",Fe());d(this,"workletNode");d(this,"mixNode");qa=qa+1,this.log=i.log.createChild({id:`${this.getAlias()}${qa}`}),this.log.info(`[aec] created id=${this.getAlias()}${qa}`),i.assetsPath&&this.preload(`${i.assetsPath}/aec-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,r,o){if(!i.room.audioManager.hasAudioTrack)throw new P({code:U.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return Bl||(Bl=this.doPreload(i)),Bl}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield bi(this.audioContext,t)}finally{URL.revokeObjectURL(t)}})}getName(){return wi.Name}getAlias(){return"aec"}getGroup(){return"aec"}getValidateRule(i){switch(i){case"start":return wi.startValidateRule(this.core);case"update":return wi.updateValidateRule;case"stop":return wi.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;if(yield this.preload(`${i.assetsPath}/aec-wasm.js`),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:r,sign:o,status:n,message:a}=yield aT(k(v({},i),{timestamp:t}));if(!r)throw this.log.info(`aec: ${i.userId} auth result: ${r}. Message: ${a}`),new P({code:U.INVALID_PARAMETER,message:a});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-echo-cancellation-processor",{numberOfInputs:2,numberOfOutputs:1,channelCount:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:t,sign:o,status:n}}),this.workletNode.port.postMessage({type:"debug",data:{enable:!0}}),this.workletNode.port.onmessage=c=>{let{type:l,value:h}=c.data;switch(l){case"cost":h<10?this.log.debug(`cost ${h}`):h>=10&&h<20?this.log.info(`cost ${h}`):h>=20&&this.log.warn(`cost ${h}`);return;case"debug":E.emit("265",{room:e,data:h});return}}}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=(i==null?void 0:i.gain)||1),this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addAEC(this.workletNode,this.mixNode)})}update(i){return f(this,null,function*(){this.workletNode&&this.workletNode.port.postMessage({type:i.command,data:i.data})})}stop(){return f(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeAEC(this.workletNode)})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};d(wi,"updateValidateRule",{type:"object"}),d(wi,"stopValidateRule",{type:"object"}),d(wi,"Name","AEC");var ja=wi;function nT(s,i=m.MAIN){return`https://${mt[i]||xr(s,i)}/api/v1/audioAiAuth`}function aT(r){return f(this,arguments,function*({sdkAppId:s,userId:i,userSig:e,timestamp:t}){let n=`${nT(s)}?sdkAppId=${s}&userId=${i}&userSig=${e}×tamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:l,sign:h,status:u}}=yield a.json();if(u==="1")return{auth:!0,sign:h,status:u,message:l};let p="Init RTCAEC 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:u,message:l?`${p} Reason: ${l}. ${_}`:`${p}, ${_}`}})}var Xa=0,Fl,Ui=class Ui{constructor(i){this.core=i;d(this,"log");d(this,"audioContext",Fe("denoiser"));d(this,"workletNode");Xa=Xa+1,this.log=i.log.createChild({id:`${this.getAlias()}${Xa}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${Xa}`),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,r,o){if(!i.room.audioManager.hasAudioTrack)throw new P({code:U.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return Fl||(Fl=this.doPreload(i)),Fl}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield bi(this.audioContext,t)}finally{URL.revokeObjectURL(t)}})}getName(){return Ui.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return Ui.startValidateRule(this.core);case"update":return Ui.updateValidateRule;case"stop":return Ui.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:r,sign:o,status:n,message:a}=yield cT(k(v({},i),{timestamp:t}));if(!r)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${r}. Message: ${a}`),new P({code:U.INVALID_PARAMETER,message:a});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:t,sign:o,status:n}}),this.workletNode.port.onmessage=c=>{let{data:l}=c;l.type==="cost"&&this.log.debug(`[RTCAIDenoiser] ${l.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(){this.workletNode&&(this.workletNode.port.onmessage=null)}};d(Ui,"updateValidateRule",{type:"object"}),d(Ui,"stopValidateRule",{type:"object"}),d(Ui,"Name","AIDenoiser");var Qa=Ui;function dT(s,i=m.MAIN){return`https://${mt[i]||xr(s,i)}/api/v1/audioAiAuth`}function cT(r){return f(this,arguments,function*({sdkAppId:s,userId:i,userSig:e,timestamp:t}){let n=`${dT(s)}?sdkAppId=${s}&userId=${i}&userSig=${e}×tamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:l,sign:h,status:u}}=yield a.json();if(u==="1")return{auth:!0,sign:h,status:u,message:l};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:u,message:l?`${p} Reason: ${l}. ${_}`:`${p}, ${_}`}})}var km=Pe(je(),1);var Hl=class extends km.EventEmitter{constructor(){super();d(this,"observer");d(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return f(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!pe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){ee.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,r=e[e.length-1];this.state=r.state,(this.stateNum>3||t>3)&&C.info(`${r.source}: ${r.state}`),this.emit("state-changed",{type:r.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){ee.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},lT=new Hl,$l=lT;function Gl([s,i]){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,o=[];o.push(0,0,0,1,6,s);for(let a=0;a<t;a++)o.push(255);o.push(r);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Di(new DataView(new Uint8Array(o).buffer),!0)}function Wl(s){return s.type==="empty"||s.data.byteLength===0}function Jl(s){return s.getInt32(0)===1&&s.getInt8(4)===6}function ql(s){let i=0,e=0,t=new DataView(s);for(let r=0;r<s.byteLength;r++)switch(t.getUint8(r)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function jl({frame:s,seiMessageList:i}){if(!i||i.length===0||s.data.byteLength===0)return s;let t=9-ql(s.data);if(t<=0)return s;let r=i.splice(0,t).reverse().map(Gl),o=r.reduce((h,u)=>h+u.dataView.byteLength,0),n=new ArrayBuffer(o+s.data.byteLength),a=new DataView(n),c=new DataView(s.data),l=0;for(let h=0;h<r.length;h++)for(let u=0;u<r[h].dataView.byteLength;u++)a.setInt8(l++,r[h].dataView.getInt8(u));for(let h=0;h<s.data.byteLength;h++)a.setInt8(l++,c.getInt8(h));return s.data=n,s}function Xl({frame:s,onSEI:i}){try{let e=new DataView(s.data);if(Wl(s)||!Jl(e))return s;let t=[],r=0,o=-1,n=-1;for(let a=0;a<s.data.byteLength;a++){let c=e.getUint8(a);if(c===0)r++;else if(c===1){if(r===2||r===3){let l=a-r;if(o===-1?o=l:n===-1&&(n=l,t.push(new Di(new DataView(e.buffer.slice(o,n)))),o=l,n=-1),!(e.getUint8(a+1)===6)){s.data=e.buffer.slice(l);break}}r=0}else r=0}i==null||i(t.reverse())}catch(e){}return s}var Ql=0,Jo=class Jo{constructor(i){this.core=i;d(this,"log");d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_subStreamSeiMessageList",[]);Ql++,this.log=i.log.createChild({id:`${this.getAlias()}${Ql}`}),this.log.info(`[sei] created id=${this.getAlias()}${Ql}`),this.core=i,this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode({frame:i,mediaType:e}){try{let t=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList;return jl({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return Xl({frame:i,onSEI:t=>{t.forEach(r=>{this.core.trtc.emit(M.SEI_MESSAGE,{seiPayloadType:r.seiPayloadType,data:r.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:Ri?this.encode:jl,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:Ri?this.decode:Xl,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:i,options:e}){var o;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(o=this.core.room.scriptTransformWorker)==null||o.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return Jo.Name}getAlias(){return"sei"}getGroup(){return"sei"}};d(Jo,"autoStart",!0),d(Jo,"Name","SEI");var za=Jo;function zl({frame:s,onDump:i}){return i==null||i(),s}function Yl({frame:s,onDump:i}){return i==null||i(),s}var Mm={"play() error: NotAllowedError:":{tips:s=>s.includes("main <video>")||s.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:s=>s.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:s=>s.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:`The remote stream audio playback is paused, which usually has two possibilities:
|
|
56
|
+
${r.stack}`),!1}},s};var Ns=new WeakMap;function vm(s){let i=Ns.get(s);i&&(i.forEach(e=>clearTimeout(e)),Ns.delete(s))}function Dm(s,i){return J((e,t)=>function(...r){let o=Ns.get(this);o||(o=new Map,Ns.set(this,o));let n=i(...r),a=o.get(n);if(!a||a<=0){e.apply(this,r);let c=setTimeout(()=>{var l;(l=Ns.get(this))==null||l.delete(n)},s);o.set(n,c)}else{clearTimeout(a);let c=window.setTimeout(()=>{var l;e.apply(this,r),(l=Ns.get(this))==null||l.delete(n)},s);o.set(n,c)}})}var Om="5.9.2-beta.15";function Je(...s){return J((i,e)=>function(...t){try{$a.call(this,s,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function Ul(...s){return J((i,e)=>function(...t){try{$a.call(this,s,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function $a(s,i,e,t){if(Te(s))for(let r=0;r<s.length;r++)Ha.call(this,{rule:s[r],value:i[r],key:s[r].name,fnName:e,className:t});else Ha.call(this,{rule:s,value:i[0],key:s.name,fnName:e,className:t})}function Ha({rule:s,value:i,key:e,fnName:t,className:r}){function o(c){return{code:U.INVALID_PARAMETER,extraCode:c,fnName:t,messageParams:{key:e,rule:s,value:i}}}if(g(i)){if(s.required)throw new P(o(5001));if(g(s.defaultValue)){oe(s.validate)&&s.validate.call(this,i,e,t,r,this);return}i=s.defaultValue}if(Array.isArray(s.type)){let c=!1;for(let l=0;l<s.type.length;l++)s.type[l]===null&&i===null&&(c=!0),oe(s.type[l])&&i instanceof s.type[l]&&(c=!0),K(s.type[l])&&Ae(i)===s.type[l].toLowerCase()&&(c=!0);if(!c)throw new P({code:U.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:s.type.map(l=>qr(l)?Ys(l):K(l)?l:Ae(l))},value:i}})}else if(!g(s.type)&&Ae(i)!==s.type)throw new P(o(5002));if(s.allowEmpty===!1){let c=Y(i)&&(i===0||Number.isNaN(i)),l=K(i)&&i.trim()==="";if(c||l)throw new P(o(5003))}if(s.notLessThanZero&&Y(i)&&i<0)throw new P(o(5006));if(!g(s.min)&&Y(i)&&i<s.min)throw new P(o(5007));if(!g(s.max)&&Y(i)&&i>s.max)throw new P(o(5008));if(K(s.instanceOf)){if(!i||i._name!==s.instanceOf)throw new P(o(5004))}else if(oe(s.instanceOf)&&!(i instanceof s.instanceOf))throw new P(o(5004));if(Array.isArray(s.values)&&!s.values.includes(i))throw new P(o(5005));let{properties:n}=s;Ze(n)&&$t(i)&&Object.keys(n).forEach(c=>{Ha.call(this,{rule:n[c],value:i&&i[c],key:`${c}`,fnName:t,className:r})});let{arrayItem:a}=s;Ze(a)&&Te(i)&&i.forEach((c,l)=>{Ha.call(this,{rule:a,value:c,key:`${e}[${l}]`,fnName:t,className:r})}),oe(s.validate)&&s.validate.call(this,i,e,t,r,this)}function ue(s={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r}=s;return J((o,n)=>function(...a){var u;function c(p,_,I){if(I&&I.includes(p))return"hided";if(e){let R=e(...a);if(a[R.argIndex]===_)return R.value}if(_===a||p in a)return _;try{return _ instanceof HTMLElement?`id: ${_.id} type:${Ae(_)}`:(JSON.stringify(_),_)}catch(R){return`type:${Ae(_)}`}}let l=this._log||C;if(r!=null&&r(...a))return o.apply(this,a);a.length>0?l.info(`${n}() ${JSON.stringify(a,(p,_)=>c(p,_,["userSig","privateMapKey"]))}`):l.info(`${n}()`);let h=t?t(...a):qn[n];try{let p=o.apply(this,a),_=L();return Wi(p)?p.then(I=>(l.info(`${n}() success ${i.call(this,...a)}`),N.addSuccessEvent({key:h,cost:L()-_}),I)).catch(I=>{var G;I=P.convertFrom.call(this,I,n,a.length===1?a[0]:a);let R=I.extraCode||I.code,D=(G=I.message)!=null&&G.includes(R)?"":` code:${R}`;throw l.error(`${n}() failed ${i.call(this,...a)} ${I}${D} params: ${JSON.stringify(a,c)}`),N.addFailedEvent({key:h,error:I}),I}):(N.addSuccessEvent({key:h}),p)}catch(p){p=P.convertFrom.call(this,p,n);let _=p.extraCode||p.code,I=(u=p.message)!=null&&u.includes(_)?"":` code:${_}`;throw l.error(`${n}() failed ${p}${I} params: ${JSON.stringify(a,c)}`),N.addFailedEvent({key:h,error:p}),p}})}var Ga=s=>J((i,e)=>function(t,r){return f(this,null,function*(){let o=this._plugins.get(t);if(!o)throw this._log.error(`plugin ${String(t)} is not found`),new P({code:U.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(oe(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new P({code:U.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return $a.call(this,o.getValidateRule(s),[r],e,"TRTC"),i.call(this,o,r)})});var Wa=0,Vl=class{constructor(i,e){d(this,"player");d(this,"publisher");d(this,"mixInput");this.mixInput=new _s(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 vs(s,i){if(i&&typeof i!="function")throw new P({code:U.INVALID_PARAMETER,message:`start audioMixer plugin: param ${s} should be a function.`})}var ni=class ni{constructor(i){this.core=i;d(this,"log");d(this,"mixedMusicMap",new Map);d(this,"cacheMusicMap",new Map);Wa=Wa+1,this.log=i.log.createChild({id:`${this.getAlias()}${Wa}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Wa}`),this.core=i}getName(){return ni.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return ni.startValidateRule;case"update":return ni.updateValidateRule;case"stop":return ni.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:r}=i;if(this.mixedMusicMap.has(t))return;let o=this.cacheMusicMap.get(t);o?i.url?o.reset():(o.mixInput.replaceSource(i.track),o.mixInput.connect()):(o=new Vl(i,e.audioManager),this.cacheMusicMap.set(t,o)),o.updateListener(i),o.updateSettings(i),yield o.play(),this.mixedMusicMap.set(t,o),this.log.info(`start mix audio track ${t} success.`),N.addEnum({key:502700,value:3}),this.kvUpload(i)})}update(i){return f(this,null,function*(){let{id:e,operation:t,seekFrom:r,playbackRate:o}=i;this.log.info(`update music source, ${JSON.stringify(i)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(i),n.updateListener(i),g(t)||n.setOperation(t),g(r)||n.seek(r),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:r,playbackRate:o,operation:n,seekFrom:a,onTimeUpdate:c,onDurationChange:l,onEnded:h}=i;e&&N.addCount({key:502711}),t&&N.addCount({key:502703}),r&&N.addCount({key:502704}),o&&N.addCount({key:502705}),n&&N.addCount({key:502706}),a&&N.addCount({key:502707}),typeof c!="function"&&N.addCount({key:502709}),typeof h!="function"&&N.addCount({key:502710}),typeof l!="function"&&N.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()}};d(ni,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let r=i.url.split("?")[0],o=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=o.indexOf(n)>=0,c=r.startsWith("blob"),l=r.startsWith("data");if(!(a||c||l))throw new P({code:U.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new P({code:U.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});vs("onTimeUpdate",i.onTimeUpdate),vs("onEnded",i.onEnded),vs("onDurationChange",i.onDurationChange)}}),d(ni,"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){vs("onTimeUpdate",i.onTimeUpdate),vs("onEnded",i.onEnded),vs("onDurationChange",i.onDurationChange)}}),d(ni,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),d(ni,"Name","AudioMixer");var Ja=ni;var qa=0,Bl,wi=class wi{constructor(i){this.core=i;d(this,"log");d(this,"audioContext",He());d(this,"workletNode");d(this,"mixNode");d(this,"muteNode");qa=qa+1,this.log=i.log.createChild({id:`${this.getAlias()}${qa}`}),this.log.info(`[aec] created id=${this.getAlias()}${qa}`),i.assetsPath&&this.preload(`${i.assetsPath}/aec-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,r,o){if(!i.room.audioManager.hasAudioTrack)throw new P({code:U.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return Bl||(Bl=this.doPreload(i)),Bl}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield bi(this.audioContext,t)}catch(r){this.log.error(`preload aec failed. ${r}`)}finally{URL.revokeObjectURL(t)}})}getName(){return wi.Name}getAlias(){return"aec"}getGroup(){return"aec"}getValidateRule(i){switch(i){case"start":return wi.startValidateRule(this.core);case"update":return wi.updateValidateRule;case"stop":return wi.stopValidateRule}}start(i){return f(this,null,function*(){let{room:e}=this.core;if(yield this.preload(`${i.assetsPath}/aec-wasm.js`),!this.workletNode){let t=String(Date.now()).slice(0,-3),{auth:r,sign:o,status:n,message:a}=yield aT(k(v({},i),{timestamp:t}));if(!r)throw this.log.info(`aec: ${i.userId} auth result: ${r}. Message: ${a}`),new P({code:U.INVALID_PARAMETER,message:a});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-echo-cancellation-processor",{numberOfInputs:2,numberOfOutputs:1,channelCount:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:t,sign:o,status:n}}),this.workletNode.port.postMessage({type:"debug",data:{enable:!0}}),this.workletNode.port.onmessage=c=>{let{type:l,value:h}=c.data;switch(l){case"cost":h<10?this.log.debug(`cost ${h}`):h>=10&&h<20?this.log.info(`cost ${h}`):h>=20&&this.log.warn(`cost ${h}`);return;case"debug":E.emit("265",{room:e,data:h});return}}}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=(i==null?void 0:i.gain)||1),this.muteNode||(this.muteNode=this.audioContext.createConstantSource(),this.muteNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.muteNode.start()),this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addAEC(this.workletNode,this.mixNode,this.muteNode)})}update(i){return f(this,null,function*(){this.workletNode&&this.workletNode.port.postMessage({type:i.command,data:i.data})})}stop(){return f(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeAEC(this.workletNode)})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};d(wi,"updateValidateRule",{type:"object"}),d(wi,"stopValidateRule",{type:"object"}),d(wi,"Name","AEC");var ja=wi;function nT(s,i=m.MAIN){return`https://${mt[i]||xr(s,i)}/api/v1/audioAiAuth`}function aT(r){return f(this,arguments,function*({sdkAppId:s,userId:i,userSig:e,timestamp:t}){let n=`${nT(s)}?sdkAppId=${s}&userId=${i}&userSig=${e}×tamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:l,sign:h,status:u}}=yield a.json();if(u==="1")return{auth:!0,sign:h,status:u,message:l};let p="Init RTCAEC 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:u,message:l?`${p} Reason: ${l}. ${_}`:`${p}, ${_}`}})}var Xa=0,Fl,Ui=class Ui{constructor(i){this.core=i;d(this,"log");d(this,"audioContext",He("denoiser"));d(this,"workletNode");Xa=Xa+1,this.log=i.log.createChild({id:`${this.getAlias()}${Xa}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${Xa}`),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,r,o){if(!i.room.audioManager.hasAudioTrack)throw new P({code:U.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return Fl||(Fl=this.doPreload(i)),Fl}doPreload(i){return f(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield bi(this.audioContext,t)}finally{URL.revokeObjectURL(t)}})}getName(){return Ui.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return Ui.startValidateRule(this.core);case"update":return Ui.updateValidateRule;case"stop":return Ui.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:r,sign:o,status:n,message:a}=yield cT(k(v({},i),{timestamp:t}));if(!r)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${r}. Message: ${a}`),new P({code:U.INVALID_PARAMETER,message:a});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(i.sdkAppId),userId:i.userId,timestamp:t,sign:o,status:n}}),this.workletNode.port.onmessage=c=>{let{data:l}=c;l.type==="cost"&&this.log.debug(`[RTCAIDenoiser] ${l.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(){this.workletNode&&(this.workletNode.port.onmessage=null)}};d(Ui,"updateValidateRule",{type:"object"}),d(Ui,"stopValidateRule",{type:"object"}),d(Ui,"Name","AIDenoiser");var Qa=Ui;function dT(s,i=m.MAIN){return`https://${mt[i]||xr(s,i)}/api/v1/audioAiAuth`}function cT(r){return f(this,arguments,function*({sdkAppId:s,userId:i,userSig:e,timestamp:t}){let n=`${dT(s)}?sdkAppId=${s}&userId=${i}&userSig=${e}×tamp=${t}`,a=yield fetch(n),{data:{errCode:c,errMsg:l,sign:h,status:u}}=yield a.json();if(u==="1")return{auth:!0,sign:h,status:u,message:l};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:u,message:l?`${p} Reason: ${l}. ${_}`:`${p}, ${_}`}})}var km=Pe(je(),1);var Hl=class extends km.EventEmitter{constructor(){super();d(this,"observer");d(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return f(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!pe&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){ee.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let t=this.stateNum,r=e[e.length-1];this.state=r.state,(this.stateNum>3||t>3)&&C.info(`${r.source}: ${r.state}`),this.emit("state-changed",{type:r.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(t){ee.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},lT=new Hl,$l=lT;function Gl([s,i]){let e=i.byteLength,t=parseInt(String(e/255),10),r=e%255,o=[];o.push(0,0,0,1,6,s);for(let a=0;a<t;a++)o.push(255);o.push(r);let n=new DataView(i);return o.push(...new Uint8Array(n.buffer)),o.push(128),new Di(new DataView(new Uint8Array(o).buffer),!0)}function Wl(s){return s.type==="empty"||s.data.byteLength===0}function Jl(s){return s.getInt32(0)===1&&s.getInt8(4)===6}function ql(s){let i=0,e=0,t=new DataView(s);for(let r=0;r<s.byteLength;r++)switch(t.getUint8(r)){case 0:i++;break;case 1:(i===2||i===3)&&e++,i=0;break;default:i=0;break}return e}function jl({frame:s,seiMessageList:i}){if(!i||i.length===0||s.data.byteLength===0)return s;let t=9-ql(s.data);if(t<=0)return s;let r=i.splice(0,t).reverse().map(Gl),o=r.reduce((h,u)=>h+u.dataView.byteLength,0),n=new ArrayBuffer(o+s.data.byteLength),a=new DataView(n),c=new DataView(s.data),l=0;for(let h=0;h<r.length;h++)for(let u=0;u<r[h].dataView.byteLength;u++)a.setInt8(l++,r[h].dataView.getInt8(u));for(let h=0;h<s.data.byteLength;h++)a.setInt8(l++,c.getInt8(h));return s.data=n,s}function Xl({frame:s,onSEI:i}){try{let e=new DataView(s.data);if(Wl(s)||!Jl(e))return s;let t=[],r=0,o=-1,n=-1;for(let a=0;a<s.data.byteLength;a++){let c=e.getUint8(a);if(c===0)r++;else if(c===1){if(r===2||r===3){let l=a-r;if(o===-1?o=l:n===-1&&(n=l,t.push(new Di(new DataView(e.buffer.slice(o,n)))),o=l,n=-1),!(e.getUint8(a+1)===6)){s.data=e.buffer.slice(l);break}}r=0}else r=0}i==null||i(t.reverse())}catch(e){}return s}var Ql=0,Jo=class Jo{constructor(i){this.core=i;d(this,"log");d(this,"_seiMessageList",[]);d(this,"_smallSeiMessageList",[]);d(this,"_subStreamSeiMessageList",[]);Ql++,this.log=i.log.createChild({id:`${this.getAlias()}${Ql}`}),this.log.info(`[sei] created id=${this.getAlias()}${Ql}`),this.core=i,this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode({frame:i,mediaType:e}){try{let t=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList;return jl({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return Xl({frame:i,onSEI:t=>{t.forEach(r=>{this.core.trtc.emit(M.SEI_MESSAGE,{seiPayloadType:r.seiPayloadType,data:r.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(i){switch(i){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:Ri?this.encode:jl,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:Ri?this.decode:Xl,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:i,options:e}){var o;let t=[e.seiPayloadType,i],r=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(t):(this._seiMessageList.push(t),r&&this._smallSeiMessageList.push(t)),(o=this.core.room.scriptTransformWorker)==null||o.postMessage({type:"sei",data:t,isMain:!e.toSubStream,small:r})}getName(){return Jo.Name}getAlias(){return"sei"}getGroup(){return"sei"}};d(Jo,"autoStart",!0),d(Jo,"Name","SEI");var za=Jo;function zl({frame:s,onDump:i}){return i==null||i(),s}function Yl({frame:s,onDump:i}){return i==null||i(),s}var Mm={"play() error: NotAllowedError:":{tips:s=>s.includes("main <video>")||s.includes("main <audio>")?"Remote stream auto play is restricted and playback fails":"Local stream playback failure, generally only occurs in Android WeChat devices, no need to handle",color:"red",class:"red"},"updateStream() try to recover local stream":{tips:"Device acquisition exception, automatic recovery is in progress"},"updateStream() recover local stream successfully":{tips:"Device acquisition exception, automatic recovery is successful"},"updateStream() failed to recover local stream":{tips:"Device acquisition exception, automatic recovery failed"},"main stream - video track is muted":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is muted":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is muted":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unable to provide media output":{tips:"Indicates that the received video data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - audio track is unable to provide media output":{tips:"Indicates that the received audio data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"auxiliary stream - video track is unable to provide media output":{tips:"Indicates that the received screen sharing data is not enough for playback. This is usually caused by network reasons. When enough data is received for playback, the state will change to unmuted."},"main stream - video track is unmuted":{tips:"Received enough playback video data"},"main stream - audio track is unmuted":{tips:"Received enough playback audio data"},"auxiliary stream - video track is unmuted":{tips:"Received enough playback screen sharing data"},"main stream - audio player track is ended":{tips:"Remote audio track stopped"},"main stream - video player track is ended":{tips:"Remote video track stopped"},"auxiliary stream - video player track is ended":{tips:"Received enough playback screen sharing data"},"stream - video track is muted":{tips:"Camera capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"stream - video track is unable to provide media output":{tips:"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked, and the customer needs to re-acquire. SDK v4.11.4+ will automatically resume acquisition without customer intervention",color:"orange"},"video track is unable to provide media output":{tips:s=>s.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"The camera acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"video player track is ended":{tips:"The camera acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"stream - audio track is muted":{tips:"Microphone capture is paused, usually due to the device being occupied by other applications or the browser media permission being revoked. The client needs to re-capture.",color:"orange"},"audio track is unable to provide media output":{tips:s=>s.includes("\u2193")?"The remote track is temporarily unable to decode data, which may be caused by network fluctuations":"Microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio track is unable to provide media output":{tips:"The microphone acquisition is paused, usually because the device is occupied by other applications or the browser media permissions are revoked. The SDK will automatically resume the acquisition.",color:"orange"},"stream - audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"audio player track is ended":{tips:"The microphone acquisition stops, usually because the device is unplugged. In this case, the SDK will automatically resume acquisition, and the access side does not need to handle it. It may also be caused by the device being occupied by other applications or the browser media permissions being reclaimed. It is recommended to remind the user to re-acquire on the page."},"is adding audio track to current published local stream":{tips:"add audio track",color:"orange"},"is removing audio track from current published local stream":{tips:"remove audio track",color:"orange"},"is removing video track from current published local stream":{tips:"remove video track",color:"orange"},"is adding video track to current published local stream":{tips:"add video track",color:"orange"},"is replacing audio track to current published local main stream":{tips:"replace audio track",color:"orange"},"is replacing video track to current published local main stream":{tips:"replace video track",color:"orange"},"downlink network quality change":{tips:"Downstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"uplink network quality change":{tips:"Upstream network quality change: 1: excellent, 2: good, 3: average, 4: poor, 5: extremely poor"},"localStream mute video":{tips:"mute upstream video stream",color:"orange"},"localStream unmute video":{tips:"unmute upstream video stream",color:"orange"},"localStream mute audio":{tips:"mute upstream audio stream",color:"orange"},"localStream unmute audio":{tips:"unmute upstream audio stream",color:"orange"},"black detected":{tips:"Detect black screen, which means fps = 0. It is usually caused by network, and the network will be recovered after a while. If the network is normal but has not been restored, it is an abnormal situation."},'main stream start to play with options: {"muted":true}':{tips:"Play the remote stream in silent mode. Generally, the remote stream does not need to be played in silent mode. You need to confirm whether the parameters passed in the client stream.play API call are correct.",color:"orange"},"main stream - audio player is starting playing":{tips:"Remote stream audio playback success",color:"#0dd90d",class:"success"},"main stream - video player is starting playing":{tips:"Remote stream video playback success",color:"#0dd90d",class:"success"},"video player is playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"audio player is playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"stream - video player is starting playing":{tips:"Local video playback success",color:"#0dd90d",class:"success"},"stream - audio player is starting playing":{tips:"Local audio playback success",color:"#0dd90d",class:"success"},"switch camera success":{tips:"Switch camera success",color:"#0dd90d",class:"success"},"switch microphone success":{tips:"Switch microphone success",color:"#0dd90d",class:"success"},gotStream:{tips:"Local stream capture success"},"local stream is published successfully":{tips:"Publish success",color:"#0dd90d",class:"success"},"encoderImplementation change to OpenH264":{tips:"Use software encoding"},"encoderImplementation change to ExternalEncoder":{tips:"Use hardware encoding"},"getUserMedia with constraints":{tips:"Start media (camera/microphone) capture"},"getDisplayMedia with constraints":{tips:"Start screen sharing capture"},"client-banned":{tips:"Kicked out of the room",color:"red",class:"red",textColor:"#fff"},user_timeout:{tips:"The backend is too long without receiving SDK heartbeat, which is usually caused by the JS thread being blocked for a long time. If the reproduction probability is high, the application browser Performance tool analyzes where the JS thread is blocked.",color:"red",class:"red",textColor:"#fff"},"schedule failed":{tips:"Signaling request failed, does not affect the normal room entry process, SDK will connect to the default signaling domain."},"updateStream() video flag is true, but no camera detected, set video to false":{tips:"When trying to resume camera acquisition, the camera acquisition is not resumed because it is detected that there is no camera.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to bandwidth":{tips:"bandwidth estimation is not enough to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"qualityLimitationReason change to cpu":{tips:"cpu load is too high to limit the quality of the encoding, which may cause the code rate, frame rate, and resolution to be lowered.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: hidden":{tips:"User page switched to backend, in mobile devices, this will cause the device to pause the capture, and it will be restored when the user switches backend to the frontend.",color:"orange",class:"orange",textColor:"#fff"},"visibility change: visible":{tips:"User page switched to frontend",color:"orange",class:"orange",textColor:"#fff"},"main stream - audio player is paused":{tips:`The remote stream audio playback is paused, which usually has two possibilities:
|
|
57
57
|
1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.
|
|
58
58
|
2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},"main stream - video player is paused":{tips:`The remote stream video playback is paused, which usually has two possibilities:
|
|
59
59
|
1. The business side passes in the div tag container for playing audio and video to be removed by the business side from the DOM.
|
|
60
|
-
2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},'"displaySurface":"window"':{tips:"Screen sharing captures the application window",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"monitor"':{tips:"Screen sharing captures the entire screen",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"browser"':{tips:"Screen sharing captures a certain tab page",color:"blue",class:"blue",textColor:"#fff"},updateMediaSettings:{tips:"The resolution and frame rate below are the actual resolution and frame rate captured",color:"blue",class:"blue",textColor:"#fff"},"main stream start to play with":{tips:"Call remoteStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"stream start to play with":{tips:"Call localStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"main setAudioVolume to 0":{tips:"Business side calls remoteStream.setAudioVolume(0) interface to set the playback volume to 0, which will cause the playback to be silent",color:"orange",class:"orange",textColor:"#fff"},"screen sharing was stopped because the video track is ended":{tips:"Screen sharing capture stopped, possible reasons: user clicks the stop button, the window/page shared by the user is closed, etc.",color:"orange",class:"orange",textColor:"#fff"},"Join() => joining room":{tips:"Call client.join interface",color:"blue",class:"blue",textColor:"#fff"},"publish() => publishing local stream":{tips:"Call client.publish interface",color:"blue",class:"blue",textColor:"#fff"},"subscribe() => subscribe to":{tips:"Call client.subscribe interface",color:"blue",class:"blue",textColor:"#fff"},"switchRole() => switch role":{tips:"Call client.switchRole interface",color:"blue",class:"blue",textColor:"#fff"}};["enterRoom","exitRoom","switchRole","destroy","startLocalAudio","updateLocalAudio","stopLocalAudio","startLocalVideo","updateLocalVideo","stopLocalVideo","startScreenShare","updateScreenShare","stopScreenShare","startRemoteVideo","updateRemoteVideo","stopRemoteVideo","muteRemoteAudio","setRemoteAudioVolume"].forEach(s=>{Mm[`${s}()`]={tips:`Call trtc.${s}`,color:"blue",class:"blue",textColor:"#fff"}});var aM=Object.keys(Mm);var uT=0,Ya,Ds=class Ds{constructor(i){this.core=i;d(this,"_core");d(this,"log");d(this,"dumpLocalVideoMap",{});d(this,"dumpRemoteVideoMap",{});d(this,"dialog");this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${++uT}`}),this.log.info("created")}getName(){return Ds.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(i){switch(i){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return f(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog(),this.addVideoProcessor())})}update(){}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return f(this,null,function*(){try{if(Ya)yield Ya;else{let i=Date.now();Ya=this.loadScript(`https://web.sdk.qcloud.com/trtc/webrtc/assets/debug/debug-dialog@${Re}.js`),yield Ya,this.log.info(`download debug dialog script cost: ${Date.now()-i}ms`)}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(i){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(i))}})}closeDebugDiaLog(){var i;(i=this.dialog)==null||i.closeDialog(),this.dialog=null}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):zl,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):Yl,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo({frame:i,mediaType:e}){return zl({frame:i,onDump:()=>{if(!e)return;let t=e===2?"sub":"main",r=this.dumpLocalVideoMap[t];r&&(r.data.push(i.data),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}})}decodeVideo({frame:i,track:e}){return Yl({frame:i,onDump:()=>{if(!e)return;let t=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];t&&(t.data.push(i.data),t.duration>0&&Date.now()-t.startTimestamp>t.duration*1e3&&t.onDumpEnd())}})}loadScript(i){return new Promise((e,t)=>{this.log.info(`loading debug dialog from ${i}`);let r=document.createElement("script");r.type="text/javascript",r.onload=e,r.onerror=t,r.crossOrigin="anonymous",r.src=i,document.head.append?document.head.append(r):document.getElementsByTagName("head")[0].appendChild(r)})}};d(Ds,"Name","Debug"),d(Ds,"autoStart",!0),y([tt({settings:{timeout:3e3,retries:3},onError(i,e,t){var r;(r=i==null?void 0:i.message)!=null&&r.includes("timeout")?e():t(i)}})],Ds.prototype,"loadScript",1);var Ka=Ds;var Lm=s=>{switch(s){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},Za=class{constructor(i,e,t){d(this,"trackDoneOB");d(this,"startOB");d(this,"stopOB");d(this,"inputFrameCount",0);d(this,"decodedFrameCount",0);d(this,"type","auto");d(this,"config");d(this,"decoder");d(this,"_decodeSink");let{kvStatManager:r,trtc:o}=i;this.config=t.config,this.trackDoneOB=Ie(e,Q.INIT),this.stopOB=ot(this.trackDoneOB),this.startOB=ot(),t.type==="auto"?this.type="webCodecs":this.type=t.type;let n=ot(),a=c=>{let l=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),_e(l,we(this.stopOB),Ne(()=>{},h=>{e.log.error(h),r.addFailedEvent({key:Lm(this.type),error:h}),c>4?this.startOB.error(h):this.startOB.next(c+1)})),_e(l,Li(1),Fo(Dr))};_e(this.startOB,vr(0),tr(a),we(this.stopOB),Ne(()=>{e.player.setOutput(),n.next("STARTED")},c=>{n.next("FAILED")},()=>{r.addSuccessEvent({key:Lm(this.type)}),r.addSuccessEvent({key:504702})}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.startOB.next(0)}close(i){this.stopOB.next(i)}pipe(i){return Mi()(e=>f(this,null,function*(){this._decodeSink=e,e.defer(()=>{var r;(r=this.decoder)==null||r.close()});let{type:t}=this;try{switch(t){case"webCodecs":this.decoder=new AudioDecoder({error:r=>{i.log.error(r),e.error(4)},output:r=>{this.decodedFrameCount++,e.next(r),i.player.write(r)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(r){i.log.error(r),e.error(t==="webCodecs"?2:6)}}))}decodeFrame(i){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:i.data,timestamp:i.timestamp,type:"key"}))}},hT={type:"object"},qo=class qo{constructor(i){this.core=i;d(this,"log");d(this,"contextMap",new Map);d(this,"decodeProcessorMap",new WeakMap);this.log=i.log.createChild({id:`${this.getAlias()}`})}getAlias(){return qo.Name}getGroup(i){return i.track.userId+i.track.streamType}getName(){return qo.Name}getValidateRule(i){return hT}start(i){let{track:e}=i;this.decodeProcessorMap.set(e,this.decode(i)),this.core.room.audioManager.addDecodeProcessor({processor:({frame:t,track:r})=>this.decodeProcessorMap.has(r)?this.decodeProcessorMap.get(r)({frame:t,track:r}):t,type:3})}decode(i){return({frame:e,track:t})=>{if(t!==i.track)return e;if(this.contextMap.has(t))return this.contextMap.get(t).decodeFrame(e);let r=new Za(this.core,t,i);return _e(r.trackDoneOB,Li(1),Ne(()=>{this.core.clearStarted(this,this.getGroup(i)),this.stop({track:t})})),this.contextMap.set(t,r),r.decodeFrame(e)}}stop({track:i}){let e=this.contextMap.get(i);e&&(e.close("stop"),this.contextMap.delete(i),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(i){let e=this.contextMap.get(i.track);if(e){if(i.type==="mock"){e.mock(10);return}e.close("update"),this.contextMap.set(i.track,new Za(this.core,i.track,i))}}};d(qo,"Name","TRTCAudioDecoder");var jo=qo;var Pm=0,Xo=new Set,Le=null;Ed(Om);cs.checkStorage();Nc();var mT={RtcError:P,ErrorCode:U,ErrorCodeDictionary:St},H=class H extends xm.EventEmitter{constructor(e,t){super();d(this,"_room");d(this,"_eventListened",new Set);d(this,"_localVideoTrack",null);d(this,"_localAudioTrack",null);d(this,"_localScreenTrack",null);d(this,"_localScreenAudioTrack",null);d(this,"_localVideoConfig",null);d(this,"_localScreenConfig",null);d(this,"_localAudioConfig",null);d(this,"_remoteVideoConfigMap",new Map);d(this,"_remoteAudioConfigMap",new Map);d(this,"_remoteAudioVolumeMap",new Map);d(this,"_remoteAudioMuteMap",new Map);d(this,"_mediaTrackMap",new WeakMap);d(this,"_log",C.createLogger({id:`t${++Pm}`}));d(this,"_plugins",new Map);d(this,"_networkQuality",null);d(this,"_speakerId");d(this,"_getPCMAbortCtrl");this._room=new e(v({logger:this._log,frameWorkType:H.frameWorkType},t)),this._room.videoDecodeFallbackType=t.videoDecodeFallback,this._log.debug(`TRTC.create() ${JSON.stringify(t,(r,o)=>r==="plugins"?o.map(n=>n.Name):o)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(r){return this._room.audioManager.dump(r)}}}),t.plugins&&t.plugins.forEach(r=>{this._use(r,t.assetsPath)}),this._use(Ja,t.assetsPath),this._use(ja,t.assetsPath),this._use(Qa,t.assetsPath),this._use(jo,t.assetsPath||dn),this._use(Ka),t.enableSEI&&Ro&&this._use(za),this._room.on("audio-volume",r=>{!r.find(o=>o.userId==="")&&this._localAudioTrack&&r.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),t.volumeType===1&&r.forEach(o=>{var a;let n=o.userId===""?this._localAudioTrack:(a=this.room.remotePublishedUserMap.get(o.userId))==null?void 0:a.remoteAudioTrack;n&&(o.volume=n.dbVolume)}),this.emit(M.AUDIO_VOLUME,{result:r.sort((o,n)=>n.volume-o.volume)})}),this._room.videoManager.on("error",r=>{this._log.error(new P({code:U.OPERATION_FAILED,extraCode:5504,message:r.message,originError:r}))}),this._listenEvents(),this._initActiveSpeaker(),Nm(this,"trtc")}static create(e){}static _create(e,t){fm();let r=new H(e,t||{});return Xo.add(r),r}get room(){return this._room}_listenEvents(){Be(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(M.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit(M.REMOTE_USER_EXIT,{userId:e}),this._remoteAudioVolumeMap.delete(e)}).add("banned",e=>{this._exitRoom().then(()=>{this.emit(M.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().then(()=>{this.emit(M.ERROR,P.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(M.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let t=k(v({},e),{uplinkRTT:Math.min(e.uplinkRTT,Xs),downlinkRTT:Math.min(e.downlinkRTT,Xs)});this.emit(M.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{Be(r,r).add("player-state-changed",o=>{let n=k(v({},o),{userId:e.userId});r.kind===m.VIDEO&&(n.streamType=or(r.streamType)),this.emit(r.kind===m.AUDIO?M.AUDIO_PLAY_STATE_CHANGED:M.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",o=>{o.getCode()===S.PLAY_NOT_ALLOWED&&this.emit(M.AUTOPLAY_FAILED,{userId:r.userId,resume:()=>r.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{Se(r)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:r}=t,o=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:c}=t;a||this._remoteAudioConfigMap.delete(r),c||this._remoteVideoConfigMap.delete(`${r}_main`),t.hasAuxiliary||this._remoteVideoConfigMap.delete(`${r}_sub`),n!==c&&(c?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"}),this.emit(c?M.REMOTE_VIDEO_AVAILABLE:M.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),o!==a&&(a?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:t}),this.emit(a?M.REMOTE_AUDIO_AVAILABLE:M.REMOTE_AUDIO_UNAVAILABLE,{userId:r})),e.hasAuxiliary!==t.hasAuxiliary&&(t.hasAuxiliary?this._onVideoAvailable({userId:r,streamType:"sub"}):this._onVideoUnavailable({userId:r,streamType:"sub"}),this.emit(t.hasAuxiliary?M.REMOTE_VIDEO_AVAILABLE:M.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}))}).add("sei-message",e=>{this.emit(M.SEI_MESSAGE,k(v({},e),{streamType:or(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(M.ERROR,new P({code:U.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var o,n,a,c,l,h,u;let t={2:"big",3:"small",7:"sub"},r={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((o=e.msg_down_stream_info[0])==null?void 0:o.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,Xs),upLoss:((c=this._networkQuality)==null?void 0:c.uplinkLoss)||0,downLoss:((l=this._networkQuality)==null?void 0:l.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((h=e.msg_up_stream_info.msg_audio_status)==null?void 0:h.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((u=e.msg_up_stream_info.msg_audio_status)==null?void 0:u.uint32_audio_level)||0)/_t},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)/_t},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(M.STATISTICS,r)}).add("custom-message",e=>{this.emit(M.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(M.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(M.FIRST_VIDEO_FRAME,k(v({},e),{streamType:or(e.streamType)}))}),Be(this,be).add("audioInputAdded",e=>{this.emit(M.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(M.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(M.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(M.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>f(this,null,function*(){if(this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Le&&Le.deviceId===js){let t=(yield Zi()).find(r=>r.deviceId===js);t&&Le.groupId!==t.groupId&&(Le=t,this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>f(this,null,function*(){this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield Zi())[0];if(!t||!Le||Le.groupId===t.groupId)return;let r=Le.deviceId===e.deviceId,o=Le.deviceId===js&&Le.deviceId===t.deviceId;(r||o)&&(Le=t,this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))}use(e){let t,r;"plugin"in e?(t=e.plugin,r=e.assetsPath):t=e,this._use(t,r||dn)}_use(e,t){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let o=new e(bm.call(this,{TRTC:H,room:this._room,errorModule:mT,assetsPath:t}));this._plugins.set(e.Name,o),e.autoStart&&this.startPlugin(e.Name)}enterRoom(e){return f(this,null,function*(){var c,l;let{scene:t="rtc",enableAutoPlayDialog:r=!0,autoReceiveAudio:o=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!K(e.proxy)&&e.proxy.turnServer&&((l=(c=this._room).setTurnServer)==null||l.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=r,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=n,me(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,priority:e.priority,useVp8:e.useVp8};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,H.frameWorkType),this._checkTrackToPublish(),$l.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(){Se(this),this.removeAllListeners(),this._room.destroy(),Xo.delete(this),Xo.size===0&&$l.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)}),this._plugins.clear(),E.off("102",this._onLocalTrackCaptured,this)}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:r,option:o}=e,n=new ht(this._room.audioManager),a={},c={muted:!0};o&&(g(o.microphoneId)?g(o.audioTrack)||(a.customSource=o.audioTrack):a.deviceId=o.microphoneId,o&&Y(o.captureVolume)&&n.setCaptureVolume(o.captureVolume),g(o.profile)||(K(o.profile)?un[o.profile]&&n.setProfile(un[o.profile]):n.setProfile(o.profile)),Y(o.earMonitorVolume)&&(c.muted=!(o.earMonitorVolume>0),c.volume=o.earMonitorVolume),g(o.echoCancellation)||(n.profile.echoCancellation=o.echoCancellation),g(o.noiseSuppression)||(n.profile.noiseSuppression=o.noiseSuppression),g(o.autoGainControl)||(n.profile.autoGainControl=o.autoGainControl)),n.on("5",l=>{this.emit(M.ERROR,new P({code:U.DEVICE_ERROR,extraCode:5309,messageParams:{error:l}}))}),n.on("2",l=>{this.emit(M.DEVICE_CHANGED,{type:"microphone",action:"active",device:l})}),n.on("4",l=>{let h;l.error&&(h=P.convertFrom(l.error)),this.emit(M.PUBLISH_STATE_CHANGED,k(v({},l),{error:h}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),g(r)||n.setMute(r),Be(n,n).add("player-state-changed",l=>{this.emit(M.AUDIO_PLAY_STATE_CHANGED,k(v({},l),{userId:""}))}),this.listeners(M.AUDIO_FRAME).length>0&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(l=>{this.emit(H.EVENT.AUDIO_FRAME,{data:l})})),this._getPCMAbortCtrl&&n.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(l=>{this.emit(H.EVENT.AUDIO_FRAME,{data:l})}))}),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=k(v({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:n})})}updateLocalAudio(e){return f(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:r,option:o}=e,n={};o&&(o.microphoneId?yield this._localAudioTrack.switchDevice(o.microphoneId):g(o.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(o.audioTrack)),g(o.captureVolume)||this._localAudioTrack.setCaptureVolume(o.captureVolume),g(o.earMonitorVolume)||(n.muted=!(o.earMonitorVolume>0),n.volume=o.earMonitorVolume),yield this._localAudioTrack.update3A(o)),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(r)||this._localAudioTrack.setMute(r),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Gt(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),Se(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("stopLocalAudio"),delete this._getPCMAbortCtrl))})}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:r=!0,mute:o,option:n}=e,a=new $e(this._room.videoManager),c={},l={};n&&(n.cameraId?c.deviceId=n.cameraId:g(n.useFrontCamera)?g(n.videoTrack)||(c.customSource=n.videoTrack):c.facingMode=n.useFrontCamera?m.FACING_MODE_USER:m.FACING_MODE_ENVIRONMENT,n.qosPreference&&(c.contentHint=Wo(n.qosPreference)),g(n.profile)||(K(n.profile)?pt[n.profile]&&a.setProfile(pt[n.profile]):a.setProfile(n.profile)),g(n.fillMode)||(l.objectFit=n.fillMode),g(n.mirror)||(l.mirror=n.mirror),g(n.small)||(Io()?K(n.small)?a.small=pt[n.small]:n.small===!0?a.small=pt["120p"]:a.small=n.small:this._log.warn("small stream is not supported"))),a.once("first-video-frame",h=>{this.emit(M.FIRST_VIDEO_FRAME,k(v({},h),{streamType:or(h.streamType)}))}),a.on("5",h=>{this.emit(M.ERROR,new P({code:U.DEVICE_ERROR,extraCode:5308,messageParams:{error:h}}))}),a.on("2",h=>{this.emit(M.DEVICE_CHANGED,{type:"camera",action:"active",device:h})}),a.on("4",h=>{let u;h.error&&(u=P.convertFrom(h.error)),this.emit(M.PUBLISH_STATE_CHANGED,k(v({},h),{error:u}))}),this._listenOutputTrackChanged(a),yield a.capture(c),g(o)||(yield a.setMute(o)),Be(a,a).add("player-state-changed",h=>{this.emit(M.VIDEO_PLAY_STATE_CHANGED,k(v({},h),{userId:"",streamType:"main"}))}),r&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localVideoTrack=a,this._localVideoConfig=k(v({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:l,track:a})})}updateLocalVideo(e){return f(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:r,mute:o,option:n}=e,a={};if(n)if(g(n.profile)||(K(n.profile)?pt[n.profile]&&this._localVideoTrack.setProfile(pt[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&g(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):g(n.useFrontCamera)?g(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?m.FACING_MODE_USER:m.FACING_MODE_ENVIRONMENT),g(n.fillMode)||(a.objectFit=n.fillMode),g(n.mirror)||(a.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(Wo(n.qosPreference)),n.small){let c=!this._localVideoTrack.small;Io()?(n.small===!0?this._localVideoTrack.small=pt["120p"]:K(n.small)?this._localVideoTrack.small=pt[n.small]:this._localVideoTrack.small=n.small,this._room.videoManager.update(),c&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else n.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1));this._room.isJoined&&!g(r)&&(r&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!r&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),g(o)||(yield this._localVideoTrack.setMute(o)),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Gt(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(),Se(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:r=!0,option:o}=e,n=new st(this._room.videoManager);n.on("4",u=>{let p;u.error&&(p=P.convertFrom(u.error)),this.emit(M.PUBLISH_STATE_CHANGED,k(v({},u),{error:p}))}),n.once("first-video-frame",u=>{this.emit(M.FIRST_VIDEO_FRAME,k(v({},u),{streamType:or(u.streamType)}))}),this._listenOutputTrackChanged(n),e.streamType==="main"&&(n.mediaType=4);let a=null,c={},l={};o&&(g(o.profile)||(K(o.profile)?hn[o.profile]&&n.setProfile(hn[o.profile]):n.setProfile(o.profile)),o.systemAudio&&(c.systemAudio=!0,c.echoCancellation=o.echoCancellation,c.noiseSuppression=o.noiseSuppression,c.autoGainControl=o.autoGainControl),g(o.fillMode)||(l.objectFit=o.fillMode),o.videoTrack&&(c.videoTrack=o.videoTrack),o.audioTrack&&(c.audioTrack=o.audioTrack),o.captureElement&&(c.captureElement=o.captureElement),o.preferDisplaySurface&&(c.preferDisplaySurface=o.preferDisplaySurface),o.qosPreference&&(c.contentHint=Wo(o.qosPreference)));let h=yield n.capture(c);if(n.mediaTrack.addEventListener(m.ENDED,()=>{this._stopScreenShare(),this.emit(M.SCREEN_SHARE_STOPPED)}),h.getAudioTracks()[0]&&(a=new si(this._room.audioManager),yield a.setInputMediaStreamTrack(h.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),Be(n,n).add("player-state-changed",u=>{this.emit(M.VIDEO_PLAY_STATE_CHANGED,k(v({},u),{userId:"",streamType:"sub"}))}),r&&this._room.isJoined){let u=[n];a&&u.push(a),this._room.publish(...u).catch(()=>{})}this._localScreenTrack=n,this._localScreenAudioTrack=a,this._localScreenConfig=k(v({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:l,track:n})})}updateScreenShare(e){return f(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:r,option:o}=e,n={};if(o&&(g(o.fillMode)||(n.objectFit=o.fillMode),o.qosPreference)){let a=Wo(o.qosPreference);this._localScreenTrack.setContentHint(a)}this._room.isJoined&&!g(r)&&(r&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!r&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:t,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),Gt(this._localScreenConfig,e)})}stopScreenShare(){return f(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return f(this,null,function*(){let{view:t,userId:r,streamType:o,option:n}=e,a=`${r}_${o}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${r}, streamType:${o}`);return}let c=this._room.remotePublishedUserMap.get(r);if(!c)return;let l={},h=o==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;this._listenOutputTrackChanged(h),n&&(g(n.fillMode)||(l.objectFit=n.fillMode),g(n.mirror)||(l.mirror=n.mirror),l.canvasRender=n.canvasRender,o==="main"&&!g(n.small)&&(!c.remoteVideoTrack.isSubscribing&&!c.remoteVideoTrack.isSubscribed&&c.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,h.user))),yield this._room.subscribe(h),yield this._enableVideoDecodeFallback(h,o),yield this._updateVideoPlayOption({view:t,playOption:l,track:h}),this._emitTrackEvent(h),this._remoteVideoConfigMap.set(a,{config:e}),n&&!g(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:h,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return f(this,null,function*(){var D,G;let{view:t,userId:r,streamType:o,option:n}=e,a=`${r}_${o}`,c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(r))return;let l={};n&&(g(n.fillMode)||(l.objectFit=n.fillMode),g(n.mirror)||(l.mirror=n.mirror));let h=null,u=this._room.remotePublishedUserMap.get(r);if(o==="main"&&(u!=null&&u.muteState.hasVideo)&&(h=u.remoteVideoTrack),o==="sub"&&(u!=null&&u.muteState.hasAuxiliary)&&(h=u.remoteAuxiliaryTrack),!h)return;let{config:p}=c;o==="main"&&n&&!g(n.small)&&this._room.changeType(n.small,h.user),yield this._updateVideoPlayOption({view:t,playOption:l,track:h,prevConfig:p}),Gt(p,e);let _=g(n==null?void 0:n.receiveWhenViewVisible)?(D=p.option)==null?void 0:D.receiveWhenViewVisible:n.receiveWhenViewVisible,I=g(t)?p.view:t,R=g(n==null?void 0:n.viewRoot)?(G=p.option)==null?void 0:G.viewRoot:n.viewRoot;this._observeView({remoteTrack:h,view:I,receiveWhenViewVisible:_,viewRoot:R})})}stopRemoteVideo(e){return f(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return f(this,null,function*(){let r=[],o=this._room.remotePublishedUserMap.get(e.userId);if(o){let{muteState:a,remoteVideoTrack:c,remoteAuxiliaryTrack:l}=o;e.streamType==="main"&&(c.stop(),a.hasVideo&&r.push(c)),e.streamType==="sub"&&(l.stop(),a.hasAuxiliary&&r.push(l))}for(let a of r)t&&(yield this._room.unsubscribe(a),this._mediaTrackMap.delete(a.outMediaTrack));let n=this._remoteVideoConfigMap.get(`${e.userId}_${e.streamType}`);n&&n.observer&&n.observer.disconnect(),this._remoteVideoConfigMap.delete(`${e.userId}_${e.streamType}`)})}muteRemoteAudio(e,t){return f(this,null,function*(){this._remoteAudioMuteMap.set(e,t);try{if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let r=[...this._room.remotePublishedUserMap.values()];for(let o of r)o.muteState.hasAudio&&!this._remoteAudioConfigMap.has(o.userId)&&(yield this._startRemoteAudio({userId:o.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(r){throw this._remoteAudioMuteMap.delete(e),r}})}setRemoteAudioVolume(e,t){if(e==="*"){let r=[...this._room.remotePublishedUserMap.values()];for(let o of r)this._remoteAudioVolumeMap.set(o.userId,t),o.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:o.remoteAudioTrack})}else if(e){let r=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,t),r&&r.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:r.remoteAudioTrack})}}startPlugin(e,t){return 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,r){return this.listeners(e).includes(t)?this:(this._log.debug("on",e),super.on(e,t,r),this._eventListened.add(e),e===H.EVENT.AUDIO_FRAME&&!this._getPCMAbortCtrl&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(o=>{this.emit(H.EVENT.AUDIO_FRAME,{data:o})}),this._localAudioTrack&&this._localAudioTrack.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(o=>{this.emit(H.EVENT.AUDIO_FRAME,{data:o})}))})),this)}emit(e,...t){try{Cm.has(e)&&this._log.debug(`emit ${e} ${JSON.stringify(t)}`)}catch(r){}return super.emit(e,...t)}off(e,t,r){var o,n;return this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners(),(o=this._getPCMAbortCtrl)==null||o.abort("off"),delete this._getPCMAbortCtrl):(super.off(e,t,r),e===H.EVENT.AUDIO_FRAME&&((n=this._getPCMAbortCtrl)==null||n.abort("off"),delete this._getPCMAbortCtrl)),this}getAudioTrack(e={userId:"",streamType:"main"}){let t,r=null,o="main",n=!1;if(K(e)?t=e:(t=e.userId,n=e.processed===!0,e.streamType&&(o=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);a&&(r=a.remoteAudioTrack)}else r=o==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return r?n&&r.outMediaTrack&&r.outMediaTrack!==r.mediaTrack?r.outMediaTrack.clone():r.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:r="main",processed:o=!1}=e,n=null;if(t==="")r==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),r==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(t);a&&(n=r==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?o&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:t,streamType:r="main"}=e;if(t){let o=this._room.remotePublishedUserMap.get(t);if(r==="main"&&(o!=null&&o.muteState.hasVideo))return o.remoteVideoTrack.getVideoFrame();if(r==="sub"&&(o!=null&&o.muteState.hasAuxiliary))return o.remoteAuxiliaryTrack.getVideoFrame()}else{if(r==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(r==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var t,r;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(r=this._localScreenAudioTrack)==null||r.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(o=>o.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return f(this,null,function*(){(yield Zi()).forEach(r=>{r.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}),Le=r)}),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return f(this,null,function*(){var a;let{userId:t}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let o={},n=r.remoteAudioTrack;this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let c=this._remoteAudioVolumeMap.get(t),l=Y(c)?c:100;o.volume=l,this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(n),_e(Ie(n,"decode-failed"),we(Ie(n,Q.INIT)),Ne(()=>{this.startPlugin(jo.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:o,track:n}),yield(a=this.room.audioManager)==null?void 0:a.mixPlayTrack(n.outMediaTrack,t)}catch(c){throw this._remoteAudioConfigMap.delete(t),c}this._emitTrackEvent(n)})}_stopRemoteAudio(e,t=!0){return f(this,null,function*(){var o;let r=this._room.remotePublishedUserMap.get(e.userId);r&&(r.remoteAudioTrack.stop(),r.muteState.hasAudio&&t&&(yield this._room.unsubscribe(r.remoteAudioTrack)),this._mediaTrackMap.delete(r.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`),(o=this.room.audioManager)==null||o.unMixPlayTrack(e.userId)})}_enableVideoDecodeFallback(e,t){let r=this._room.videoDecodeFallbackType;!r||!this._plugins.has("TRTCVideoDecoder")||(this._log.debug("remote video will fall back when decode failed"),_e(Ie(e,"decode-failed"),we(Ie(e,Q.INIT)),vl(()=>{this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})}),Bo(Ie(e,"decode-downgrade-state-changed")),Ne(o=>{this.emit(M.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,k(v({},o),{streamType:t,userId:e.userId}))},o=>{this._log.error("fallback",o)},()=>this._log.info("fallback complete"))))}_updateVideoPlayOption(n){return f(this,arguments,function*({view:e,playOption:t,track:r,prevConfig:o}){if(r.setMirror(t.mirror),g(e)&&o&&o.view&&!Xr(t)){let a=zr(o.view);a.length>0&&(yield r.play(a,t))}if(!g(e)){let a=zr(e);a.length>0?yield r.play(a,t):r.stop()}})}_updateAudioPlayOption(o){return f(this,arguments,function*({playOption:e={},track:t,prevConfig:r}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}g(e.muted)||t.setPlayerMute(e.muted),g(e.volume)||t.setAudioVolume(e.volume/100),t instanceof ht&&e.muted===!1&&!g(e.volume)&&e.volume>0&&t.mixPlayTrack(t.mediaTrack,"")})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,t=!0){let r=e.isRemote?e.userId:"";e.outMediaTrack&&(t&&this._mediaTrackMap.get(e.outMediaTrack)===r||(this._mediaTrackMap.set(e.outMediaTrack,r),this.emit(M.TRACK,{userId:r,streamType:or(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var t,r,o;let e=[];if((t=this._localAudioConfig)!=null&&t.publish&&this._localAudioTrack&&e.push(this._localAudioTrack),(r=this._localVideoConfig)!=null&&r.publish&&this._localVideoTrack&&e.push(this._localVideoTrack),(o=this._localScreenConfig)!=null&&o.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:r=!1,viewRoot:o}){if(g(t))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${or(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||Te(t)&&t.length===0||!r){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let l=n.visibleViewMap||new Map,h=-1;(!a||a.root!==o)&&(a==null||a.disconnect(),l.clear(),a=new IntersectionObserver(p=>{p.forEach(_=>{l.set(_.target,_.isIntersecting)}),clearTimeout(h),h=window.setTimeout(()=>{[...l.values()].find(I=>I)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:o}));let u=new Set(zr(t));l.forEach((p,_)=>{u.has(_)||(a.unobserve(_),l.delete(_))}),u.forEach(p=>{l.set(p,!0),a.observe(p)}),a.takeRecords().forEach(p=>{l.set(p.target,p.isIntersecting)}),n.visibleViewMap=l,n.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",r=e.split(`_${t}`)[0];r&&this._stopRemoteVideo({userId:r,streamType:t}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._remoteAudioVolumeMap.clear(),vm(this),this._room.remotePublishedUserMap.forEach(e=>{Se(e.remoteAudioTrack),Se(e.remoteVideoTrack),Se(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),Se(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!Le||gs(Le))&&(this._initActiveSpeaker(),E.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return f(this,null,function*(){if(Le&&!gs(Le))this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:Le});else{let e=yield Zi();e[0]&&!gs(e[0])?(Le=e[0],this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):E.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let r=this._room.remotePublishedUserMap.get(e);if(r){let o=t==="main"?r.remoteVideoTrack:r.remoteAuxiliaryTrack,n=[o];this._room.autoReceiveAudio&&r.remoteAudioTrack.isAvailable&&n.push(r.remoteAudioTrack),this._room.subscribe(...n).then(()=>{this._emitTrackEvent(o)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:t}){t.hasAudio&&t.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:t}){this._stopRemoteVideo({userId:e,streamType:t},!1).catch(()=>{})}sendSEIMessage(e,t){var o;let r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:k(v({seiPayloadType:243},t),{small:!!((o=this._localVideoTrack)!=null&&o.small)})}),N.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,r;(r=(t=this._room).sendCustomMessage)==null||r.call(t,e),N.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){C.setLogLevel(e),g(t)||(t?C.enableUploadLog():C.disableUploadLog())}static isSupported(){return zn()}static getCameraList(e=!0){return ut(e)}static getMicrophoneList(e=!0){return it(e)}static getSpeakerList(e=!0){return Zi(e)}static setCurrentSpeaker(e){return f(this,null,function*(){if(pe&&(e===Et.SPEAKER||e===Et.HEADSET)){let r=yield H.getMicrophoneList(),o="";if(r.forEach(n=>{n.label===e&&(o=n.deviceId)}),!o)return;Xo.forEach(n=>f(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:o}}))}));return}(yield Zi()).forEach(r=>{r.deviceId===e&&(Xo.forEach(o=>{o._setCurrentSpeaker(e),o.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:r})}),Le=r)})})}static _addKVStat({type:e,key:t,value:r,base:o,useUV:n,version:a}){switch(a&&(Er.version=a),e){case"count":Er.addCount({key:t,useUV:n});break;case"enum":Er.addEnum({key:t,value:r,useUV:n});break;case"number":Er.addNumber({key:t,value:r,split:o});break}}};d(H,"_loggerManager",C),d(H,"EVENT",M),d(H,"ERROR_CODE",U),d(H,"TYPE",Et),d(H,"frameWorkType",30),y([ue({replaceArg:e=>({argIndex:0,value:{name:"plugin"in e?e.plugin.Name:e.Name,assetsPath:"assetsPath"in e?e==null?void 0:e.assetsPath:"default"}})})],H.prototype,"use",1),y([Je(Me.TRTC.enterRoom),rr("room",([e],[t])=>(e.roomId||e.strRoomId)===(t.roomId||t.strRoomId)&&e.userId===t.userId&&e.sdkAppId===t.sdkAppId),J(e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)}),ue()],H.prototype,"enterRoom",1),y([ue()],H.prototype,"exitRoom",1),y([Je(Me.TRTC.switchRole),Pr("room",{merge:(e,t)=>t}),ue()],H.prototype,"switchRole",1),y([ue()],H.prototype,"destroy",1),y([Je(Me.TRTC.startLocalAudio),rr("audio",([e],[t])=>{var r,o;return((r=e==null?void 0:e.option)==null?void 0:r.microphoneId)===((o=t==null?void 0:t.option)==null?void 0:o.microphoneId)}),ue()],H.prototype,"startLocalAudio",1),y([Je(Me.TRTC.updateLocalAudio),Pr("audio",{debounce:{delay:200,getKey:()=>`${Pm}-localAudio`,isNeedToDebounce:e=>{var t;return!g((t=e.option)==null?void 0:t.captureVolume)}}}),ue()],H.prototype,"updateLocalAudio",1),y([sr("audio"),ue()],H.prototype,"stopLocalAudio",1),y([Je(Me.TRTC.startLocalVideo),rr("video",([e],[t])=>{var r,o;return((r=e==null?void 0:e.option)==null?void 0:r.cameraId)===((o=t==null?void 0:t.option)==null?void 0:o.cameraId)}),ue()],H.prototype,"startLocalVideo",1),y([Je(Me.TRTC.updateLocalVideo),Pr("video"),ue()],H.prototype,"updateLocalVideo",1),y([sr("video"),ue()],H.prototype,"stopLocalVideo",1),y([Je(Me.TRTC.startScreenShare),rr("screen",()=>!0),ue()],H.prototype,"startScreenShare",1),y([Je(Me.TRTC.updateScreenShare),Pr("screen"),ue()],H.prototype,"updateScreenShare",1),y([ue()],H.prototype,"stopScreenShare",1),y([Je(Me.TRTC.startRemoteVideo),rr(e=>`v${e.userId}${e.streamType}`,()=>!0),ue({getRemoteId:e=>`${e.userId}_${e.streamType}`})],H.prototype,"startRemoteVideo",1),y([Je(Me.TRTC.updateRemoteVideo),Pr(e=>`v${e.userId}${e.streamType}`),ue({getRemoteId:e=>`${e.userId}_${e.streamType}`})],H.prototype,"updateRemoteVideo",1),y([Je(Me.TRTC.stopRemoteVideo),J(e=>function(t){return f(this,null,function*(){if(t.userId==="*"){let r=[];return this._room.remotePublishedUserMap.forEach(o=>{this._remoteVideoConfigMap.has(`${o.userId}_main`)&&r.push(this.stopRemoteVideo({streamType:"main",userId:o.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${o.userId}_sub`)&&r.push(this.stopRemoteVideo({streamType:"sub",userId:o.userId}).catch(()=>{}))}),Promise.all(r)}return e.call(this,t)})}),ue({getRemoteId:e=>`${e.userId}_${e.streamType}`})],H.prototype,"stopRemoteVideo",1),y([sr(e=>`v${e.userId}${e.streamType}`)],H.prototype,"_stopRemoteVideo",1),y([Je(...Me.TRTC.muteRemoteAudio),ue({getRemoteId:e=>e})],H.prototype,"muteRemoteAudio",1),y([Ul(...Me.TRTC.setRemoteAudioVolume),Dm(200,e=>e),ue({getRemoteId:e=>e})],H.prototype,"setRemoteAudioVolume",1),y([Ga("start"),Qe(e=>{var t;return(t=e.afterStart)==null?void 0:t.call(e)}),rr((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),ue({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>_c[e.getName()],ignoreLog:e=>e.getName()==="Debug"})],H.prototype,"startPlugin",1),y([Ga("update"),Pr((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),ue({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>gc[e.getName()]})],H.prototype,"updatePlugin",1),y([Ga("stop"),sr((e,t)=>{if(e.disableRandomCall)return null;let r=e.getGroup(t),o=e.getAlias();return r==="*"?new RegExp(`${o}.*`):o+r}),ue({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Tc[e.getName()]})],H.prototype,"stopPlugin",1),y([Ul(...Me.TRTC.enableAudioVolumeEvaluation)],H.prototype,"enableAudioVolumeEvaluation",1),y([ue()],H.prototype,"getVideoSnapshot",1),y([ue()],H.prototype,"_setCurrentSpeaker",1),y([rr(e=>`a${e.userId}`,()=>!0)],H.prototype,"_startRemoteAudio",1),y([J(e=>function(t){return f(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(r=>this._stopRemoteAudio(k(v({},t),{userId:r.userId})).catch(()=>{}))):e.call(this,t)})}),sr(e=>`a${e.userId}`)],H.prototype,"_stopRemoteAudio",1),y([sr("room")],H.prototype,"_exitRoom",1),y([sr("screen")],H.prototype,"_stopScreenShare",1),y([Je(...Me.TRTC.sendSEIMessage),Ol({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],H.prototype,"sendSEIMessage",1),y([Je(Me.TRTC.sendCustomMessage),Ol({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],H.prototype,"sendCustomMessage",1),y([Je(Me.TRTC.create)],H,"_create",1);var Kl=H,Qo=Kl;var Zl=class{constructor(){d(this,"_set",new Set);E.on(T.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,r){return`${t}_${e}_${i}_${r}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:r}){return r.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,r.useStringRoomId))}};function pT(){return f(this,null,function*(){let s,i;try{let u=yield it();s=u&&u.length}catch(u){}try{let u=yield ut();i=u&&u.length}catch(u){}let e={microphone:s,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:r,isH264DecodeSupported:o,isVp8DecodeSupported:n}=this.checkSystemResult.detail,a=Yt.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:t,h264Decode:o,vp8Encode:r,vp8Decode:n},l={browser:a.browser,os:a.os,trtc:c,devices:e},h={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};ee.uploadEvent({log:`trtcstats-${JSON.stringify(l)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(l)}`),ee.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(h)}`,userId:this.userId})})}function wm(){return J(s=>{let i=new Zl;return function(e,t,r){return f(this,null,function*(){let o=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=t,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new b({code:S.INVALID_OPERATION,message:V({key:w.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new b({code:S.INVALID_OPERATION,message:V({key:w.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:o}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${o} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),E.emit(T.JOIN_START,{room:this,roomId:o,params:e});let n=nt.getEnv();n||(n=li.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(mn.OLD_CLOUD_LADDER)?n=li.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(mn.WEBRTC)&&(n=li.WEBRTC))),ee.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),Yt.checkSystemRequirementsInternal().then(a=>{this.checkSystemResult=a,pT.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!nt.getEnv()&&(yield this.schedule(e,r));let a=yield s.call(this,e,t,r);return this.roomId=o,this._joinedTimestamp=nt.performanceNow(),E.emit(T.JOIN_SUCCESS,{room:this}),r===30&&!e.component&&ee.uploadEvent({log:`stat-conv-${Number(Mt)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw i.delete({room:this,roomId:o}),E.emit(T.JOIN_FAILED,{room:this,error:a}),a}})}})}var Um=()=>J(s=>function(...i){return f(this,null,function*(){E.emit(T.LEAVE_START,{room:this}),yield s.call(this),E.emit(T.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function Vm(){return J(s=>function(...i){let e=s.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var Fm=Pe(je());var Ee={SETUP_SUCCESS:"1",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4",SETUP_FAILED:"5",DISCONNECTED:"6"};var Ut={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140},Bm=[Ut.UPDATE_REMOTE_MUTE_STAT,Ut.UPLINK_NETWORK_STATS,Ut.USER_LIST_RES,Ut.MUTE_RESULT,Ut.SERVER_FIRST_PACKAGE_RECEIVED,Ut.RECEIVE_CUSTOM_MSG],B={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",START_PUBLISH_CDN_STREAM_RES:"start-publish-cdn-stream-res",UPDATE_PUBLISH_CDN_STREAM_RES:"update-publish-cdn-stream-res",STOP_PUBLISH_CDN_STREAM_RES:"stop-publish-cdn-stream-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg"},q={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",START_PUBLISH_CDN_STREAM:"start_publish_cdn_stream",UPDATE_PUBLISH_CDN_STREAM:"update_publish_cdn_stream",STOP_PUBLISH_CDN_STREAM:"stop_publish_cdn_stream",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3",ABILITY_STATUS_REPORT:"ability_status_report",RECONNECT_WS:"reconnect",SEND_CUSTOM_MSG:"channel_msg"};var ed=new Set;function Hm(s){let i=[...ed.values()].find(e=>e.room.userId===s&&!e.room.isJoined);return i||null}var Os=class extends Fm.default{constructor(e){var r,o;super();d(this,"room");d(this,"url");d(this,"backupUrl");d(this,"race");d(this,"destroyed",!1);d(this,"_socketInUse");d(this,"_socket");d(this,"_backupSocket");d(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0});d(this,"_currentState","DISCONNECTED");d(this,"_isReconnecting",!1);d(this,"_seq",0);d(this,"_log");d(this,"_lastMessageTime",-1);d(this,"_connnectStartTime",-1);d(this,"_stopConnectRetry");d(this,"bytesSent",0);d(this,"bytesReceived",0);d(this,"keepAlive",!1);d(this,"signalDomainWhenUnifiedProxy");d(this,"stopKeepAliveTimeout");d(this,"rtt",0);this.room=e.room,this.race=g(e.race)?!0:e.race,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy,(((o=(r=this.room.scheduleResult)==null?void 0:r.config)==null?void 0:o.keepAliveClient)||0)-ed.size>0&&this.room.enableSPC&&(this.keepAlive=!0,ed.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=C.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))}`;this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`);let t=new URLSearchParams(location.search).get("clientIp");return t&&(e+=`&clientIp=${t}`),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=L();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 jr(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?m.BACKUP:m.MAIN),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:r}){let o=new WebSocket(e);this.bindSocket(o),r?this._socket=o:this._backupSocket=o;let n=-1;return new Promise((a,c)=>{o.onclose=c,o.onerror=c,o.onopen=()=>a(o),t&&(n=setTimeout(()=>{this.unbindAndCloseSocket(r?m.MAIN:m.BACKUP),c(new b({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{o.onclose=null,o.onerror=null,o.onopen=null,clearTimeout(n)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===m.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}onclose(e){e.target===this._socketInUse&&(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),(!e.wasClean||e.code!==1e3)&&this.startReconnection(),this.room.isJoining&&this.emit(Ee.SETUP_FAILED,new b({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(m.MAIN),this.unbindAndCloseSocket(m.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(Ee.SETUP_FAILED,new b({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=Ks(e.data);let t=JSON.parse(e.data),{cmd:r,data:o}=t,n=Object.values(Ut),c=Object.keys(Ut)[n.indexOf(r)],l=B[c]||r;switch(Bm.includes(r)||(this._log.debug(`received ${r} msg: ${e.data}`),l&&this._log.info(`Received event: [ ${l} ]`)),r){case Ut.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=o.clientIp,this._signalInfo.signalIp=o.signalInnerIp,o.svrTime&&Nu(o.svrTime),this._log.info(`ChannelSetup Success ${L()-this._connnectStartTime}`),N.addSuccessEvent({key:521701,cost:L()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(Ee.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let h=new b({code:S.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:V({key:w.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),N.addFailedEvent({key:521701,error:h}),this.emit(Ee.SETUP_FAILED,h)}break}case Ut.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=o.relayOuterIp,this._signalInfo.relayInnerIp=o.relayInnerIp,this._signalInfo.relayPort=o.relayPort,this._signalInfo.tinyId=t.tinyId,this._signalInfo.endReportExtend=o.endReportExtend,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(l,{data:t});break}default:this.emit(String(l),{data:t});break}}reGetSignalChannelUrl(){return f(this,null,function*(){try{if(!this.room.joinParams)return;wt(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?m.MAIN:m.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}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:r,relayInnerIp:o,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:q.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:o,relayOuterIp:r,relayPort:n},responseCommand:B.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),N.addSuccessEvent({key:521702,cost:L()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(N.addFailedEvent({key:521702,error:a.code}),this._log.warn(`reconnect failed, ${a.code} ${a.message}`),this.room.reJoin())}catch(e){this._log.error(e),this.room.reJoin()}}})}send(e,t={}){if(this.isConnected&&!this.room.isLeft){let r={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},o=JSON.stringify(r);return this._socketInUse.send(o),this.bytesSent+=Ks(o),r.seq}}sendWaitForResponse({command:e,data:t,timeout:r=5e3,responseCommand:o,commandDesc:n,enableLog:a=!0,addReceiveTime:c=!1}){return new Promise((l,h)=>{let u=setTimeout(()=>{this.off(o,_);let R=new b({code:S.API_CALL_TIMEOUT,message:V({key:w.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(R),h(R)},r),p=Date.now(),_=R=>{R.data.seq===I&&(clearTimeout(u),this.off(o,_),c&&(R.data.receiveTime=Date.now()),l(R))};this.on(o,_);let I=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:r,retries:o=0,retryTimeout:n=0}=e;return Jt({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${r} when connected`),this.once(Ee.CONNECTED,a))},onRetrying:a=>{this._log.warn(`${t||r} timeout observed, retrying [${a}/${o}]`)},settings:{retries:o,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),ed.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(m.MAIN),this.unbindAndCloseSocket(m.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(B.JOIN_ROOM_RESULT,t)},e*1e3);let t=r=>{r.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(B.JOIN_ROOM_RESULT,t))};this.on(B.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(Ee.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(Ee.CONNECTED):e==="DISCONNECTED"&&this.emit(Ee.DISCONNECTED))}};y([tt({settings:{retries:1/0,timeout:2e3},onError(e,t){!this.room.isDestroyed&&!this.destroyed&&t()},onRetrying(e,t){this._log.warn(`retrying to connect ${e}`),e>=3&&e%3===0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,(this.room.isDestroyed||this.destroyed)&&t())}})],Os.prototype,"connect",1);var $m=Pe(je());var eu=0,tu=!1,td=new Set,_T=s=>eu>2&&!tu&&td.size===0&&s,iu=!1,Ye=class{constructor(i){d(this,"userId");d(this,"tinyId");d(this,"_sdpSemantics");d(this,"_isUplink");d(this,"_room");d(this,"_log");d(this,"_signalChannel");d(this,"_isErrorObserved",!1);d(this,"_waitForPeerConnectionConnectedPromise");d(this,"_waitForPeerConnectionConnectedPromiseReject",null);d(this,"_peerConnection",null);d(this,"_emitter",new $m.default);d(this,"_currentState","DISCONNECTED");d(this,"_isReconnecting",!1);d(this,"_reconnectionCount",0);d(this,"_reconnectionTimer",-1);d(this,"_isFirstConnection",!0);d(this,"_prevTime",-1);d(this,"_localAddress");d(this,"_remoteAddress");this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=C.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=L())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,N.addSuccessEvent({key:521705,cost:Math.min(L()-this._prevTime,30*1e3)})):this._isReconnecting&&N.addSuccessEvent({key:521706,cost:L()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,N.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&N.addFailedEvent({key:521706,error:i}),i}}initialize(){let i={iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(i),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(i){this._log.info("close connection"),this._emitter.emit("closed",i),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),td.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:S.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return Ct;let i=null;if(this._isUplink){if(!Ki()||this._peerConnection.getSenders().length===0)return Ct;i=this._peerConnection.getSenders()[0].transport}else{if(!Sr()||this._peerConnection.getReceivers().length===0)return Ct;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:Ct}onConnectionStateChange(i){let e=this._peerConnection.iceConnectionState,t=this.getDTLSTransportState();if(this._log.info(`connectionState: ${i.target.connectionState}, ICE: ${e}, DTLS: ${t}`),i.target.connectionState===ce.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===ce.FAILED||i.target.connectionState===ce.CLOSED){let r=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,o=new b({message:r,code:S.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",o)}(i.target.connectionState===ce.CONNECTED||i.target.connectionState===ce.COMPLETED)&&(this.logSelectedCandidate(),ee.logSuccessEvent({userId:this._room.userId,eventType:Ke.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(eu=0,tu=!1,iu=!0,td.add(this)):td.delete(this),E.emit(T.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(Yi(e)){let t=i.get(e.localCandidateId),r=i.get(e.remoteCandidateId);t&&(this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.candidateType==="relay"?`relayProtocol:${t.relayProtocol}`:""}`),this._localAddress=`${t.ip||t.address}:${t.port}`),r&&(this._log.info(`remote candidate: ${r.candidateType} ${r.protocol}:${r.ip||r.address}:${r.port}`),this._remoteAddress=`${r.protocol}:${r.ip||r.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(n),o(),i())},r=({room:a})=>{a===this._room&&(clearTimeout(n),o(),e(new b({code:S.API_CALL_ABORTED,message:V({key:w.CONNECTION_ABORTED,data:"leave room"})})))},o=()=>{E.off(T.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{o();let a=new b({code:S.API_CALL_TIMEOUT,message:"connection timeout"});eu+=1,_T(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),tu=!0,this._emitter.emit("firewall-restriction")),e(a)},qs);E.on(T.LEAVE_SUCCESS,r,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(Ee.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=ui()){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?S.UPLINK_RECONNECTION_FAILED:S.DOWNLINK_RECONNECTION_FAILED,message:V({key:this._isUplink?w.UPLINK_RECONNECTION_FAILED:w.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(Ee.CONNECTED,this.reconnect,this),-1)}on(i,e,t){this._emitter.on(i,e,t)}off(i,e,t){this._emitter.off(i,e,t)}getIsReconnecting(){return this._isReconnecting}get isH264(){var i,e;return!!((e=(i=this._peerConnection)==null?void 0:i.remoteDescription)!=null&&e.sdp.includes("H264"))}setOffer(i){var e;return(e=this._peerConnection)==null?void 0:e.setLocalDescription(i)}setAnswer(i){var e;return(e=this._peerConnection)==null?void 0:e.setRemoteDescription(i)}};y([rt(521712,!1)],Ye.prototype,"setOffer",1),y([rt(521713,!1)],Ye.prototype,"setAnswer",1);var nu=Pe(ou());var ge=function(s){return nu.default.parse(s)},It=function(s){return nu.default.write(s)},zm=function(s){let i=ge(s);return i.media.forEach(e=>{e.type===m.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),It(i)};function Ym(s){let i=ge(s);return i.media.forEach(e=>{var t,r;if(e.type===m.VIDEO){let o=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&o.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let l=c.match(/apt=(\d+)/);l&&l[1]&&o.has(Number(l[1]))&&o.add(a)});let n=({payload:a})=>!o.has(a);e.rtp=e.rtp.filter(n),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=(r=e.payloads)==null?void 0:r.split(" ").filter(a=>!o.has(Number(a))).join(" ")}}),It(i)}function id(s){return Object.keys(s).filter(i=>s[i])}var Ms=class Ms extends Ye{constructor(e){super(k(v({},e),{isUplink:!1}));d(this,"_flag",0);d(this,"isRobot",!1);d(this,"role","anchor");d(this,"remoteAudioTrack");d(this,"remoteVideoTrack");d(this,"remoteAuxiliaryTrack");d(this,"ssrc",{audio:0,video:0,auxiliary:0});d(this,"_isSDPExchanging",!1);this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new Oi(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new oi(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Cs(this._room,this)}get videoCodec(){var t,r;let e=(r=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:r.sdp;return e?e.includes("H264")?"h264":"vp8":"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 pi(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===m.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){let t=e.streams[0],{track:r}=e,o=t.id===Js?m.MAIN:m.AUXILIARY;this._log.debug(`ontrack ${o} ${r.kind}`);let n=m.AUDIO;r.kind===m.VIDEO&&(n=o===m.MAIN?m.VIDEO:m.AUXILIARY);let a=this.remoteAudioTrack;n===m.VIDEO?a=this.remoteVideoTrack:n===m.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(r)}addRRTRLine(e){let t=e.split(`\r
|
|
60
|
+
2. If the user is in Chrome 70 and below, when the div container is moved, the playback will be paused.`,color:"orange",class:"orange",textColor:"#fff"},'"displaySurface":"window"':{tips:"Screen sharing captures the application window",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"monitor"':{tips:"Screen sharing captures the entire screen",color:"blue",class:"blue",textColor:"#fff"},'"displaySurface":"browser"':{tips:"Screen sharing captures a certain tab page",color:"blue",class:"blue",textColor:"#fff"},updateMediaSettings:{tips:"The resolution and frame rate below are the actual resolution and frame rate captured",color:"blue",class:"blue",textColor:"#fff"},"main stream start to play with":{tips:"Call remoteStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"stream start to play with":{tips:"Call localStream.play interface",color:"blue",class:"blue",textColor:"#fff"},"main setAudioVolume to 0":{tips:"Business side calls remoteStream.setAudioVolume(0) interface to set the playback volume to 0, which will cause the playback to be silent",color:"orange",class:"orange",textColor:"#fff"},"screen sharing was stopped because the video track is ended":{tips:"Screen sharing capture stopped, possible reasons: user clicks the stop button, the window/page shared by the user is closed, etc.",color:"orange",class:"orange",textColor:"#fff"},"Join() => joining room":{tips:"Call client.join interface",color:"blue",class:"blue",textColor:"#fff"},"publish() => publishing local stream":{tips:"Call client.publish interface",color:"blue",class:"blue",textColor:"#fff"},"subscribe() => subscribe to":{tips:"Call client.subscribe interface",color:"blue",class:"blue",textColor:"#fff"},"switchRole() => switch role":{tips:"Call client.switchRole interface",color:"blue",class:"blue",textColor:"#fff"}};["enterRoom","exitRoom","switchRole","destroy","startLocalAudio","updateLocalAudio","stopLocalAudio","startLocalVideo","updateLocalVideo","stopLocalVideo","startScreenShare","updateScreenShare","stopScreenShare","startRemoteVideo","updateRemoteVideo","stopRemoteVideo","muteRemoteAudio","setRemoteAudioVolume"].forEach(s=>{Mm[`${s}()`]={tips:`Call trtc.${s}`,color:"blue",class:"blue",textColor:"#fff"}});var aM=Object.keys(Mm);var uT=0,Ya,Ds=class Ds{constructor(i){this.core=i;d(this,"_core");d(this,"log");d(this,"dumpLocalVideoMap",{});d(this,"dumpRemoteVideoMap",{});d(this,"dialog");this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${++uT}`}),this.log.info("created")}getName(){return Ds.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(i){switch(i){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return f(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog(),this.addVideoProcessor())})}update(){}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return f(this,null,function*(){try{if(Ya)yield Ya;else{let i=Date.now();Ya=this.loadScript(`https://web.sdk.qcloud.com/trtc/webrtc/assets/debug/debug-dialog@${Re}.js`),yield Ya,this.log.info(`download debug dialog script cost: ${Date.now()-i}ms`)}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(i){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(i))}})}closeDebugDiaLog(){var i;(i=this.dialog)==null||i.closeDialog(),this.dialog=null}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):zl,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):Yl,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo({frame:i,mediaType:e}){return zl({frame:i,onDump:()=>{if(!e)return;let t=e===2?"sub":"main",r=this.dumpLocalVideoMap[t];r&&(r.data.push(i.data),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}})}decodeVideo({frame:i,track:e}){return Yl({frame:i,onDump:()=>{if(!e)return;let t=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];t&&(t.data.push(i.data),t.duration>0&&Date.now()-t.startTimestamp>t.duration*1e3&&t.onDumpEnd())}})}loadScript(i){return new Promise((e,t)=>{this.log.info(`loading debug dialog from ${i}`);let r=document.createElement("script");r.type="text/javascript",r.onload=e,r.onerror=t,r.crossOrigin="anonymous",r.src=i,document.head.append?document.head.append(r):document.getElementsByTagName("head")[0].appendChild(r)})}};d(Ds,"Name","Debug"),d(Ds,"autoStart",!0),y([tt({settings:{timeout:3e3,retries:3},onError(i,e,t){var r;(r=i==null?void 0:i.message)!=null&&r.includes("timeout")?e():t(i)}})],Ds.prototype,"loadScript",1);var Ka=Ds;var Lm=s=>{switch(s){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},Za=class{constructor(i,e,t){d(this,"trackDoneOB");d(this,"startOB");d(this,"stopOB");d(this,"inputFrameCount",0);d(this,"decodedFrameCount",0);d(this,"type","auto");d(this,"config");d(this,"decoder");d(this,"_decodeSink");let{kvStatManager:r,trtc:o}=i;this.config=t.config,this.trackDoneOB=Ie(e,Q.INIT),this.stopOB=ot(this.trackDoneOB),this.startOB=ot(),t.type==="auto"?this.type="webCodecs":this.type=t.type;let n=ot(),a=c=>{let l=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),_e(l,Ue(this.stopOB),Ne(()=>{},h=>{e.log.error(h),r.addFailedEvent({key:Lm(this.type),error:h}),c>4?this.startOB.error(h):this.startOB.next(c+1)})),_e(l,Li(1),Fo(Dr))};_e(this.startOB,vr(0),tr(a),Ue(this.stopOB),Ne(()=>{e.player.setOutput(),n.next("STARTED")},c=>{n.next("FAILED")},()=>{r.addSuccessEvent({key:Lm(this.type)}),r.addSuccessEvent({key:504702})}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.startOB.next(0)}close(i){this.stopOB.next(i)}pipe(i){return Mi()(e=>f(this,null,function*(){this._decodeSink=e,e.defer(()=>{var r;(r=this.decoder)==null||r.close()});let{type:t}=this;try{switch(t){case"webCodecs":this.decoder=new AudioDecoder({error:r=>{i.log.error(r),e.error(4)},output:r=>{this.decodedFrameCount++,e.next(r),i.player.write(r)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(r){i.log.error(r),e.error(t==="webCodecs"?2:6)}}))}decodeFrame(i){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:i.data,timestamp:i.timestamp,type:"key"}))}},hT={type:"object"},qo=class qo{constructor(i){this.core=i;d(this,"log");d(this,"contextMap",new Map);d(this,"decodeProcessorMap",new WeakMap);this.log=i.log.createChild({id:`${this.getAlias()}`})}getAlias(){return qo.Name}getGroup(i){return i.track.userId+i.track.streamType}getName(){return qo.Name}getValidateRule(i){return hT}start(i){let{track:e}=i;this.decodeProcessorMap.set(e,this.decode(i)),this.core.room.audioManager.addDecodeProcessor({processor:({frame:t,track:r})=>this.decodeProcessorMap.has(r)?this.decodeProcessorMap.get(r)({frame:t,track:r}):t,type:3})}decode(i){return({frame:e,track:t})=>{if(t!==i.track)return e;if(this.contextMap.has(t))return this.contextMap.get(t).decodeFrame(e);let r=new Za(this.core,t,i);return _e(r.trackDoneOB,Li(1),Ne(()=>{this.core.clearStarted(this,this.getGroup(i)),this.stop({track:t})})),this.contextMap.set(t,r),r.decodeFrame(e)}}stop({track:i}){let e=this.contextMap.get(i);e&&(e.close("stop"),this.contextMap.delete(i),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(i){let e=this.contextMap.get(i.track);if(e){if(i.type==="mock"){e.mock(10);return}e.close("update"),this.contextMap.set(i.track,new Za(this.core,i.track,i))}}};d(qo,"Name","TRTCAudioDecoder");var jo=qo;var Pm=0,Xo=new Set,Le=null;Ed(Om);cs.checkStorage();Nc();var mT={RtcError:P,ErrorCode:U,ErrorCodeDictionary:St},H=class H extends xm.EventEmitter{constructor(e,t){super();d(this,"_room");d(this,"_eventListened",new Set);d(this,"_localVideoTrack",null);d(this,"_localAudioTrack",null);d(this,"_localScreenTrack",null);d(this,"_localScreenAudioTrack",null);d(this,"_localVideoConfig",null);d(this,"_localScreenConfig",null);d(this,"_localAudioConfig",null);d(this,"_remoteVideoConfigMap",new Map);d(this,"_remoteAudioConfigMap",new Map);d(this,"_remoteAudioVolumeMap",new Map);d(this,"_remoteAudioMuteMap",new Map);d(this,"_mediaTrackMap",new WeakMap);d(this,"_log",C.createLogger({id:`t${++Pm}`}));d(this,"_plugins",new Map);d(this,"_networkQuality",null);d(this,"_speakerId");d(this,"_getPCMAbortCtrl");this._room=new e(v({logger:this._log,frameWorkType:H.frameWorkType},t)),this._room.videoDecodeFallbackType=t.videoDecodeFallback,this._log.debug(`TRTC.create() ${JSON.stringify(t,(r,o)=>r==="plugins"?o.map(n=>n.Name):o)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(r){return this._room.audioManager.dump(r)}}}),t.plugins&&t.plugins.forEach(r=>{this._use(r,t.assetsPath)}),this._use(Ja,t.assetsPath),this._use(ja,t.assetsPath),this._use(Qa,t.assetsPath),this._use(jo,t.assetsPath||dn),this._use(Ka),t.enableSEI&&Ro&&this._use(za),this._room.on("audio-volume",r=>{!r.find(o=>o.userId==="")&&this._localAudioTrack&&r.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),t.volumeType===1&&r.forEach(o=>{var a;let n=o.userId===""?this._localAudioTrack:(a=this.room.remotePublishedUserMap.get(o.userId))==null?void 0:a.remoteAudioTrack;n&&(o.volume=n.dbVolume)}),this.emit(M.AUDIO_VOLUME,{result:r.sort((o,n)=>n.volume-o.volume)})}),this._room.videoManager.on("error",r=>{this._log.error(new P({code:U.OPERATION_FAILED,extraCode:5504,message:r.message,originError:r}))}),this._listenEvents(),this._initActiveSpeaker(),Nm(this,"trtc")}static create(e){}static _create(e,t){fm();let r=new H(e,t||{});return Xo.add(r),r}get room(){return this._room}_listenEvents(){Fe(this,this._room).add("peer-join",e=>{let{userId:t}=e;this.emit(M.REMOTE_USER_ENTER,{userId:t})}).add("peer-leave",e=>{this.emit(M.REMOTE_USER_EXIT,{userId:e}),this._remoteAudioVolumeMap.delete(e)}).add("banned",e=>{this._exitRoom().then(()=>{this.emit(M.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().then(()=>{this.emit(M.ERROR,P.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(M.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let t=k(v({},e),{uplinkRTT:Math.min(e.uplinkRTT,Xs),downlinkRTT:Math.min(e.downlinkRTT,Xs)});this.emit(M.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{Fe(r,r).add("player-state-changed",o=>{let n=k(v({},o),{userId:e.userId});r.kind===m.VIDEO&&(n.streamType=or(r.streamType)),this.emit(r.kind===m.AUDIO?M.AUDIO_PLAY_STATE_CHANGED:M.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",o=>{o.getCode()===S.PLAY_NOT_ALLOWED&&this.emit(M.AUTOPLAY_FAILED,{userId:r.userId,resume:()=>r.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{Se(r)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:r}=t,o=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:c}=t;a||this._remoteAudioConfigMap.delete(r),c||this._remoteVideoConfigMap.delete(`${r}_main`),t.hasAuxiliary||this._remoteVideoConfigMap.delete(`${r}_sub`),n!==c&&(c?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"}),this.emit(c?M.REMOTE_VIDEO_AVAILABLE:M.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"main"})),o!==a&&(a?this._onAudioAvailable({userId:r}):this._onAudioUnavailable({userId:r,muteState:t}),this.emit(a?M.REMOTE_AUDIO_AVAILABLE:M.REMOTE_AUDIO_UNAVAILABLE,{userId:r})),e.hasAuxiliary!==t.hasAuxiliary&&(t.hasAuxiliary?this._onVideoAvailable({userId:r,streamType:"sub"}):this._onVideoUnavailable({userId:r,streamType:"sub"}),this.emit(t.hasAuxiliary?M.REMOTE_VIDEO_AVAILABLE:M.REMOTE_VIDEO_UNAVAILABLE,{userId:r,streamType:"sub"}))}).add("sei-message",e=>{this.emit(M.SEI_MESSAGE,k(v({},e),{streamType:or(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(M.ERROR,new P({code:U.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var o,n,a,c,l,h,u;let t={2:"big",3:"small",7:"sub"},r={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((o=e.msg_down_stream_info[0])==null?void 0:o.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,Xs),upLoss:((c=this._networkQuality)==null?void 0:c.uplinkLoss)||0,downLoss:((l=this._networkQuality)==null?void 0:l.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((h=e.msg_up_stream_info.msg_audio_status)==null?void 0:h.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((u=e.msg_up_stream_info.msg_audio_status)==null?void 0:u.uint32_audio_level)||0)/_t},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)/_t},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(M.STATISTICS,r)}).add("custom-message",e=>{this.emit(M.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(M.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(M.FIRST_VIDEO_FRAME,k(v({},e),{streamType:or(e.streamType)}))}),Fe(this,be).add("audioInputAdded",e=>{this.emit(M.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(M.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(M.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(M.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>f(this,null,function*(){if(this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Le&&Le.deviceId===js){let t=(yield Zi()).find(r=>r.deviceId===js);t&&Le.groupId!==t.groupId&&(Le=t,this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>f(this,null,function*(){this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield Zi())[0];if(!t||!Le||Le.groupId===t.groupId)return;let r=Le.deviceId===e.deviceId,o=Le.deviceId===js&&Le.deviceId===t.deviceId;(r||o)&&(Le=t,this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}))}use(e){let t,r;"plugin"in e?(t=e.plugin,r=e.assetsPath):t=e,this._use(t,r||dn)}_use(e,t){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let o=new e(bm.call(this,{TRTC:H,room:this._room,errorModule:mT,assetsPath:t}));this._plugins.set(e.Name,o),e.autoStart&&this.startPlugin(e.Name)}enterRoom(e){return f(this,null,function*(){var c,l;let{scene:t="rtc",enableAutoPlayDialog:r=!0,autoReceiveAudio:o=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!K(e.proxy)&&e.proxy.turnServer&&((l=(c=this._room).setTurnServer)==null||l.call(c,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=r,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=n,me(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,priority:e.priority,useVp8:e.useVp8};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,H.frameWorkType),this._checkTrackToPublish(),$l.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(){Se(this),this.removeAllListeners(),this._room.destroy(),Xo.delete(this),Xo.size===0&&$l.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)}),this._plugins.clear(),E.off("102",this._onLocalTrackCaptured,this)}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:r,option:o}=e,n=new ht(this._room.audioManager),a={},c={muted:!0};o&&(g(o.microphoneId)?g(o.audioTrack)||(a.customSource=o.audioTrack):a.deviceId=o.microphoneId,o&&Y(o.captureVolume)&&n.setCaptureVolume(o.captureVolume),g(o.profile)||(K(o.profile)?un[o.profile]&&n.setProfile(un[o.profile]):n.setProfile(o.profile)),Y(o.earMonitorVolume)&&(c.muted=!(o.earMonitorVolume>0),c.volume=o.earMonitorVolume),g(o.echoCancellation)||(n.profile.echoCancellation=o.echoCancellation),g(o.noiseSuppression)||(n.profile.noiseSuppression=o.noiseSuppression),g(o.autoGainControl)||(n.profile.autoGainControl=o.autoGainControl)),n.on("5",l=>{this.emit(M.ERROR,new P({code:U.DEVICE_ERROR,extraCode:5309,messageParams:{error:l}}))}),n.on("2",l=>{this.emit(M.DEVICE_CHANGED,{type:"microphone",action:"active",device:l})}),n.on("4",l=>{let h;l.error&&(h=P.convertFrom(l.error)),this.emit(M.PUBLISH_STATE_CHANGED,k(v({},l),{error:h}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),g(r)||n.setMute(r),Fe(n,n).add("player-state-changed",l=>{this.emit(M.AUDIO_PLAY_STATE_CHANGED,k(v({},l),{userId:""}))}),this.listeners(M.AUDIO_FRAME).length>0&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(l=>{this.emit(H.EVENT.AUDIO_FRAME,{data:l})})),this._getPCMAbortCtrl&&n.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(l=>{this.emit(H.EVENT.AUDIO_FRAME,{data:l})}))}),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=k(v({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:c,track:n})})}updateLocalAudio(e){return f(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:t,mute:r,option:o}=e,n={};o&&(o.microphoneId?yield this._localAudioTrack.switchDevice(o.microphoneId):g(o.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(o.audioTrack)),g(o.captureVolume)||this._localAudioTrack.setCaptureVolume(o.captureVolume),g(o.earMonitorVolume)||(n.muted=!(o.earMonitorVolume>0),n.volume=o.earMonitorVolume),yield this._localAudioTrack.update3A(o)),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(r)||this._localAudioTrack.setMute(r),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Gt(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),Se(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("stopLocalAudio"),delete this._getPCMAbortCtrl))})}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:r=!0,mute:o,option:n}=e,a=new $e(this._room.videoManager),c={},l={};n&&(n.cameraId?c.deviceId=n.cameraId:g(n.useFrontCamera)?g(n.videoTrack)||(c.customSource=n.videoTrack):c.facingMode=n.useFrontCamera?m.FACING_MODE_USER:m.FACING_MODE_ENVIRONMENT,n.qosPreference&&(c.contentHint=Wo(n.qosPreference)),g(n.profile)||(K(n.profile)?pt[n.profile]&&a.setProfile(pt[n.profile]):a.setProfile(n.profile)),g(n.fillMode)||(l.objectFit=n.fillMode),g(n.mirror)||(l.mirror=n.mirror),g(n.small)||(Io()?K(n.small)?a.small=pt[n.small]:n.small===!0?a.small=pt["120p"]:a.small=n.small:this._log.warn("small stream is not supported"))),a.once("first-video-frame",h=>{this.emit(M.FIRST_VIDEO_FRAME,k(v({},h),{streamType:or(h.streamType)}))}),a.on("5",h=>{this.emit(M.ERROR,new P({code:U.DEVICE_ERROR,extraCode:5308,messageParams:{error:h}}))}),a.on("2",h=>{this.emit(M.DEVICE_CHANGED,{type:"camera",action:"active",device:h})}),a.on("4",h=>{let u;h.error&&(u=P.convertFrom(h.error)),this.emit(M.PUBLISH_STATE_CHANGED,k(v({},h),{error:u}))}),this._listenOutputTrackChanged(a),yield a.capture(c),g(o)||(yield a.setMute(o)),Fe(a,a).add("player-state-changed",h=>{this.emit(M.VIDEO_PLAY_STATE_CHANGED,k(v({},h),{userId:"",streamType:"main"}))}),r&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localVideoTrack=a,this._localVideoConfig=k(v({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:l,track:a})})}updateLocalVideo(e){return f(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:r,mute:o,option:n}=e,a={};if(n)if(g(n.profile)||(K(n.profile)?pt[n.profile]&&this._localVideoTrack.setProfile(pt[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&g(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):g(n.useFrontCamera)?g(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?m.FACING_MODE_USER:m.FACING_MODE_ENVIRONMENT),g(n.fillMode)||(a.objectFit=n.fillMode),g(n.mirror)||(a.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(Wo(n.qosPreference)),n.small){let c=!this._localVideoTrack.small;Io()?(n.small===!0?this._localVideoTrack.small=pt["120p"]:K(n.small)?this._localVideoTrack.small=pt[n.small]:this._localVideoTrack.small=n.small,this._room.videoManager.update(),c&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else n.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1));this._room.isJoined&&!g(r)&&(r&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!r&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),g(o)||(yield this._localVideoTrack.setMute(o)),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Gt(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(),Se(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:r=!0,option:o}=e,n=new st(this._room.videoManager);n.on("4",u=>{let p;u.error&&(p=P.convertFrom(u.error)),this.emit(M.PUBLISH_STATE_CHANGED,k(v({},u),{error:p}))}),n.once("first-video-frame",u=>{this.emit(M.FIRST_VIDEO_FRAME,k(v({},u),{streamType:or(u.streamType)}))}),this._listenOutputTrackChanged(n),e.streamType==="main"&&(n.mediaType=4);let a=null,c={},l={};o&&(g(o.profile)||(K(o.profile)?hn[o.profile]&&n.setProfile(hn[o.profile]):n.setProfile(o.profile)),o.systemAudio&&(c.systemAudio=!0,c.echoCancellation=o.echoCancellation,c.noiseSuppression=o.noiseSuppression,c.autoGainControl=o.autoGainControl),g(o.fillMode)||(l.objectFit=o.fillMode),o.videoTrack&&(c.videoTrack=o.videoTrack),o.audioTrack&&(c.audioTrack=o.audioTrack),o.captureElement&&(c.captureElement=o.captureElement),o.preferDisplaySurface&&(c.preferDisplaySurface=o.preferDisplaySurface),o.qosPreference&&(c.contentHint=Wo(o.qosPreference)));let h=yield n.capture(c);if(n.mediaTrack.addEventListener(m.ENDED,()=>{this._stopScreenShare(),this.emit(M.SCREEN_SHARE_STOPPED)}),h.getAudioTracks()[0]&&(a=new si(this._room.audioManager),yield a.setInputMediaStreamTrack(h.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),Fe(n,n).add("player-state-changed",u=>{this.emit(M.VIDEO_PLAY_STATE_CHANGED,k(v({},u),{userId:"",streamType:"sub"}))}),r&&this._room.isJoined){let u=[n];a&&u.push(a),this._room.publish(...u).catch(()=>{})}this._localScreenTrack=n,this._localScreenAudioTrack=a,this._localScreenConfig=k(v({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:l,track:n})})}updateScreenShare(e){return f(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:r,option:o}=e,n={};if(o&&(g(o.fillMode)||(n.objectFit=o.fillMode),o.qosPreference)){let a=Wo(o.qosPreference);this._localScreenTrack.setContentHint(a)}this._room.isJoined&&!g(r)&&(r&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!r&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:t,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),Gt(this._localScreenConfig,e)})}stopScreenShare(){return f(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return f(this,null,function*(){let{view:t,userId:r,streamType:o,option:n}=e,a=`${r}_${o}`;if(this._remoteVideoConfigMap.has(a)){this._log.warn(`remote video has already started. userId:${r}, streamType:${o}`);return}let c=this._room.remotePublishedUserMap.get(r);if(!c)return;let l={},h=o==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack;this._listenOutputTrackChanged(h),n&&(g(n.fillMode)||(l.objectFit=n.fillMode),g(n.mirror)||(l.mirror=n.mirror),l.canvasRender=n.canvasRender,o==="main"&&!g(n.small)&&(!c.remoteVideoTrack.isSubscribing&&!c.remoteVideoTrack.isSubscribed&&c.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,h.user))),yield this._room.subscribe(h),yield this._enableVideoDecodeFallback(h,o),yield this._updateVideoPlayOption({view:t,playOption:l,track:h}),this._emitTrackEvent(h),this._remoteVideoConfigMap.set(a,{config:e}),n&&!g(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:h,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return f(this,null,function*(){var D,G;let{view:t,userId:r,streamType:o,option:n}=e,a=`${r}_${o}`,c=this._remoteVideoConfigMap.get(a);if(!c||!this._room.remotePublishedUserMap.has(r))return;let l={};n&&(g(n.fillMode)||(l.objectFit=n.fillMode),g(n.mirror)||(l.mirror=n.mirror));let h=null,u=this._room.remotePublishedUserMap.get(r);if(o==="main"&&(u!=null&&u.muteState.hasVideo)&&(h=u.remoteVideoTrack),o==="sub"&&(u!=null&&u.muteState.hasAuxiliary)&&(h=u.remoteAuxiliaryTrack),!h)return;let{config:p}=c;o==="main"&&n&&!g(n.small)&&this._room.changeType(n.small,h.user),yield this._updateVideoPlayOption({view:t,playOption:l,track:h,prevConfig:p}),Gt(p,e);let _=g(n==null?void 0:n.receiveWhenViewVisible)?(D=p.option)==null?void 0:D.receiveWhenViewVisible:n.receiveWhenViewVisible,I=g(t)?p.view:t,R=g(n==null?void 0:n.viewRoot)?(G=p.option)==null?void 0:G.viewRoot:n.viewRoot;this._observeView({remoteTrack:h,view:I,receiveWhenViewVisible:_,viewRoot:R})})}stopRemoteVideo(e){return f(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return f(this,null,function*(){let r=[],o=this._room.remotePublishedUserMap.get(e.userId);if(o){let{muteState:a,remoteVideoTrack:c,remoteAuxiliaryTrack:l}=o;e.streamType==="main"&&(c.stop(),a.hasVideo&&r.push(c)),e.streamType==="sub"&&(l.stop(),a.hasAuxiliary&&r.push(l))}for(let a of r)t&&(yield this._room.unsubscribe(a),this._mediaTrackMap.delete(a.outMediaTrack));let n=this._remoteVideoConfigMap.get(`${e.userId}_${e.streamType}`);n&&n.observer&&n.observer.disconnect(),this._remoteVideoConfigMap.delete(`${e.userId}_${e.streamType}`)})}muteRemoteAudio(e,t){return f(this,null,function*(){this._remoteAudioMuteMap.set(e,t);try{if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let r=[...this._room.remotePublishedUserMap.values()];for(let o of r)o.muteState.hasAudio&&!this._remoteAudioConfigMap.has(o.userId)&&(yield this._startRemoteAudio({userId:o.userId}))}else t?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(r){throw this._remoteAudioMuteMap.delete(e),r}})}setRemoteAudioVolume(e,t){if(e==="*"){let r=[...this._room.remotePublishedUserMap.values()];for(let o of r)this._remoteAudioVolumeMap.set(o.userId,t),o.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:o.remoteAudioTrack})}else if(e){let r=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,t),r&&r.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:t},track:r.remoteAudioTrack})}}startPlugin(e,t){return 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,r){return this.listeners(e).includes(t)?this:(this._log.debug("on",e),super.on(e,t,r),this._eventListened.add(e),e===H.EVENT.AUDIO_FRAME&&!this._getPCMAbortCtrl&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(o=>{this.emit(H.EVENT.AUDIO_FRAME,{data:o})}),this._localAudioTrack&&this._localAudioTrack.on("input-media-track-changed",()=>{this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("inputMediaTrackChanged"),this._getPCMAbortCtrl=this._room.audioManager.getPCM(o=>{this.emit(H.EVENT.AUDIO_FRAME,{data:o})}))})),this)}emit(e,...t){try{Cm.has(e)&&this._log.debug(`emit ${e} ${JSON.stringify(t)}`)}catch(r){}return super.emit(e,...t)}off(e,t,r){var o,n;return this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners(),(o=this._getPCMAbortCtrl)==null||o.abort("off"),delete this._getPCMAbortCtrl):(super.off(e,t,r),e===H.EVENT.AUDIO_FRAME&&((n=this._getPCMAbortCtrl)==null||n.abort("off"),delete this._getPCMAbortCtrl)),this}getAudioTrack(e={userId:"",streamType:"main"}){let t,r=null,o="main",n=!1;if(K(e)?t=e:(t=e.userId,n=e.processed===!0,e.streamType&&(o=e.streamType)),t){let a=this._room.remotePublishedUserMap.get(t);a&&(r=a.remoteAudioTrack)}else r=o==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return r?n&&r.outMediaTrack&&r.outMediaTrack!==r.mediaTrack?r.outMediaTrack.clone():r.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:t="",streamType:r="main",processed:o=!1}=e,n=null;if(t==="")r==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),r==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let a=this._room.remotePublishedUserMap.get(t);a&&(n=r==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack)}return n?o&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:t,streamType:r="main"}=e;if(t){let o=this._room.remotePublishedUserMap.get(t);if(r==="main"&&(o!=null&&o.muteState.hasVideo))return o.remoteVideoTrack.getVideoFrame();if(r==="sub"&&(o!=null&&o.muteState.hasAuxiliary))return o.remoteAuxiliaryTrack.getVideoFrame()}else{if(r==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(r==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var t,r;this._speakerId=e,(t=this._localAudioTrack)==null||t.setAudioOutput(e),(r=this._localScreenAudioTrack)==null||r.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(o=>o.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return f(this,null,function*(){(yield Zi()).forEach(r=>{r.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}),Le=r)}),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: https://web.sdk.qcloud.com/trtc/webrtc/v5/doc/en/TRTC.html#.setCurrentSpeaker')})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return f(this,null,function*(){var a;let{userId:t}=e;if(this._remoteAudioConfigMap.has(t)){this._log.warn(`remote audio has already started. userId:${t}`);return}let r=this._room.remotePublishedUserMap.get(t);if(!r)return;let o={},n=r.remoteAudioTrack;this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let c=this._remoteAudioVolumeMap.get(t),l=Y(c)?c:100;o.volume=l,this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(n),_e(Ie(n,"decode-failed"),Ue(Ie(n,Q.INIT)),Ne(()=>{this.startPlugin(jo.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:o,track:n}),yield(a=this.room.audioManager)==null?void 0:a.mixPlayTrack(n.outMediaTrack,t)}catch(c){throw this._remoteAudioConfigMap.delete(t),c}this._emitTrackEvent(n)})}_stopRemoteAudio(e,t=!0){return f(this,null,function*(){var o;let r=this._room.remotePublishedUserMap.get(e.userId);r&&(r.remoteAudioTrack.stop(),r.muteState.hasAudio&&t&&(yield this._room.unsubscribe(r.remoteAudioTrack)),this._mediaTrackMap.delete(r.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`),(o=this.room.audioManager)==null||o.unMixPlayTrack(e.userId)})}_enableVideoDecodeFallback(e,t){let r=this._room.videoDecodeFallbackType;!r||!this._plugins.has("TRTCVideoDecoder")||(this._log.debug("remote video will fall back when decode failed"),_e(Ie(e,"decode-failed"),Ue(Ie(e,Q.INIT)),vl(()=>{this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})}),Bo(Ie(e,"decode-downgrade-state-changed")),Ne(o=>{this.emit(M.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,k(v({},o),{streamType:t,userId:e.userId}))},o=>{this._log.error("fallback",o)},()=>this._log.info("fallback complete"))))}_updateVideoPlayOption(n){return f(this,arguments,function*({view:e,playOption:t,track:r,prevConfig:o}){if(r.setMirror(t.mirror),g(e)&&o&&o.view&&!Xr(t)){let a=zr(o.view);a.length>0&&(yield r.play(a,t))}if(!g(e)){let a=zr(e);a.length>0?yield r.play(a,t):r.stop()}})}_updateAudioPlayOption(o){return f(this,arguments,function*({playOption:e={},track:t,prevConfig:r}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}g(e.muted)||t.setPlayerMute(e.muted),g(e.volume)||t.setAudioVolume(e.volume/100),t instanceof ht&&e.muted===!1&&!g(e.volume)&&e.volume>0&&t.mixPlayTrack(t.mediaTrack,"")})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,t=!0){let r=e.isRemote?e.userId:"";e.outMediaTrack&&(t&&this._mediaTrackMap.get(e.outMediaTrack)===r||(this._mediaTrackMap.set(e.outMediaTrack,r),this.emit(M.TRACK,{userId:r,streamType:or(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var t,r,o;let e=[];if((t=this._localAudioConfig)!=null&&t.publish&&this._localAudioTrack&&e.push(this._localAudioTrack),(r=this._localVideoConfig)!=null&&r.publish&&this._localVideoTrack&&e.push(this._localVideoTrack),(o=this._localScreenConfig)!=null&&o.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:t,receiveWhenViewVisible:r=!1,viewRoot:o}){if(g(t))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${or(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||Te(t)&&t.length===0||!r){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let l=n.visibleViewMap||new Map,h=-1;(!a||a.root!==o)&&(a==null||a.disconnect(),l.clear(),a=new IntersectionObserver(p=>{p.forEach(_=>{l.set(_.target,_.isIntersecting)}),clearTimeout(h),h=window.setTimeout(()=>{[...l.values()].find(I=>I)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:o}));let u=new Set(zr(t));l.forEach((p,_)=>{u.has(_)||(a.unobserve(_),l.delete(_))}),u.forEach(p=>{l.set(p,!0),a.observe(p)}),a.takeRecords().forEach(p=>{l.set(p.target,p.isIntersecting)}),n.visibleViewMap=l,n.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",r=e.split(`_${t}`)[0];r&&this._stopRemoteVideo({userId:r,streamType:t}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._remoteAudioVolumeMap.clear(),vm(this),this._room.remotePublishedUserMap.forEach(e=>{Se(e.remoteAudioTrack),Se(e.remoteVideoTrack),Se(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),Se(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!Le||gs(Le))&&(this._initActiveSpeaker(),E.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return f(this,null,function*(){if(Le&&!gs(Le))this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:Le});else{let e=yield Zi();e[0]&&!gs(e[0])?(Le=e[0],this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):E.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let r=this._room.remotePublishedUserMap.get(e);if(r){let o=t==="main"?r.remoteVideoTrack:r.remoteAuxiliaryTrack,n=[o];this._room.autoReceiveAudio&&r.remoteAudioTrack.isAvailable&&n.push(r.remoteAudioTrack),this._room.subscribe(...n).then(()=>{this._emitTrackEvent(o)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:t}){t.hasAudio&&t.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:t}){this._stopRemoteVideo({userId:e,streamType:t},!1).catch(()=>{})}sendSEIMessage(e,t){var o;let r=this._plugins.get("SEI");r&&(r.update({buffer:e,options:k(v({seiPayloadType:243},t),{small:!!((o=this._localVideoTrack)!=null&&o.small)})}),N.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var t,r;(r=(t=this._room).sendCustomMessage)==null||r.call(t,e),N.addCount({key:500001,useUV:!0})}static setLogLevel(e,t){C.setLogLevel(e),g(t)||(t?C.enableUploadLog():C.disableUploadLog())}static isSupported(){return zn()}static getCameraList(e=!0){return ut(e)}static getMicrophoneList(e=!0){return it(e)}static getSpeakerList(e=!0){return Zi(e)}static setCurrentSpeaker(e){return f(this,null,function*(){if(pe&&(e===Et.SPEAKER||e===Et.HEADSET)){let r=yield H.getMicrophoneList(),o="";if(r.forEach(n=>{n.label===e&&(o=n.deviceId)}),!o)return;Xo.forEach(n=>f(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:o}}))}));return}(yield Zi()).forEach(r=>{r.deviceId===e&&(Xo.forEach(o=>{o._setCurrentSpeaker(e),o.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:r})}),Le=r)})})}static _addKVStat({type:e,key:t,value:r,base:o,useUV:n,version:a}){switch(a&&(Er.version=a),e){case"count":Er.addCount({key:t,useUV:n});break;case"enum":Er.addEnum({key:t,value:r,useUV:n});break;case"number":Er.addNumber({key:t,value:r,split:o});break}}};d(H,"_loggerManager",C),d(H,"EVENT",M),d(H,"ERROR_CODE",U),d(H,"TYPE",Et),d(H,"frameWorkType",30),y([ue({replaceArg:e=>({argIndex:0,value:{name:"plugin"in e?e.plugin.Name:e.Name,assetsPath:"assetsPath"in e?e==null?void 0:e.assetsPath:"default"}})})],H.prototype,"use",1),y([Je(Me.TRTC.enterRoom),rr("room",([e],[t])=>(e.roomId||e.strRoomId)===(t.roomId||t.strRoomId)&&e.userId===t.userId&&e.sdkAppId===t.sdkAppId),J(e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)}),ue()],H.prototype,"enterRoom",1),y([ue()],H.prototype,"exitRoom",1),y([Je(Me.TRTC.switchRole),Pr("room",{merge:(e,t)=>t}),ue()],H.prototype,"switchRole",1),y([ue()],H.prototype,"destroy",1),y([Je(Me.TRTC.startLocalAudio),rr("audio",([e],[t])=>{var r,o;return((r=e==null?void 0:e.option)==null?void 0:r.microphoneId)===((o=t==null?void 0:t.option)==null?void 0:o.microphoneId)}),ue()],H.prototype,"startLocalAudio",1),y([Je(Me.TRTC.updateLocalAudio),Pr("audio",{debounce:{delay:200,getKey:()=>`${Pm}-localAudio`,isNeedToDebounce:e=>{var t;return!g((t=e.option)==null?void 0:t.captureVolume)}}}),ue()],H.prototype,"updateLocalAudio",1),y([sr("audio"),ue()],H.prototype,"stopLocalAudio",1),y([Je(Me.TRTC.startLocalVideo),rr("video",([e],[t])=>{var r,o;return((r=e==null?void 0:e.option)==null?void 0:r.cameraId)===((o=t==null?void 0:t.option)==null?void 0:o.cameraId)}),ue()],H.prototype,"startLocalVideo",1),y([Je(Me.TRTC.updateLocalVideo),Pr("video"),ue()],H.prototype,"updateLocalVideo",1),y([sr("video"),ue()],H.prototype,"stopLocalVideo",1),y([Je(Me.TRTC.startScreenShare),rr("screen",()=>!0),ue()],H.prototype,"startScreenShare",1),y([Je(Me.TRTC.updateScreenShare),Pr("screen"),ue()],H.prototype,"updateScreenShare",1),y([ue()],H.prototype,"stopScreenShare",1),y([Je(Me.TRTC.startRemoteVideo),rr(e=>`v${e.userId}${e.streamType}`,()=>!0),ue({getRemoteId:e=>`${e.userId}_${e.streamType}`})],H.prototype,"startRemoteVideo",1),y([Je(Me.TRTC.updateRemoteVideo),Pr(e=>`v${e.userId}${e.streamType}`),ue({getRemoteId:e=>`${e.userId}_${e.streamType}`})],H.prototype,"updateRemoteVideo",1),y([Je(Me.TRTC.stopRemoteVideo),J(e=>function(t){return f(this,null,function*(){if(t.userId==="*"){let r=[];return this._room.remotePublishedUserMap.forEach(o=>{this._remoteVideoConfigMap.has(`${o.userId}_main`)&&r.push(this.stopRemoteVideo({streamType:"main",userId:o.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${o.userId}_sub`)&&r.push(this.stopRemoteVideo({streamType:"sub",userId:o.userId}).catch(()=>{}))}),Promise.all(r)}return e.call(this,t)})}),ue({getRemoteId:e=>`${e.userId}_${e.streamType}`})],H.prototype,"stopRemoteVideo",1),y([sr(e=>`v${e.userId}${e.streamType}`)],H.prototype,"_stopRemoteVideo",1),y([Je(...Me.TRTC.muteRemoteAudio),ue({getRemoteId:e=>e})],H.prototype,"muteRemoteAudio",1),y([Ul(...Me.TRTC.setRemoteAudioVolume),Dm(200,e=>e),ue({getRemoteId:e=>e})],H.prototype,"setRemoteAudioVolume",1),y([Ga("start"),Qe(e=>{var t;return(t=e.afterStart)==null?void 0:t.call(e)}),rr((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),ue({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>_c[e.getName()],ignoreLog:e=>e.getName()==="Debug"})],H.prototype,"startPlugin",1),y([Ga("update"),Pr((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),ue({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>gc[e.getName()]})],H.prototype,"updatePlugin",1),y([Ga("stop"),sr((e,t)=>{if(e.disableRandomCall)return null;let r=e.getGroup(t),o=e.getAlias();return r==="*"?new RegExp(`${o}.*`):o+r}),ue({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Tc[e.getName()]})],H.prototype,"stopPlugin",1),y([Ul(...Me.TRTC.enableAudioVolumeEvaluation)],H.prototype,"enableAudioVolumeEvaluation",1),y([ue()],H.prototype,"getVideoSnapshot",1),y([ue()],H.prototype,"_setCurrentSpeaker",1),y([rr(e=>`a${e.userId}`,()=>!0)],H.prototype,"_startRemoteAudio",1),y([J(e=>function(t){return f(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(r=>this._stopRemoteAudio(k(v({},t),{userId:r.userId})).catch(()=>{}))):e.call(this,t)})}),sr(e=>`a${e.userId}`)],H.prototype,"_stopRemoteAudio",1),y([sr("room")],H.prototype,"_exitRoom",1),y([sr("screen")],H.prototype,"_stopScreenShare",1),y([Je(...Me.TRTC.sendSEIMessage),Ol({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],H.prototype,"sendSEIMessage",1),y([Je(Me.TRTC.sendCustomMessage),Ol({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],H.prototype,"sendCustomMessage",1),y([Je(Me.TRTC.create)],H,"_create",1);var Kl=H,Qo=Kl;var Zl=class{constructor(){d(this,"_set",new Set);E.on(T.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,r){return`${t}_${e}_${i}_${r}`}isJoined({userId:i,roomId:e,sdkAppId:t,room:r}){return r.scene==="rtc"?!1:this._set.has(this.getKey(i,e,t,r.useStringRoomId))}};function pT(){return f(this,null,function*(){let s,i;try{let u=yield it();s=u&&u.length}catch(u){}try{let u=yield ut();i=u&&u.length}catch(u){}let e={microphone:s,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:r,isH264DecodeSupported:o,isVp8DecodeSupported:n}=this.checkSystemResult.detail,a=Yt.basis(),c={webRTC:a.isWebRTCSupported,getUserMedia:a.isGetUserMediaSupported,webSocket:a.isWebSocketsSupported,screenShare:a.isScreenShareSupported,webAudio:a.isWebAudioSupported,h264Encode:t,h264Decode:o,vp8Encode:r,vp8Decode:n},l={browser:a.browser,os:a.os,trtc:c,devices:e},h={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};ee.uploadEvent({log:`trtcstats-${JSON.stringify(l)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(l)}`),ee.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(h)}`,userId:this.userId})})}function wm(){return J(s=>{let i=new Zl;return function(e,t,r){return f(this,null,function*(){let o=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=t,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new b({code:S.INVALID_OPERATION,message:V({key:w.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new b({code:S.INVALID_OPERATION,message:V({key:w.REPEAT_JOIN,data:this.userId})});i.add({room:this,roomId:o}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${o} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),E.emit(T.JOIN_START,{room:this,roomId:o,params:e});let n=nt.getEnv();n||(n=li.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(mn.OLD_CLOUD_LADDER)?n=li.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(mn.WEBRTC)&&(n=li.WEBRTC))),ee.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),Yt.checkSystemRequirementsInternal().then(a=>{this.checkSystemResult=a,pT.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!nt.getEnv()&&(yield this.schedule(e,r));let a=yield s.call(this,e,t,r);return this.roomId=o,this._joinedTimestamp=nt.performanceNow(),E.emit(T.JOIN_SUCCESS,{room:this}),r===30&&!e.component&&ee.uploadEvent({log:`stat-conv-${Number(Mt)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw i.delete({room:this,roomId:o}),E.emit(T.JOIN_FAILED,{room:this,error:a}),a}})}})}var Um=()=>J(s=>function(...i){return f(this,null,function*(){E.emit(T.LEAVE_START,{room:this}),yield s.call(this),E.emit(T.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function Vm(){return J(s=>function(...i){let e=s.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var Fm=Pe(je());var Ee={SETUP_SUCCESS:"1",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4",SETUP_FAILED:"5",DISCONNECTED:"6"};var Ut={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140},Bm=[Ut.UPDATE_REMOTE_MUTE_STAT,Ut.UPLINK_NETWORK_STATS,Ut.USER_LIST_RES,Ut.MUTE_RESULT,Ut.SERVER_FIRST_PACKAGE_RECEIVED,Ut.RECEIVE_CUSTOM_MSG],B={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",START_PUBLISH_CDN_STREAM_RES:"start-publish-cdn-stream-res",UPDATE_PUBLISH_CDN_STREAM_RES:"update-publish-cdn-stream-res",STOP_PUBLISH_CDN_STREAM_RES:"stop-publish-cdn-stream-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg"},q={PUBLISH_CHANGE:"publish_change",JOIN_ROOM:"join",LEAVE_ROOM:"leave",ON_QUALITY_REPORT:"quality_report",UPDATE_MUTE_STAT:"mute_uplink",PUBLISH:"publish",PUBLISH_STATE_CHANGE:"publish_state_change",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",RECEIVE_DATA_USER_LIST:"receive_data_userlist",UNSUBSCRIBE:"unsubscribe",SUBSCRIBE_CHANGE:"subscribe_change",START_PUBLISH_TENCENT_CDN:"start_publishing",STOP_PUBLISH_TENCENT_CDN:"stop_publishing",START_PUBLISH_GIVEN_CDN:"start_push_user_cdn",STOP_PUBLISH_GIVEN_CDN:"stop_push_user_cdn",START_MIX_TRANSCODE:"start_mcu_mix",STOP_MIX_TRANSCODE:"stop_mcu_mix",START_PUBLISH_CDN_STREAM:"start_publish_cdn_stream",UPDATE_PUBLISH_CDN_STREAM:"update_publish_cdn_stream",STOP_PUBLISH_CDN_STREAM:"stop_publish_cdn_stream",GET_USER_LIST:"get_user_list",SWITCH_ROLE:"change_role",UPDATE_CONSTRAINT_CONFIG:"update_constraint_config",REBUILD_PEER_CONNECTION:"rebuild_pc",READY_TO_RECEIVE_DATA:"ready_to_receive",SPC_JOIN_ROOM:"join/v2",SPC_PUBLISH:"publish/v2",SPC_SUBSCRIBE:"subscribe/v3",ABILITY_STATUS_REPORT:"ability_status_report",RECONNECT_WS:"reconnect",SEND_CUSTOM_MSG:"channel_msg"};var ed=new Set;function Hm(s){let i=[...ed.values()].find(e=>e.room.userId===s&&!e.room.isJoined);return i||null}var Os=class extends Fm.default{constructor(e){var r,o;super();d(this,"room");d(this,"url");d(this,"backupUrl");d(this,"race");d(this,"destroyed",!1);d(this,"_socketInUse");d(this,"_socket");d(this,"_backupSocket");d(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0});d(this,"_currentState","DISCONNECTED");d(this,"_isReconnecting",!1);d(this,"_seq",0);d(this,"_log");d(this,"_lastMessageTime",-1);d(this,"_connnectStartTime",-1);d(this,"_stopConnectRetry");d(this,"bytesSent",0);d(this,"bytesReceived",0);d(this,"keepAlive",!1);d(this,"signalDomainWhenUnifiedProxy");d(this,"stopKeepAliveTimeout");d(this,"rtt",0);this.room=e.room,this.race=g(e.race)?!0:e.race,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy,(((o=(r=this.room.scheduleResult)==null?void 0:r.config)==null?void 0:o.keepAliveClient)||0)-ed.size>0&&this.room.enableSPC&&(this.keepAlive=!0,ed.add(this)),this.url=e.url,this.backupUrl=e.backupUrl,this._seq=0,this._log=C.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))}`;this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`);let t=new URLSearchParams(location.search).get("clientIp");return t&&(e+=`&clientIp=${t}`),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=L();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 jr(t),this.unbindAndCloseSocket(this._socketInUse===this._socket?m.BACKUP:m.MAIN),this.emitConnectionStateChanged("CONNECTED")})}connectWS({url:e,timeout:t,isMain:r}){let o=new WebSocket(e);this.bindSocket(o),r?this._socket=o:this._backupSocket=o;let n=-1;return new Promise((a,c)=>{o.onclose=c,o.onerror=c,o.onopen=()=>a(o),t&&(n=setTimeout(()=>{this.unbindAndCloseSocket(r?m.MAIN:m.BACKUP),c(new b({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},t))}).finally(()=>{o.onclose=null,o.onerror=null,o.onopen=null,clearTimeout(n)})}bindSocket(e){e.addEventListener("close",this.onclose),e.addEventListener("error",this.onerror),e.addEventListener("message",this.onmessage)}unbindSocket(e){e.removeEventListener("close",this.onclose),e.removeEventListener("error",this.onerror),e.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(e){if(e===m.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch(t){}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch(t){}this._backupSocket=null}}onclose(e){e.target===this._socketInUse&&(this._log.warn(`${e.target===this._socket?"main":"backup"} is closed code:${e.code} ${e.reason}`),this.emitConnectionStateChanged("DISCONNECTED"),(!e.wasClean||e.code!==1e3)&&this.startReconnection(),this.room.isJoining&&this.emit(Ee.SETUP_FAILED,new b({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(m.MAIN),this.unbindAndCloseSocket(m.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(Ee.SETUP_FAILED,new b({code:S.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=Ks(e.data);let t=JSON.parse(e.data),{cmd:r,data:o}=t,n=Object.values(Ut),c=Object.keys(Ut)[n.indexOf(r)],l=B[c]||r;switch(Bm.includes(r)||(this._log.debug(`received ${r} msg: ${e.data}`),l&&this._log.info(`Received event: [ ${l} ]`)),r){case Ut.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=o.clientIp,this._signalInfo.signalIp=o.signalInnerIp,o.svrTime&&Nu(o.svrTime),this._log.info(`ChannelSetup Success ${L()-this._connnectStartTime}`),N.addSuccessEvent({key:521701,cost:L()-this._connnectStartTime}),this._connnectStartTime=-1,this.emit(Ee.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let h=new b({code:S.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:V({key:w.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:t.code,errorMsg:t.message}})});this._log.error(`${t.code}, ${t.message}`),this.close(),N.addFailedEvent({key:521701,error:h}),this.emit(Ee.SETUP_FAILED,h)}break}case Ut.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=o.relayOuterIp,this._signalInfo.relayInnerIp=o.relayInnerIp,this._signalInfo.relayPort=o.relayPort,this._signalInfo.tinyId=t.tinyId,this._signalInfo.endReportExtend=o.endReportExtend,this._log.info(`signalIp:${this._signalInfo.signalIp} clientIp:${this._signalInfo.clientIp} relayIp: ${this._signalInfo.relayIp}`)),this.emit(l,{data:t});break}default:this.emit(String(l),{data:t});break}}reGetSignalChannelUrl(){return f(this,null,function*(){try{if(!this.room.joinParams)return;wt(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:e,backupUrl:t}=this.room.getSignalChannelUrl();this.url=e,this.backupUrl=t}catch(e){}})}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let e=this._socketInUse===this._socket;this.unbindAndCloseSocket(e?m.MAIN:m.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}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:r,relayInnerIp:o,relayPort:n}=this._signalInfo,{data:a}=yield this.sendWaitForResponse({command:q.RECONNECT_WS,data:{roomId:e,useStringRoomId:t,relayInnerIp:o,relayOuterIp:r,relayPort:n},responseCommand:B.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),N.addSuccessEvent({key:521702,cost:L()-this._connnectStartTime}),this._connnectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(N.addFailedEvent({key:521702,error:a.code}),this._log.warn(`reconnect failed, ${a.code} ${a.message}`),this.room.reJoin())}catch(e){this._log.error(e),this.room.reJoin()}}})}send(e,t={}){if(this.isConnected&&!this.room.isLeft){let r={cmd:e,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},o=JSON.stringify(r);return this._socketInUse.send(o),this.bytesSent+=Ks(o),r.seq}}sendWaitForResponse({command:e,data:t,timeout:r=5e3,responseCommand:o,commandDesc:n,enableLog:a=!0,addReceiveTime:c=!1}){return new Promise((l,h)=>{let u=setTimeout(()=>{this.off(o,_);let R=new b({code:S.API_CALL_TIMEOUT,message:V({key:w.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(R),h(R)},r),p=Date.now(),_=R=>{R.data.seq===I&&(clearTimeout(u),this.off(o,_),c&&(R.data.receiveTime=Date.now()),l(R))};this.on(o,_);let I=this.send(e,t)})}sendWaitForResponseWithRetry(e){let{commandDesc:t,command:r,retries:o=0,retryTimeout:n=0}=e;return Jt({retryFunction:this.sendWaitForResponse,onError:({retry:a})=>{this.isOnline?a():(this._log.warn(`retry ${r} when connected`),this.once(Ee.CONNECTED,a))},onRetrying:a=>{this._log.warn(`${t||r} timeout observed, retrying [${a}/${o}]`)},settings:{retries:o,timeout:n},context:this})(e)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),ed.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(m.MAIN),this.unbindAndCloseSocket(m.BACKUP),this.emitConnectionStateChanged("DISCONNECTED")}destroy(){this.close(),this.destroyed=!0}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(B.JOIN_ROOM_RESULT,t)},e*1e3);let t=r=>{r.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(B.JOIN_ROOM_RESULT,t))};this.on(B.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(Ee.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(Ee.CONNECTED):e==="DISCONNECTED"&&this.emit(Ee.DISCONNECTED))}};y([tt({settings:{retries:1/0,timeout:2e3},onError(e,t){!this.room.isDestroyed&&!this.destroyed&&t()},onRetrying(e,t){this._log.warn(`retrying to connect ${e}`),e>=3&&e%3===0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,(this.room.isDestroyed||this.destroyed)&&t())}})],Os.prototype,"connect",1);var $m=Pe(je());var eu=0,tu=!1,td=new Set,_T=s=>eu>2&&!tu&&td.size===0&&s,iu=!1,Ye=class{constructor(i){d(this,"userId");d(this,"tinyId");d(this,"_sdpSemantics");d(this,"_isUplink");d(this,"_room");d(this,"_log");d(this,"_signalChannel");d(this,"_isErrorObserved",!1);d(this,"_waitForPeerConnectionConnectedPromise");d(this,"_waitForPeerConnectionConnectedPromiseReject",null);d(this,"_peerConnection",null);d(this,"_emitter",new $m.default);d(this,"_currentState","DISCONNECTED");d(this,"_isReconnecting",!1);d(this,"_reconnectionCount",0);d(this,"_reconnectionTimer",-1);d(this,"_isFirstConnection",!0);d(this,"_prevTime",-1);d(this,"_localAddress");d(this,"_remoteAddress");this.userId=i.userId,this.tinyId=i.tinyId,this._room=i.room,this._sdpSemantics=i.room.sdpSemantics,this._isUplink=i.isUplink,this._log=C.createLogger({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=i.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=L())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,N.addSuccessEvent({key:521705,cost:Math.min(L()-this._prevTime,30*1e3)})):this._isReconnecting&&N.addSuccessEvent({key:521706,cost:L()-this._prevTime}),this._prevTime=-1}catch(i){throw this._isFirstConnection?(this._isFirstConnection=!1,N.addFailedEvent({key:521705,error:i})):this._isReconnecting&&this._reconnectionCount>=3&&N.addFailedEvent({key:521706,error:i}),i}}initialize(){let i={iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(i),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(i){this._log.info("close connection"),this._emitter.emit("closed",i),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),td.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:S.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return Ct;let i=null;if(this._isUplink){if(!Ki()||this._peerConnection.getSenders().length===0)return Ct;i=this._peerConnection.getSenders()[0].transport}else{if(!Sr()||this._peerConnection.getReceivers().length===0)return Ct;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:Ct}onConnectionStateChange(i){let e=this._peerConnection.iceConnectionState,t=this.getDTLSTransportState();if(this._log.info(`connectionState: ${i.target.connectionState}, ICE: ${e}, DTLS: ${t}`),i.target.connectionState===ce.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===ce.FAILED||i.target.connectionState===ce.CLOSED){let r=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,o=new b({message:r,code:S.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",o)}(i.target.connectionState===ce.CONNECTED||i.target.connectionState===ce.COMPLETED)&&(this.logSelectedCandidate(),ee.logSuccessEvent({userId:this._room.userId,eventType:Ke.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(eu=0,tu=!1,iu=!0,td.add(this)):td.delete(this),E.emit(T.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(Yi(e)){let t=i.get(e.localCandidateId),r=i.get(e.remoteCandidateId);t&&(this._log.info(`local candidate: ${t.candidateType} ${t.protocol}:${t.ip||t.address}:${t.port} ${t.networkType||""} ${t.candidateType==="relay"?`relayProtocol:${t.relayProtocol}`:""}`),this._localAddress=`${t.ip||t.address}:${t.port}`),r&&(this._log.info(`remote candidate: ${r.candidateType} ${r.protocol}:${r.ip||r.address}:${r.port}`),this._remoteAddress=`${r.protocol}:${r.ip||r.address}`);break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise?this._waitForPeerConnectionConnectedPromise:(this._waitForPeerConnectionConnectedPromise=new Promise((i,e)=>{if(this._currentState==="CONNECTED")return i();this._waitForPeerConnectionConnectedPromiseReject=e;let t=a=>{a.state==="CONNECTED"&&(clearTimeout(n),o(),i())},r=({room:a})=>{a===this._room&&(clearTimeout(n),o(),e(new b({code:S.API_CALL_ABORTED,message:V({key:w.CONNECTION_ABORTED,data:"leave room"})})))},o=()=>{E.off(T.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{o();let a=new b({code:S.API_CALL_TIMEOUT,message:"connection timeout"});eu+=1,_T(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),tu=!0,this._emitter.emit("firewall-restriction")),e(a)},qs);E.on(T.LEAVE_SUCCESS,r,this),this._emitter.on("connection-state-changed",t,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null}),this._waitForPeerConnectionConnectedPromise)}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(Ee.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=ui()){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?S.UPLINK_RECONNECTION_FAILED:S.DOWNLINK_RECONNECTION_FAILED,message:V({key:this._isUplink?w.UPLINK_RECONNECTION_FAILED:w.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(Ee.CONNECTED,this.reconnect,this),-1)}on(i,e,t){this._emitter.on(i,e,t)}off(i,e,t){this._emitter.off(i,e,t)}getIsReconnecting(){return this._isReconnecting}get isH264(){var i,e;return!!((e=(i=this._peerConnection)==null?void 0:i.remoteDescription)!=null&&e.sdp.includes("H264"))}setOffer(i){var e;return(e=this._peerConnection)==null?void 0:e.setLocalDescription(i)}setAnswer(i){var e;return(e=this._peerConnection)==null?void 0:e.setRemoteDescription(i)}};y([rt(521712,!1)],Ye.prototype,"setOffer",1),y([rt(521713,!1)],Ye.prototype,"setAnswer",1);var nu=Pe(ou());var ge=function(s){return nu.default.parse(s)},It=function(s){return nu.default.write(s)},zm=function(s){let i=ge(s);return i.media.forEach(e=>{e.type===m.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),It(i)};function Ym(s){let i=ge(s);return i.media.forEach(e=>{var t,r;if(e.type===m.VIDEO){let o=new Set;e.rtp.forEach(({payload:a,codec:c})=>c==="H264"&&o.add(a)),e.fmtp.forEach(({payload:a,config:c})=>{let l=c.match(/apt=(\d+)/);l&&l[1]&&o.has(Number(l[1]))&&o.add(a)});let n=({payload:a})=>!o.has(a);e.rtp=e.rtp.filter(n),e.rtcpFb=(t=e.rtcpFb)==null?void 0:t.filter(n),e.fmtp=e.fmtp.filter(n),e.payloads=(r=e.payloads)==null?void 0:r.split(" ").filter(a=>!o.has(Number(a))).join(" ")}}),It(i)}function id(s){return Object.keys(s).filter(i=>s[i])}var Ms=class Ms extends Ye{constructor(e){super(k(v({},e),{isUplink:!1}));d(this,"_flag",0);d(this,"isRobot",!1);d(this,"role","anchor");d(this,"remoteAudioTrack");d(this,"remoteVideoTrack");d(this,"remoteAuxiliaryTrack");d(this,"ssrc",{audio:0,video:0,auxiliary:0});d(this,"_isSDPExchanging",!1);this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new Oi(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new oi(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new Cs(this._room,this)}get videoCodec(){var t,r;let e=(r=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:r.sdp;return e?e.includes("H264")?"h264":"vp8":"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 pi(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===m.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){let t=e.streams[0],{track:r}=e,o=t.id===Js?m.MAIN:m.AUXILIARY;this._log.debug(`ontrack ${o} ${r.kind}`);let n=m.AUDIO;r.kind===m.VIDEO&&(n=o===m.MAIN?m.VIDEO:m.AUXILIARY);let a=this.remoteAudioTrack;n===m.VIDEO?a=this.remoteVideoTrack:n===m.AUXILIARY&&(a=this.remoteAuxiliaryTrack),a.setInputMediaStreamTrack(r)}addRRTRLine(e){let t=e.split(`\r
|
|
61
61
|
`),r=new Map;t.forEach((n,a)=>{/^a=rtcp-fb:/.test(n)&&t[a+1]&&!/^a=rtcp-fb:/.test(t[a+1])&&r.set(a+1,`${n.match(/^a=rtcp-fb:\d+/)[0]} rrtr`)});let o=[...r];for(let n=0;n<o.length;n++){let[a,c]=o[n];t.splice(a+n,0,c)}return t.join(`\r
|
|
62
62
|
`)}addSPSDescription(e){let t=ge(e);return t.media.forEach(r=>{r.type===m.VIDEO&&r.fmtp.forEach(o=>{o.config+=";sps-pps-idr-in-keyframe=1"})}),It(t)}removeSDESDescription(e){let t=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],r=ge(e);return r.media.forEach(o=>{o.ext&&(o.ext=o.ext.filter(n=>!t.includes(n.uri)))}),It(r)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return f(this,null,function*(){var r,o;try{if((((r=this._peerConnection)==null?void 0:r.connectionState)===ce.NEW||((o=this._peerConnection)==null?void 0:o.connectionState)===ce.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e)){this._peerConnection||(this.initialize(),yield this.connect(e));return}if(this._log.info(`subscribe ${t} ${JSON.stringify(e)}`),this._peerConnection||this._isSDPExchanging){let n="subscribe_change";Object.values(e).find(a=>a===!0)||(n="unsubscribe"),yield this.sendSubscription(n,e)}else this.initialize(),yield this.connect(e)}catch(n){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${n.message} ${JSON.stringify(this.muteState)}`),new b({code:S.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}unsubscribe(r){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 o=v({},this.subscribeState);e.forEach(a=>{switch(a.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(a=>a===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${id(o)}]`),yield this.sendSubscription(n,o),n==="unsubscribe"&&(this.closePeerConnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"))})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},o=q.UNSUBSCRIBE,n=B.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=q.SUBSCRIBE_CHANGE,n=B.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:o,data:r,responseCommand:n,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let c=new b({code:a.code,message:V({key:w.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:r}=this._peerConnection.localDescription,o={type:t,sdp:r,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},n=yield this._signalChannel.sendWaitForResponse({command:q.SUBSCRIBE,commandDesc:"exchange sdp",data:o,responseCommand:B.SUBSCRIBE_RESULT,timeout:Dd});if(!this._peerConnection){let a=new b({code:S.INVALID_OPERATION,message:V({key:w.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return f(this,null,function*(){let e={voiceActivityDetection:!1};gt()&&this._sdpSemantics===Gi?(this._peerConnection.addTransceiver(m.AUDIO,{direction:z.RECVONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:z.RECVONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:z.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:r}=yield Qn();r||(this._log.warn("remove h264 desc from sdp"),t.sdp=Ym(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=zm(t.sdp),this._sdpSemantics===Gi&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)})}onSubscribeResult(e){return f(this,null,function*(){let{code:t,message:r=""}=e&&e.data||{},{type:o,sdp:n}=e&&e.data&&e.data.data||{};if(t===dr)throw new b({code:S.NOT_SUPPORTED_H264,message:V({key:w.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new b({code:t,message:V({key:w.EXCHANGE_SDP_FAILED,data:{errMsg:r}})});this._log.debug(`accept remote answer: ${n}`),yield this.setAnswer({type:o,sdp:n}),this.updateSSRC(n)}catch(a){throw this._log.error(a),a}})}updateSSRC(e){try{ge(e).media.forEach(r=>{if(r.ssrcs)if(r.type===m.AUDIO){let o=r.ssrcs.find(n=>{var a;return(a=n.value)==null?void 0:a.includes(Js)});o&&(this.ssrc.audio=Number(o.id))}else{let o=r.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(Js)}),n=r.ssrcs.find(a=>{var c;return(c=a.value)==null?void 0:c.includes(Rd)});o&&(this.ssrc.video=Number(o.id)),n&&(this.ssrc.auxiliary=Number(n.id))}})}catch(t){}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return f(this,null,function*(){if(!(xe(Ms.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch(t){let r=yt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${r/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},r)}})}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}get audioReceiver(){var e;return((e=this._peerConnection)==null?void 0:e.getReceivers()[0])||null}};y([J(e=>function(...t){return new Promise((r,o)=>{let n=a=>{this._emitter.off("closed",n),o(new b({code:S.API_CALL_ABORTED,message:V({key:w.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,o).finally(()=>{this._emitter.off("closed",n)})})})],Ms.prototype,"subscribe",1),y([rt(521717,!1)],Ms.prototype,"unsubscribe",1),y([Qe(Ye.prototype.afterConnect),ua(Ye.prototype.beforeConnect)],Ms.prototype,"connect",1);var au=Ms,du=au;var Zm={voiceActivityDetection:!1},Ls=class Ls extends Ye{constructor(e){super(k(v({},e),{isUplink:!0}));d(this,"localMainAudioTrack",null);d(this,"localMainVideoTrack",null);d(this,"localAuxAudioTrack",null);d(this,"localAuxVideoTrack",null);d(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});d(this,"_isPublishingAux",!1);d(this,"_publishingLocalAudioTrack");d(this,"_publishingLocalVideoTrack");d(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});d(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!!(this.localMainAudioTrack||this.localMainVideoTrack)}get isAuxStreamPublished(){return!!(this.localAuxVideoTrack||this.localAuxAudioTrack)}get publishState(){var t,r,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(Qt()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((r=a[1])!=null&&r.track),e.smallVideo=!!((o=a[2])!=null&&o.track),e.auxVideo=!!((n=a[3])!=null&&n.track)):a.forEach(c=>{c.track&&(c.track.kind===m.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,t){var n,a,c;let r=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:r,state:e}))),o}publish(o){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),t&&(this._publishingLocalVideoTrack=t),this._isPublishingAux=r;let n;t&&!r&&t.small&&(n=this._room.videoManager.smallTrack),this.sendMediaSettings(),gt()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:r}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:n}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,r?(t&&(this.localAuxVideoTrack=t),e&&(this.localAuxAudioTrack=e)):(t&&(this.localMainVideoTrack=t),e&&(this.localMainAudioTrack=e)),this.installTrackMuteEvents(e,t),this.sendMutedFlag()})}publishByTransceiver(n){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:o}){this._log.info("publish by transceiver");let a=new MediaStream,c=t==null?void 0:t.outMediaTrack,l=e==null?void 0:e.outMediaTrack;l&&a.addTrack(l),c&&a.addTrack(c);let h=this._peerConnection.getTransceivers();if(h.length===0)this._peerConnection.addTransceiver(l||m.AUDIO,{direction:z.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?m.VIDEO:c||m.VIDEO,{direction:z.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(r||m.VIDEO,{direction:z.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?c||m.VIDEO:m.VIDEO,{direction:z.SENDONLY,streams:[a]}),yield this.connect();else{let u=[];if(l&&(h[0].sender.track||u.push(0),yield h[0].sender.replaceTrack(l),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:m.AUDIO})),c){let p=o?3:1;yield h[p].sender.replaceTrack(c),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:m.VIDEO,videoType:o?m.AUXILIARY:m.BIG}),u.push(p),r&&(yield h[2].sender.replaceTrack(r),yield this.setBandwidth({bandwidth:t.small.bitrate,type:m.VIDEO,videoType:m.SMALL}),u.push(2))}yield this.setTransceiverDirection(z.SENDONLY,u),yield this.doPublishChange(),t==null||t.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),t==null||t.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}})}publishByAddTrack(o){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r}){this._log.info("publish by addtrack");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack;if(this._peerConnection&&this._peerConnection.connectionState!=="new"){e&&a&&(yield this.addTrack(e)),n&&(yield this.addTrack(t));return}let c=new MediaStream;if(a&&c.addTrack(a),n&&c.addTrack(n),a&&this._peerConnection.addTrack(a,c),n&&(this._peerConnection.addTrack(n,c),r)){let l=new MediaStream;l.addTrack(r),this._peerConnection.addTrack(r,l)}yield this.connect()})}enableSmall(e){return 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(z.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(z.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!Qt()){if(e&&e.outMediaTrack&&!t&&this.localMainVideoTrack){yield this.removeTrack(e),this.localMainAudioTrack=null;return}if(t&&t.outMediaTrack&&!e&&this.localMainAudioTrack){yield this.removeTrack(t),this.localMainVideoTrack=null;return}yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),this.emitConnectionStateChangedEvent("DISCONNECTED",t);return}let o=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localAuxAudioTrack&&!this.localMainAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=k(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=k(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(z.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return f(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponse({command:q.PUBLISH_STATE_CHANGE,data:t,responseCommand:B.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:q.UNPUBLISH,commandDesc:"unpublish",responseCommand:B.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===S.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let r=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:o,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:o=this._publishingLocalVideoTrack),zt){if(r&&r.outMediaTrack){let a=r.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=o.profile.bitrate*1e3,o.small&&(this._mediaSettings.smallVideoWidth=o.small.width,this._mediaSettings.smallVideoHeight=o.small.height,this._mediaSettings.smallVideoFps=o.small.frameRate,this._mediaSettings.smallVideoBps=o.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else r&&r.outMediaTrack&&(this._mediaSettings.audioChannel=r.profile.channelCount,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=r.profile.sampleRate),o&&o.outMediaTrack&&(this._mediaSettings.videoWidth=o.profile.width,this._mediaSettings.videoHeight=o.profile.height,this._mediaSettings.videoFps=o.profile.frameRate,this._mediaSettings.videoBps=o.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:q.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:B.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?m.AUXILIARY:m.MAIN} stream`),gt()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return f(this,null,function*(){var o;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===m.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)!=null&&o.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===z.INACTIVE&&(yield this.setTransceiverDirection(z.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return f(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;Qt()&&this._peerConnection.getTransceivers().findIndex(o=>o.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",t));let r=this._peerConnection.getSenders().find(o=>o.track&&o.track.kind===t.kind);if(r&&r.track){this._log.warn("sender already exists, remove sender first");let o=r.track;this.removeSender(r),yield this.updateOffer("remove",o)}if(t&&this._peerConnection.addTrack(t,new MediaStream([t])),t.kind===m.VIDEO&&e instanceof $e&&e.small){let o=new MediaStream,{smallTrack:n}=this._room.videoManager;o.addTrack(n),this._peerConnection.addTrack(n,o)}yield this.updateOffer("add",t)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===Gr||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=ge(e);for(let r=0;r<t.media.length;r++)if(Number(t.media[r].mid)===0&&t.media[r].type===m.VIDEO)return!0;return!1}removeSender(e){let t=null;Qt()&&(t=this._peerConnection.getTransceivers().find(r=>r.sender&&r.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&oe(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?m.AUXILIARY:m.MAIN} stream`),gt()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return f(this,null,function*(){if(!e.outMediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===m.AUDIO)yield r[0].sender.replaceTrack(null);else{let o=t?3:1;yield r[o].sender.replaceTrack(null),o===1&&e.small&&(yield r[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(z.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return f(this,null,function*(){if(!ae)return;let r=!1,o=!1;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let n=this._peerConnection.getTransceivers();if(t.forEach(l=>{n[l].direction!==e&&(n[l].direction=e,r=!0)}),r){this._log.info("updating offer");let l=yield this._peerConnection.createOffer();yield this.setOffer(l)}let a=-1,c=this._peerConnection.remoteDescription.sdp.split(`\r
|
|
63
63
|
`).map(l=>{if(l.match(new RegExp(`a=(${z.INACTIVE}|${z.RECVONLY}|${z.SENDONLY})`))&&a++,t.includes(a)){if(e===z.INACTIVE&&l.includes(`a=${z.RECVONLY}`))return o=!0,`a=${e}`;if(e===z.SENDONLY&&l.includes(`a=${z.INACTIVE}`))return o=!0,`a=${z.RECVONLY}`}return l}).join(`\r
|
|
@@ -106,7 +106,7 @@ void main() {
|
|
|
106
106
|
void main() {
|
|
107
107
|
gl_Position = vertexPos;
|
|
108
108
|
textureCoord = texturePos;
|
|
109
|
-
}`});d(this,"yTextureRef");d(this,"uTextureRef");d(this,"vTextureRef");d(this,"Y");d(this,"U");d(this,"V");this.useProgram();let t=this.context.ctx;t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),this.setTexBuffer([0,1,1,1,0,0,1,0]),this.yTextureRef=this._initTexture("ySampler",0),this.uTextureRef=this._initTexture("uSampler",1),this.vTextureRef=this._initTexture("vSampler",2),this._canvas=e._canvas}_initTexture(e,t){let r=this.context.ctx,o=r.createTexture();return r.bindTexture(r.TEXTURE_2D,o),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.bindTexture(r.TEXTURE_2D,null),r.uniform1i(r.getUniformLocation(this.program,e),t),o}render(e){let t=this.context.ctx,r=this.width,o=this.height;return this.useProgram(),t.viewport(0,0,r,o),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.yTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r,o,t.LUMINANCE,t.UNSIGNED_BYTE,this.Y),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this.uTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r/2,o/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.U),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this.vTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r/2,o/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.V),this.draw(),!0}resize(e,t){super.resize(e,t);let r=this.context.ctx;r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,this.yTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e,t,0,r.LUMINANCE,r.UNSIGNED_BYTE,null),r.activeTexture(r.TEXTURE1),r.bindTexture(r.TEXTURE_2D,this.uTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e/2,t/2,0,r.LUMINANCE,r.UNSIGNED_BYTE,null),r.activeTexture(r.TEXTURE2),r.bindTexture(r.TEXTURE_2D,this.vTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e/2,t/2,0,r.LUMINANCE,r.UNSIGNED_BYTE,null)}};var pu=[s=>{s.codec="avc1.420028"},s=>{delete s.hardwareAcceleration}],np=(s,i)=>{switch(s){case"webCodecs":return i==="videoFrame"?514705:514706;case"wasm":return i==="webgl"?514707:i==="videoFrame"?514708:514709}throw new Error("decoder type not supported")},cd=class{constructor(i){d(this,"trackDoneOB");d(this,"startOB");d(this,"stopOB");d(this,"decoder");d(this,"videoContext");d(this,"gop",0);d(this,"gop_helper",0);d(this,"waitFirstKeyFrame",!0);d(this,"startTimestamp",0);d(this,"startTime",0);d(this,"startPerformanceTime",0);d(this,"inputFrameCount",0);d(this,"decodedFrameCount",0);d(this,"downgradeLevel",0);d(this,"config");d(this,"videoElement");d(this,"type","wasm");d(this,"renderer","2d");d(this,"wasmOption");d(this,"createDecoder");d(this,"_decodeSink");d(this,"isReported",!1);let{track:e,createDecoder:t}=i;if(this.createDecoder=t,this.wasmOption={yuvMode:i.renderer==="webgl",wasmPath:i.wasmPath,workerMode:i.workerMode,canvas:i.canvas},this.config=i.config,this.videoElement=i.videoElement,this.renderer=i.renderer,this.trackDoneOB=Ie(e,Q.INIT),this.stopOB=ot(this.trackDoneOB),i.type==="auto"){switch(i.fallback){case"wasm":this.type="wasm",this.renderer="webgl";break;case"wasm_2d":this.type="wasm",this.renderer="2d";break;case"wasm_video":this.type="wasm",this.renderer="videoFrame";break;default:this.type="webCodecs"}this.wasmOption.yuvMode=this.renderer==="webgl"}else this.type=i.type;this.changeRenderer(this.renderer),this.startOB=ot();let r=ot(),o;_e(r,Rl((a,c)=>(a!==c&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:o,prevState:a,state:c}),c),"INITIALIZED"),we(this.stopOB),Ne());let n=a=>{let c=this.pipe(e);return r.next("STARTING"),e.log.info(`decoder type: ${this.type} renderer: ${this.renderer}`),_e(c,we(this.stopOB),Ne(()=>{e.stat.framesDecoded++},l=>{if(e.log.error(l),N.addFailedEvent({key:np(this.type,this.renderer),error:l}),a>4)this.startOB.error(l);else{switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":switch(this.renderer){case"webgl":this.changeRenderer("videoFrame");break}}this.startOB.next(a+1)}})),_e(c,Li(1),Fo(Dr))};_e(this.startOB,vr(0),tr(n),we(this.stopOB),Ne(()=>{e.player.handlePlaying("canvas"),r.next("STARTED")},a=>{o=a,r.next("FAILED")},()=>{N.addSuccessEvent({key:np(this.type,this.renderer)}),N.addSuccessEvent({key:514704})}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.startOB.next(0)}close(i){this.stopOB.next(i)}changeRenderer(i){this.renderer=i,this.renderer==="videoFrame"&&!Ac()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(i){var r;if(this.inputFrameCount++,((r=this.decoder)==null?void 0:r.state)!=="configured")return i;let e=i.type==="key",{timestamp:t}=i;if(e?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder&&this.decoder.state==="configured"){if(this.waitFirstKeyFrame)if(e)this.waitFirstKeyFrame=!1,this.startTimestamp=t,this.startTime=Date.now(),this.startPerformanceTime=L();else return;let o=(t-this.startTimestamp)/90,a=Date.now()-this.startTime-o,c=a<500?0:a/1e3>>0;switch(e&&(c>0?this.downgradeLevel++:this.downgradeLevel>3&&this.downgradeLevel--),this.downgradeLevel){case 0:break;case 1:break;case 2:if(this.gop_helper>this.gop>>1)return;break;case 3:if(this.gop_helper>0)return;break;default:return}this.decoder.decode(i);return}return i}pipe(i){return Mi()(e=>f(this,null,function*(){this._decodeSink=e,e.defer(()=>{var o,n;(o=this.decoder)==null||o.close(),(n=this.videoContext)==null||n.destroy(),delete this._decodeSink});let{renderer:t,type:r}=this;try{switch(r){case"wasm":this.decoder=this.createDecoder(r,this.wasmOption);break;case"webCodecs":for(let o=0;o<=pu.length;o++){let{supported:n}=yield VideoDecoder.isConfigSupported(this.config);if(n)break;if(o===pu.length){e.error(3);return}pu[o](this.config)}this.decoder=this.createDecoder(r);break;case"mse":throw new Error("not supported yet")}if(this.decoder.on("videoFrame",o=>{this.decodedFrameCount++,e.next(o)}),this.decoder.on("error",o=>{i.log.error(o),e.error(r==="webCodecs"?4:8)}),yield this.decoder.initialize(this.videoElement),this.decoder.configure(this.config),r==="wasm"&&t==="webgl"){this.videoContext=new ke({frameRate:15,logger:i.log,name:i.userId}),this.videoContext.create(),this.videoContext.on(ke.UNAVAILABLE,n=>{i.log.error(n),e.error(7)});let o=new dd(this.videoContext);this.decoder.on("videoCodecInfo",n=>o.resize(n.width,n.height)),this.decoder.on("videoFrame",n=>{[o.Y,o.U,o.V]=n,this.downgradeLevel===1?this.decodedFrameCount%2===0&&o.render(this.decodedFrameCount):o.render(this.decodedFrameCount)}),i.source=o,i.player.setCanvas(this.videoContext._canvas,2)}else if(t==="videoFrame"){i.player.setCanvas();let o=new MediaStreamTrackGenerator({kind:"video"}),n=o.writable.getWriter();i.setInputMediaStreamTrack(o),this.decoder.on("videoFrame",a=>{n.write(a)}),o.onmute=()=>{e.error(r==="webCodecs"?5:9)},e.defer(()=>o.onmute=null)}else{this.videoContext=new Ge({frameRate:15,logger:i.log,name:i.userId}),this.videoContext.create({alpha:!1});let o=this.videoContext.createVideoImageSource();this.decoder.on("videoFrame",a=>{o.image=a,o.update()});let n=new kr(this.videoContext,{name:"remotePlayer",logger:i.log});o.connect(n),i.source=o,i.player.setCanvas(this.videoContext._canvas,2)}}catch(o){i.log.error(o),e.error(r==="webCodecs"?2:6)}}))}};var en=class extends ap.EventEmitter{constructor(e){super();this.room=e;d(this,"videoContext");d(this,"_glVideoContext");d(this,"_2dVideoContext");d(this,"destination");d(this,"smallVideoContext");d(this,"smallDestination");d(this,"smallTrackSource");d(this,"smallImageSource");d(this,"_isMirror",!1);d(this,"cameraTrack");d(this,"cameraNode");d(this,"mirrorNode");d(this,"mixNode");d(this,"screenTrack");d(this,"screenNode");d(this,"selfModel",!1);d(this,"blurRadius",3);d(this,"arTrack");d(this,"Wasm");d(this,"waterMarkNode");d(this,"_waterMarkOption");d(this,"watermarkImageList",[]);d(this,"_beautyParams");d(this,"isUsingArTrack",!1);d(this,"_isMixScreen",!1);d(this,"_virtualBackground");d(this,"_virtualBackgroundAbortCallback");d(this,"virtualBackgroundInstance");d(this,"_bgAssetPath");d(this,"log",C.createLogger({id:"vm"}));d(this,"_checkId",0);d(this,"_use2d",!1);d(this,"_autoSwitchRenderMode",!0);d(this,"_selfieSegmentation");d(this,"encodePipeline",[]);d(this,"decodePipeline",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new Ge({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 Ge({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new ke({frameRate:15,logger:this.log,name:"m"});else if(this._glVideoContext.available)return this._glVideoContext;return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(),this._glVideoContext.on("unavailable",e=>{var t;this.emit("error",e),this.log.warn("video context unavailable",e),(t=this._virtualBackgroundAbortCallback)==null||t.call(this,e),this.update().catch(r=>{this.log.error(r)})})}catch(e){this.emit("error",e)}}enablePrintDetail(e=2e3){this._checkId=re.run("interval",()=>{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(Ji||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",t){let r=e==="videoCtxGl"?512700:512701;t?N.addFailedEvent({key:r,error:t}):N.addSuccessEvent({key:r})}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{if(this._glVideoContext=new ke({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),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 r=this.cameraTrack,{small:o,settings:n,player:a}=r;o?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new Pa(this.smallVideoContext,o,this.log)),this.smallVideoContext.frameRate=o.frameRate,this.smallDestination.resolution=o,e?(this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.connect(this.smallDestination))):(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource?this.smallTrackSource.replaceTrack(this.initialTrack):(this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource"),this.smallTrackSource.width=n.width,this.smallTrackSource.height=n.height,this.smallTrackSource.connect(this.smallDestination)))):this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource),Ji&&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"}`),r.setOutputMediaStreamTrack(c)}catch(r){this.log.error("set main output failed",r)}}update(){return f(this,null,function*(){var r,o;if(!this.cameraTrack||!this.cameraTrack.mediaTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:e,profile:t}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log})),at===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof Pi?(this.cameraNode.close(),delete this.cameraNode):this.cameraNode.image=this.initialTrack.canvas),this.cameraNode||(this.cameraNode=this.videoContext.createVideoImageSource(this.initialTrack.canvas,{name:"cameraCanvasSource",logger:this.log}))):(this.cameraNode&&(this.cameraNode instanceof Pi?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode.close(),delete this.cameraNode)),this.cameraNode||(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraTrackSource"))):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.disableCheckMute():this.destination=new La(this.videoContext,{name:"mainDestination",logger:this.log}),this.cameraNode=new ad(this.videoContext,{input:this.cameraTrack.mediaTrack,width:e.width,height:e.height,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.destination.enableCheckMute()),this.videoContext.frameRate=t.frameRate,this._use2d){let n=this.cameraNode;n.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new od(this.videoContext,this.log)),n=n.connect(this.mirrorNode),n.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new nd(this.videoContext,this.log),n.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption&&(this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y),(r=this.waterMarkNode)==null||r.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource")),(o=this.screenNode)==null||o.connect(this.mixNode,{zIndex:0}),n=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)),n.connect(this.destination)}return this.log.info(`update ${this._use2d?"2d":"webgl"}`),this._setMainOutput(this.videoContext._canvas)})}changeInput(e){var t,r,o,n;if(e instanceof st)return this.log.info("change screen input",(t=e.mediaTrack)==null?void 0:t.label),this.setScreenTrack(e);if(e instanceof $e)return this.log.info("change video input",(r=e.mediaTrack)==null?void 0:r.label),this.setCameraTrack(e);if(e instanceof oi){this.log.info("change remote input",(o=e.mediaTrack)==null?void 0:o.label);let a=e.mediaTrack;return e.setOutputMediaStreamTrack(a)}this.log.warn("change unknown input",(n=e.mediaTrack)==null?void 0:n.label)}removeInput(e){var t;e instanceof st?((t=this.screenNode)==null||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof $e?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof oi&&e.source&&e.source.context.destroy()}setCameraTrack(e){return f(this,null,function*(){this.cameraTrack=e,this.update()})}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,t){return f(this,null,function*(){let r=document.createElement("canvas");t&&e&&(r.height=t,r.width=e);let o=r.getContext("2d");if(!o)throw new b({code:S.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((n,a)=>n.zIndex-a.zIndex),this.watermarkImageList.forEach(({image:n,x:a,y:c,width:l,height:h})=>{o.drawImage(n,a,c,l,h)}),Yr(r.toDataURL())})}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some(o=>o.imageUrl===e.imageUrl&&o.height===e.height&&o.width===e.width&&o.x===e.x&&o.y===e.y&&o.type===e.type&&o.zIndex===e.zIndex)||((t==="mute"||t==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(o=>o.type!==t)),this.watermarkImageList.push(e))}setBeautyParams(e){return 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*(){var u,p;let t;try{t=yield Yr((e==null?void 0:e.imageElement)||e.imageUrl)}catch(_){throw new b({code:S.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:r=0,y:o=0,width:n=t.width,height:a=t.height,type:c="watermark",zIndex:l=2}=e;this.watermarkImageList.some(_=>_.type===c)?(this.watermarkImageList=this.watermarkImageList.filter(_=>_.type!==c),this.pushWaterMarkImageList({x:r,y:o,width:n,height:a,image:t,zIndex:l,type:c,imageUrl:e.imageUrl}),t=yield this.getWatermarkImage((u=this.cameraTrack)==null?void 0:u.settings.width,(p=this.cameraTrack)==null?void 0:p.settings.height),this._waterMarkOption={x:0,y:0,width:t.width,height:t.height,image:t},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(t.width,t.height),this.waterMarkNode.image=t):this.update()):(this.pushWaterMarkImageList({x:r,y:o,width:n,height:a,image:t,zIndex:l,type:c,imageUrl:e.imageUrl}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(_,I)=>_==="imageUrl"?void 0:I))})}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,(t,r)=>t==="imageUrl"?void 0:r)),yield this.freshWatermark()})}freshWatermark(){return f(this,null,function*(){var t,r,o;(t=this.waterMarkNode)==null||t.close(),delete this.waterMarkNode,delete this._waterMarkOption;let e=yield this.getWatermarkImage((r=this.cameraTrack)==null?void 0:r.settings.width,(o=this.cameraTrack)==null?void 0:o.settings.height);this._waterMarkOption={x:0,y:0,width:e.width,height:e.height,image:e},this.update()})}setVirtualBackground(e){return f(this,null,function*(){if(!e)delete this._virtualBackground,delete this._virtualBackgroundAbortCallback;else{if(e.onAbort&&(this._virtualBackgroundAbortCallback=e.onAbort),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 Yr(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type)}if(this.log.info(`${this._virtualBackground?"start":"stop"} virtual background, ${(e==null?void 0:e.type)||""}, ${this.blurRadius||""}`),yield this.update(),this._virtualBackground&&!this._glVideoContext.available)throw new b({code:S.INVALID_OPERATION,message:`webgl context create failed, ${this._glVideoContext.error}`})})}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()}createDecodeContext(e){return new cd(e)}clear(){var e;(e=this.videoContext)==null||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};y([ha(function(e){this.log.error("update failed",e)})],en.prototype,"update",1);var MT=0;var ld=class extends Q{constructor(e){super("room");d(this,"seq",++MT);d(this,"sdkAppId");d(this,"userId");d(this,"userSig");d(this,"privateMapKey");d(this,"latencyLevel");d(this,"tinyId");d(this,"scene");d(this,"roomId");d(this,"useStringRoomId");d(this,"role","anchor");d(this,"joinParams",null);d(this,"localTracks",new Set);d(this,"enableAutoPlayDialog",!0);d(this,"autoReceiveAudio",!0);d(this,"autoReceiveVideo",!0);d(this,"proxy_ws");d(this,"proxy_wt");d(this,"proxy_unified");d(this,"checkSystemResult",{result:!0,detail:{isBrowserSupported:!0,isWebRTCSupported:!0,isWebCodecsSupported:!0,isMediaDevicesSupported:!0,isScreenShareSupported:!0,isSmallStreamSupported:!0,isH264EncodeSupported:!0,isVp8EncodeSupported:!0,isH264DecodeSupported:!0,isVp8DecodeSupported:!0}});d(this,"keyPointManager");d(this,"audioManager");d(this,"videoManager");d(this,"callDurationCalculator");d(this,"badCaseDetector");d(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null});d(this,"videoDecodeFallbackType");d(this,"_isUsingCachedSchedule",!1);d(this,"_log",C.createLogger({id:`r${this.seq}`}));d(this,"_joinedTimestamp",0);d(this,"_sdkType");d(this,"heartbeatReport");d(this,"quality");d(this,"enableSEI");d(this,"isDestroyed",!1);this.useStringRoomId=!!e.useStringRoomId,me(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),me(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),me(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new rp({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new sp({room:this}),this.badCaseDetector=new op({room:this}),this.audioManager=new ga(this),this.videoManager=new en(this)}get scriptTransformWorker(){}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(K(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(Ze(e)){let{websocketProxy:t,webtransportProxy:r,loggerProxy:o,scheduleProxy:n,unifiedProxy:a}=e;this.proxy_ws=t,this.proxy_wt=r,this.proxy_unified=a,a?(Ba([a,a]),nr(`https://${a}`)):(o&&nr(o),n&&Ba(n))}E.once(T.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:mt.main,sched_back_domain:mt.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 r of this.quality.downlinkInfo)e.downlinksRTT[r.userId]=r.rtt;return e})}getRemoteVideoStats(){return f(this,arguments,function*(e="main"){let t={};return this.remotePublishedUserMap.forEach(r=>{let o=e==="auxiliary"?r.remoteAuxiliaryTrack:r.remoteVideoTrack;t[r.userId]=o.stat}),t})}checkDestroy(){if(this.isDestroyed)throw new b({code:S.INVALID_OPERATION,message:V({key:w.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Oe.INVALID_DESTROY),new b({code:S.INVALID_OPERATION,message:V({key:w.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,E.emit(T.ROOM_DESTROY,{room:this})}schedule(e,t){return f(this,null,function*(){var o,n,a;let r=L();try{let{isCached:c,result:l,detailCost:h}=yield xl({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=c,this._log.info(`schedule cache:${+c} ${ft(l,{keysToExclude:["username","credential"]})}`),c&&E.once(T.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=v(v({},this.scheduleResult),l),Y((o=l.config)==null?void 0:o.retryCount)&&Nd(l.config.retryCount),K((n=l.config)==null?void 0:n.loggerDomain)&&nr(l.config.loggerDomain),this.videoDecodeFallbackType=((a=l.config)==null?void 0:a.videoDecodeFallback)||this.videoDecodeFallbackType,E.emit(T.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:h}),N.addSuccessEvent({key:521700,cost:L()-r,split:50})}catch(c){throw N.addFailedEvent({key:521700,error:c}),c}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}};var Ep=Pe(je());var fu=Pe(ou());var dp=s=>{let i=ge(s),e={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return i.media.forEach((t,r)=>{var o;if(t.ssrcs&&!g(t.ssrcs[0].id)){let n=Number(t.ssrcs[0].id),a=Number((o=t.ssrcs.filter(c=>c.attribute==="cname")[1])==null?void 0:o.id);switch(r){case 0:e.audioSsrc=n;break;case 1:e.bigVideoSsrc=n,e.bigVideoRtxSsrc=a;break;case 2:e.smallVideoSsrc=n,e.smallVideoRtxSsrc=a;break;case 3:e.auxVideoSsrc=n,e.auxVideoRtxSsrc=a;break}}}),e};function cp(s){var e;let i=[];for(let t=0;t<s.rtp.length;t++){if(["rtx","red","ulpfec"].includes(s.rtp[t].codec))continue;let r=s.fmtp.filter(o=>o.payload===s.rtp[t].payload)[0];i.push({payload:s.rtp[t].payload,codec:s.rtp[t].codec,fmtp:r?r.config:"",rate:s.rtp[t].rate,rtx:((e=s.rtp[t+1])==null?void 0:e.codec)==="rtx"?s.rtp[t+1].payload:0,rtcpfb:((s==null?void 0:s.rtcpFb)||[]).filter(o=>o.payload===s.rtp[t].payload).map(({type:o,subtype:n})=>({id:o,params:n?[n]:[]}))})}return i}function LT(){return f(this,null,function*(){let s=new RTCPeerConnection;s.addTransceiver(m.VIDEO,{direction:m.TRANSCEIVER_DIRECTION_RECVONLY});let i=yield s.createOffer();if(!i.sdp)return[];let e=ge(i.sdp),t=cp(e.media[0]);return s.close(),t})}var lp=(s,i)=>f(void 0,null,function*(){var c;let e=ge(s),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 r=e.media[0],o=e.media[1];r.ext&&(t.audio.extensions=r.ext.map(l=>({id:l.value,uri:l.uri}))),o.ext&&(t.video.extensions=o.ext.map(l=>({id:l.value,uri:l.uri})));let n={codec:r.rtp[0].codec,fmtp:r.fmtp[0].config,payload:r.fmtp[0].payload,rate:r.rtp[0].rate,channels:r.rtp[0].encoding,rtcpfb:[],rtx:0};(c=r.rtcpFb)==null||c.forEach(({payload:l,type:h,subtype:u})=>{if(l===n.payload){let p={id:h,params:[]};u&&p.params.push(u),n.rtcpfb.push(p)}}),t.audio.codecs.push(n);let a=["h264","vp8"];return i&&a.shift(),t.video.codecs=[...cp(o)].filter(l=>a.includes(l.codec.toLocaleLowerCase())),t.video.decoders=(yield LT()).filter(l=>["h264","vp8"].includes(l.codec.toLocaleLowerCase())),t}),up=({serverAbility:s,clientAbility:i,offerSDP:e,enableCustomMessage:t})=>{let r=ge(e),o={extmapAllowMixed:"extmap-allow-mixed",groups:r.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},n={candidates:s.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:m.TRANSCEIVER_DIRECTION_RECVONLY,ext:s.audio.extensions.map(a=>({value:a.id,uri:a.uri})),fingerprint:{type:s.dtls.hash,hash:s.dtls.fingerprint},fmtp:[{payload:s.audio.codecs[0].payload,config:s.audio.codecs[0].fmtp}],icePwd:s.ice.password,iceUfrag:s.ice.ufrag,mid:"0",payloads:String(s.audio.codecs[0].payload),port:r.media[0].port,protocol:r.media[0].protocol,type:m.AUDIO,setup:s.dtls.setup,rtcpFb:s.audio.codecs[0].rtcpfb.map(a=>({payload:s.audio.codecs[0].payload,type:a.id,subtype:a.params[0]})),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:s.audio.codecs[0].payload,codec:s.audio.codecs[0].codec,rate:s.audio.codecs[0].rate,encoding:s.audio.codecs[0].channels}]};return o.media.push(n),[1,2,3].forEach(a=>{o.media.push(_u({mid:a,serverAbility:s,clientAbility:i,parsedOffer:r}))}),t&&o.media.push(r.media.find(a=>a.mid==="dc")),It(o)},_u=({mid:s,serverAbility:i,clientAbility:e,parsedOffer:t,isDownlink:r=!1})=>{let o={candidates:i.candidates.map(n=>({component:1,foundation:"1",generation:0,ip:n.ip,port:n.port,priority:n.priority,transport:n.foundation,type:n.type})),connection:{version:4,ip:"0.0.0.0"},direction:m.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map(n=>({value:n.id,uri:n.uri})),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(s),payloads:"",port:t.media[0].port,protocol:t.media[0].protocol,type:m.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(r){let n=i.video.decoders;(!n||n.length===0)&&(n=i.video.codecs),(!n||n.length===0)&&(n=e.video.decoders),n.forEach(a=>{Br(o,a)})}else{let n=i.video.codecs.findIndex(c=>c.codec.toLowerCase()===(i.useVp8?"vp8":"h264")),a=i.video.codecs[n]||e.video.codecs[0];Br(o,a)}return o},Br=(s,i)=>{s.payloads=`${s.payloads} ${i.payload}`.trim(),s.fmtp.push({payload:i.payload,config:i.fmtp}),s.rtcpFb=[...s.rtcpFb||[],...i.rtcpfb.map(e=>({payload:i.payload,type:e.id,subtype:e.params[0]}))],s.rtp.push({payload:i.payload,codec:i.codec.toUpperCase(),rate:i.rate}),i.rtx&&(s.payloads=`${s.payloads} ${i.rtx}`,s.fmtp.push({payload:i.rtx,config:`apt=${i.payload}`}),s.rtp.push({payload:i.rtx,codec:"rtx",rate:i.rate}))};function PT(s){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"]);s.ext&&(s.ext=s.ext.filter(e=>!i.has(e.uri)))}function xT(s){if(!s.rtcpFb)return;let i=[];s.rtcpFb.forEach((e,t)=>{var r;i.push(e),s.rtcpFb&&((r=s.rtcpFb[t+1])==null?void 0:r.payload)!==e.payload&&e.type!=="rrtr"&&i.push({payload:e.payload,type:"rrtr"})}),s.rtcpFb=i}function wT(s){s.type===m.VIDEO&&s.fmtp&&s.fmtp.forEach(i=>{i.config.includes("apt")||(i.config+=";sps-pps-idr-in-keyframe=1")})}function UT(s){s.type===m.AUDIO&&s.fmtp&&s.fmtp.forEach(i=>{i.config+=";sprop-stereo=1;stereo=1"})}var hp=(s,i,e)=>{let t=fu.default.parse(s);return t.media.forEach((r,o)=>{var n;if((r.type===m.AUDIO||r.type===m.VIDEO)&&(xT(r),wT(r),UT(r),PT(r),r.type===m.VIDEO)){if(o<4)r.payloads="",r.fmtp=[],r.rtp=[],r.rtcpFb=[],i.video.codecs.forEach(a=>Br(r,a));else if(e){r.payloads="",r.fmtp=[],r.rtp=[],r.rtcpFb=[];let a=e.video.decoders;(!a||a.length===0)&&(a=e.video.codecs),(!a||a.length===0)&&(a=i.video.decoders),a.forEach(c=>Br(r,c))}}(n=r.payloads)!=null&&n.includes("datachannel")&&t.groups&&r.mid&&(t.groups[0].mids=t.groups[0].mids.replace(r.mid,"dc"),r.mid="dc")}),fu.default.write(t)};var mp=Pe(je());var ud=class extends mp.EventEmitter{constructor(e){super();this.room=e;d(this,"mainFpsHealth",1);d(this,"mainBitrateHealth",1);d(this,"badMainBitrateHealthCount",0);d(this,"lastEmitBadHealthTime",0);d(this,"log");!pe&&Ot&&E.on("262",this.onVideoCodecChanged,this),this.log=e.getLogger().createChild({id:"h-d"})}onVideoCodecChanged({remoteUserId:e,streamType:t,isHWCodec:r,codec:o}){if(!(e||t===7||o!=="h264")){if(!r){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 r=t.uint32_video_enc_fps/t.uint32_video_capture_fps;t.uint32_video_stream_type===2&&(this.mainFpsHealth=r)}if(t.uint32_video_codec_bitrate&&t.uint32_video_stream_type===2){let{localMainVideoTrack:r}=this.room;r&&(this.mainBitrateHealth=t.uint32_video_codec_bitrate/1e3/r.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(){E.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};d(ud,"EVENT_BAD_HEALTH","bad_health");var pp=ud;function fp({seiMessageList:s,isAudio:i,isMain:e}){return new TransformStream({transform(t,r){let o=t;i?audioEncodePipeline.forEach(n=>{o=n({frame:o})}):videoEncodePipeline.forEach(n=>{o=n({frame:o,seiMessageList:s,onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:o.data,userId:"",streamType:e?"main":"auxiliary"})}})}),r.enqueue(o)}})}function _p(s,i,e){return new TransformStream({transform(t,r){let o=t;videoDecodePipeline.forEach(n=>{o=n({frame:o,onSEI:a=>{a.forEach(c=>{self.postMessage({type:"sei",seiPayloadType:c.seiPayloadType,data:c.seiPayload.buffer,userId:s,streamType:i})})},onDump:()=>{self.postMessage({type:"dump",isAudio:e,data:o.data,userId:s,streamType:i})}})}),r.enqueue(o)}})}function gp(s){let i=[Di],e=[ql,Wl,Jl,Gl,fp,_p],t=()=>{let l=[],h=[],u=[];self.onmessage=p=>{p.data.type==="sei"&&(p.data.isMain?(l.push(p.data.data),p.data.small&&u.push(p.data.data)):h.push(p.data.data))},self.onrtctransform=p=>{let{options:_}=p.transformer,I=_.isReceiver?_p(_.userId,_.streamType,_.isAudio):fp({isAudio:_.isAudio,seiMessageList:_.isMain?_.small?u:l:h,isMain:_.isMain});p.transformer.readable.pipeThrough(I).pipeTo(p.transformer.writable)}},r=`const videoEncodePipeline=[${s.videoEncodePipeline.toString()}];
|
|
109
|
+
}`});d(this,"yTextureRef");d(this,"uTextureRef");d(this,"vTextureRef");d(this,"Y");d(this,"U");d(this,"V");this.useProgram();let t=this.context.ctx;t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),this.setTexBuffer([0,1,1,1,0,0,1,0]),this.yTextureRef=this._initTexture("ySampler",0),this.uTextureRef=this._initTexture("uSampler",1),this.vTextureRef=this._initTexture("vSampler",2),this._canvas=e._canvas}_initTexture(e,t){let r=this.context.ctx,o=r.createTexture();return r.bindTexture(r.TEXTURE_2D,o),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.bindTexture(r.TEXTURE_2D,null),r.uniform1i(r.getUniformLocation(this.program,e),t),o}render(e){let t=this.context.ctx,r=this.width,o=this.height;return this.useProgram(),t.viewport(0,0,r,o),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.yTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r,o,t.LUMINANCE,t.UNSIGNED_BYTE,this.Y),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this.uTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r/2,o/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.U),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this.vTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,r/2,o/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.V),this.draw(),!0}resize(e,t){super.resize(e,t);let r=this.context.ctx;r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,this.yTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e,t,0,r.LUMINANCE,r.UNSIGNED_BYTE,null),r.activeTexture(r.TEXTURE1),r.bindTexture(r.TEXTURE_2D,this.uTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e/2,t/2,0,r.LUMINANCE,r.UNSIGNED_BYTE,null),r.activeTexture(r.TEXTURE2),r.bindTexture(r.TEXTURE_2D,this.vTextureRef),r.texImage2D(r.TEXTURE_2D,0,r.LUMINANCE,e/2,t/2,0,r.LUMINANCE,r.UNSIGNED_BYTE,null)}};var pu=[s=>{s.codec="avc1.420028"},s=>{delete s.hardwareAcceleration}],np=(s,i)=>{switch(s){case"webCodecs":return i==="videoFrame"?514705:514706;case"wasm":return i==="webgl"?514707:i==="videoFrame"?514708:514709}throw new Error("decoder type not supported")},cd=class{constructor(i){d(this,"trackDoneOB");d(this,"startOB");d(this,"stopOB");d(this,"decoder");d(this,"videoContext");d(this,"gop",0);d(this,"gop_helper",0);d(this,"waitFirstKeyFrame",!0);d(this,"startTimestamp",0);d(this,"startTime",0);d(this,"startPerformanceTime",0);d(this,"inputFrameCount",0);d(this,"decodedFrameCount",0);d(this,"downgradeLevel",0);d(this,"config");d(this,"videoElement");d(this,"type","wasm");d(this,"renderer","2d");d(this,"wasmOption");d(this,"createDecoder");d(this,"_decodeSink");d(this,"isReported",!1);let{track:e,createDecoder:t}=i;if(this.createDecoder=t,this.wasmOption={yuvMode:i.renderer==="webgl",wasmPath:i.wasmPath,workerMode:i.workerMode,canvas:i.canvas},this.config=i.config,this.videoElement=i.videoElement,this.renderer=i.renderer,this.trackDoneOB=Ie(e,Q.INIT),this.stopOB=ot(this.trackDoneOB),i.type==="auto"){switch(i.fallback){case"wasm":this.type="wasm",this.renderer="webgl";break;case"wasm_2d":this.type="wasm",this.renderer="2d";break;case"wasm_video":this.type="wasm",this.renderer="videoFrame";break;default:this.type="webCodecs"}this.wasmOption.yuvMode=this.renderer==="webgl"}else this.type=i.type;this.changeRenderer(this.renderer),this.startOB=ot();let r=ot(),o;_e(r,Rl((a,c)=>(a!==c&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:o,prevState:a,state:c}),c),"INITIALIZED"),Ue(this.stopOB),Ne());let n=a=>{let c=this.pipe(e);return r.next("STARTING"),e.log.info(`decoder type: ${this.type} renderer: ${this.renderer}`),_e(c,Ue(this.stopOB),Ne(()=>{e.stat.framesDecoded++},l=>{if(e.log.error(l),N.addFailedEvent({key:np(this.type,this.renderer),error:l}),a>4)this.startOB.error(l);else{switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":switch(this.renderer){case"webgl":this.changeRenderer("videoFrame");break}}this.startOB.next(a+1)}})),_e(c,Li(1),Fo(Dr))};_e(this.startOB,vr(0),tr(n),Ue(this.stopOB),Ne(()=>{e.player.handlePlaying("canvas"),r.next("STARTED")},a=>{o=a,r.next("FAILED")},()=>{N.addSuccessEvent({key:np(this.type,this.renderer)}),N.addSuccessEvent({key:514704})}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.startOB.next(0)}close(i){this.stopOB.next(i)}changeRenderer(i){this.renderer=i,this.renderer==="videoFrame"&&!Ac()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(i){var r;if(this.inputFrameCount++,((r=this.decoder)==null?void 0:r.state)!=="configured")return i;let e=i.type==="key",{timestamp:t}=i;if(e?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder&&this.decoder.state==="configured"){if(this.waitFirstKeyFrame)if(e)this.waitFirstKeyFrame=!1,this.startTimestamp=t,this.startTime=Date.now(),this.startPerformanceTime=L();else return;let o=(t-this.startTimestamp)/90,a=Date.now()-this.startTime-o,c=a<500?0:a/1e3>>0;switch(e&&(c>0?this.downgradeLevel++:this.downgradeLevel>3&&this.downgradeLevel--),this.downgradeLevel){case 0:break;case 1:break;case 2:if(this.gop_helper>this.gop>>1)return;break;case 3:if(this.gop_helper>0)return;break;default:return}this.decoder.decode(i);return}return i}pipe(i){return Mi()(e=>f(this,null,function*(){this._decodeSink=e,e.defer(()=>{var o,n;(o=this.decoder)==null||o.close(),(n=this.videoContext)==null||n.destroy(),delete this._decodeSink});let{renderer:t,type:r}=this;try{switch(r){case"wasm":this.decoder=this.createDecoder(r,this.wasmOption);break;case"webCodecs":for(let o=0;o<=pu.length;o++){let{supported:n}=yield VideoDecoder.isConfigSupported(this.config);if(n)break;if(o===pu.length){e.error(3);return}pu[o](this.config)}this.decoder=this.createDecoder(r);break;case"mse":throw new Error("not supported yet")}if(this.decoder.on("videoFrame",o=>{this.decodedFrameCount++,e.next(o)}),this.decoder.on("error",o=>{i.log.error(o),e.error(r==="webCodecs"?4:8)}),yield this.decoder.initialize(this.videoElement),this.decoder.configure(this.config),r==="wasm"&&t==="webgl"){this.videoContext=new ke({frameRate:15,logger:i.log,name:i.userId}),this.videoContext.create(),this.videoContext.on(ke.UNAVAILABLE,n=>{i.log.error(n),e.error(7)});let o=new dd(this.videoContext);this.decoder.on("videoCodecInfo",n=>o.resize(n.width,n.height)),this.decoder.on("videoFrame",n=>{[o.Y,o.U,o.V]=n,this.downgradeLevel===1?this.decodedFrameCount%2===0&&o.render(this.decodedFrameCount):o.render(this.decodedFrameCount)}),i.source=o,i.player.setCanvas(this.videoContext._canvas,2)}else if(t==="videoFrame"){i.player.setCanvas();let o=new MediaStreamTrackGenerator({kind:"video"}),n=o.writable.getWriter();i.setInputMediaStreamTrack(o),this.decoder.on("videoFrame",a=>{n.write(a)}),o.onmute=()=>{e.error(r==="webCodecs"?5:9)},e.defer(()=>o.onmute=null)}else{this.videoContext=new Ge({frameRate:15,logger:i.log,name:i.userId}),this.videoContext.create({alpha:!1});let o=this.videoContext.createVideoImageSource();this.decoder.on("videoFrame",a=>{o.image=a,o.update()});let n=new kr(this.videoContext,{name:"remotePlayer",logger:i.log});o.connect(n),i.source=o,i.player.setCanvas(this.videoContext._canvas,2)}}catch(o){i.log.error(o),e.error(r==="webCodecs"?2:6)}}))}};var en=class extends ap.EventEmitter{constructor(e){super();this.room=e;d(this,"videoContext");d(this,"_glVideoContext");d(this,"_2dVideoContext");d(this,"destination");d(this,"smallVideoContext");d(this,"smallDestination");d(this,"smallTrackSource");d(this,"smallImageSource");d(this,"_isMirror",!1);d(this,"cameraTrack");d(this,"cameraNode");d(this,"mirrorNode");d(this,"mixNode");d(this,"screenTrack");d(this,"screenNode");d(this,"selfModel",!1);d(this,"blurRadius",3);d(this,"arTrack");d(this,"Wasm");d(this,"waterMarkNode");d(this,"_waterMarkOption");d(this,"watermarkImageList",[]);d(this,"_beautyParams");d(this,"isUsingArTrack",!1);d(this,"_isMixScreen",!1);d(this,"_virtualBackground");d(this,"_virtualBackgroundAbortCallback");d(this,"virtualBackgroundInstance");d(this,"_bgAssetPath");d(this,"log",C.createLogger({id:"vm"}));d(this,"_checkId",0);d(this,"_use2d",!1);d(this,"_autoSwitchRenderMode",!0);d(this,"_selfieSegmentation");d(this,"encodePipeline",[]);d(this,"decodePipeline",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new Ge({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 Ge({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new ke({frameRate:15,logger:this.log,name:"m"});else if(this._glVideoContext.available)return this._glVideoContext;return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(),this._glVideoContext.on("unavailable",e=>{var t;this.emit("error",e),this.log.warn("video context unavailable",e),(t=this._virtualBackgroundAbortCallback)==null||t.call(this,e),this.update().catch(r=>{this.log.error(r)})})}catch(e){this.emit("error",e)}}enablePrintDetail(e=2e3){this._checkId=re.run("interval",()=>{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(Ji||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",t){let r=e==="videoCtxGl"?512700:512701;t?N.addFailedEvent({key:r,error:t}):N.addSuccessEvent({key:r})}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{if(this._glVideoContext=new ke({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),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 r=this.cameraTrack,{small:o,settings:n,player:a}=r;o?(this.smallVideoContext.available||(this.smallVideoContext.create({alpha:!1}),this.smallDestination=new Pa(this.smallVideoContext,o,this.log)),this.smallVideoContext.frameRate=o.frameRate,this.smallDestination.resolution=o,e?(this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.connect(this.smallDestination))):(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource?this.smallTrackSource.replaceTrack(this.initialTrack):(this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource"),this.smallTrackSource.width=n.width,this.smallTrackSource.height=n.height,this.smallTrackSource.connect(this.smallDestination)))):this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource),Ji&&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"}`),r.setOutputMediaStreamTrack(c)}catch(r){this.log.error("set main output failed",r)}}update(){return f(this,null,function*(){var r,o;if(!this.cameraTrack||!this.cameraTrack.mediaTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:e,profile:t}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log})),at===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof Pi?(this.cameraNode.close(),delete this.cameraNode):this.cameraNode.image=this.initialTrack.canvas),this.cameraNode||(this.cameraNode=this.videoContext.createVideoImageSource(this.initialTrack.canvas,{name:"cameraCanvasSource",logger:this.log}))):(this.cameraNode&&(this.cameraNode instanceof Pi?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode.close(),delete this.cameraNode)),this.cameraNode||(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraTrackSource"))):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.disableCheckMute():this.destination=new La(this.videoContext,{name:"mainDestination",logger:this.log}),this.cameraNode=new ad(this.videoContext,{input:this.cameraTrack.mediaTrack,width:e.width,height:e.height,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.destination.enableCheckMute()),this.videoContext.frameRate=t.frameRate,this._use2d){let n=this.cameraNode;n.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new od(this.videoContext,this.log)),n=n.connect(this.mirrorNode),n.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new nd(this.videoContext,this.log),n.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption&&(this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y),(r=this.waterMarkNode)==null||r.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource")),(o=this.screenNode)==null||o.connect(this.mixNode,{zIndex:0}),n=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)),n.connect(this.destination)}return this.log.info(`update ${this._use2d?"2d":"webgl"}`),this._setMainOutput(this.videoContext._canvas)})}changeInput(e){var t,r,o,n;if(e instanceof st)return this.log.info("change screen input",(t=e.mediaTrack)==null?void 0:t.label),this.setScreenTrack(e);if(e instanceof $e)return this.log.info("change video input",(r=e.mediaTrack)==null?void 0:r.label),this.setCameraTrack(e);if(e instanceof oi){this.log.info("change remote input",(o=e.mediaTrack)==null?void 0:o.label);let a=e.mediaTrack;return e.setOutputMediaStreamTrack(a)}this.log.warn("change unknown input",(n=e.mediaTrack)==null?void 0:n.label)}removeInput(e){var t;e instanceof st?((t=this.screenNode)==null||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof $e?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof oi&&e.source&&e.source.context.destroy()}setCameraTrack(e){return f(this,null,function*(){this.cameraTrack=e,this.update()})}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,t){return f(this,null,function*(){let r=document.createElement("canvas");t&&e&&(r.height=t,r.width=e);let o=r.getContext("2d");if(!o)throw new b({code:S.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((n,a)=>n.zIndex-a.zIndex),this.watermarkImageList.forEach(({image:n,x:a,y:c,width:l,height:h})=>{o.drawImage(n,a,c,l,h)}),Yr(r.toDataURL())})}pushWaterMarkImageList(e){let{type:t}=e;this.watermarkImageList.some(o=>o.imageUrl===e.imageUrl&&o.height===e.height&&o.width===e.width&&o.x===e.x&&o.y===e.y&&o.type===e.type&&o.zIndex===e.zIndex)||((t==="mute"||t==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(o=>o.type!==t)),this.watermarkImageList.push(e))}setBeautyParams(e){return 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*(){var u,p;let t;try{t=yield Yr((e==null?void 0:e.imageElement)||e.imageUrl)}catch(_){throw new b({code:S.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:r=0,y:o=0,width:n=t.width,height:a=t.height,type:c="watermark",zIndex:l=2}=e;this.watermarkImageList.some(_=>_.type===c)?(this.watermarkImageList=this.watermarkImageList.filter(_=>_.type!==c),this.pushWaterMarkImageList({x:r,y:o,width:n,height:a,image:t,zIndex:l,type:c,imageUrl:e.imageUrl}),t=yield this.getWatermarkImage((u=this.cameraTrack)==null?void 0:u.settings.width,(p=this.cameraTrack)==null?void 0:p.settings.height),this._waterMarkOption={x:0,y:0,width:t.width,height:t.height,image:t},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(t.width,t.height),this.waterMarkNode.image=t):this.update()):(this.pushWaterMarkImageList({x:r,y:o,width:n,height:a,image:t,zIndex:l,type:c,imageUrl:e.imageUrl}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(_,I)=>_==="imageUrl"?void 0:I))})}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,(t,r)=>t==="imageUrl"?void 0:r)),yield this.freshWatermark()})}freshWatermark(){return f(this,null,function*(){var t,r,o;(t=this.waterMarkNode)==null||t.close(),delete this.waterMarkNode,delete this._waterMarkOption;let e=yield this.getWatermarkImage((r=this.cameraTrack)==null?void 0:r.settings.width,(o=this.cameraTrack)==null?void 0:o.settings.height);this._waterMarkOption={x:0,y:0,width:e.width,height:e.height,image:e},this.update()})}setVirtualBackground(e){return f(this,null,function*(){if(!e)delete this._virtualBackground,delete this._virtualBackgroundAbortCallback;else{if(e.onAbort&&(this._virtualBackgroundAbortCallback=e.onAbort),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 Yr(e.imageUrl):(this.blurRadius=e.blurLevel||this.blurRadius||3,this._virtualBackground=e.type)}if(this.log.info(`${this._virtualBackground?"start":"stop"} virtual background, ${(e==null?void 0:e.type)||""}, ${this.blurRadius||""}`),yield this.update(),this._virtualBackground&&!this._glVideoContext.available)throw new b({code:S.INVALID_OPERATION,message:`webgl context create failed, ${this._glVideoContext.error}`})})}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()}createDecodeContext(e){return new cd(e)}clear(){var e;(e=this.videoContext)==null||e.disconnect(),delete this.destination,delete this.cameraNode,delete this.mirrorNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor({processor:e,type:t}){var r;this.encodePipeline.includes(e)||(this.encodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}addDecodeProcessor({processor:e,type:t}){var r;this.decodePipeline.includes(e)||(this.decodePipeline[t]=e,(r=this.room)==null||r.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};y([ha(function(e){this.log.error("update failed",e)})],en.prototype,"update",1);var MT=0;var ld=class extends Q{constructor(e){super("room");d(this,"seq",++MT);d(this,"sdkAppId");d(this,"userId");d(this,"userSig");d(this,"privateMapKey");d(this,"latencyLevel");d(this,"tinyId");d(this,"scene");d(this,"roomId");d(this,"useStringRoomId");d(this,"role","anchor");d(this,"joinParams",null);d(this,"localTracks",new Set);d(this,"enableAutoPlayDialog",!0);d(this,"autoReceiveAudio",!0);d(this,"autoReceiveVideo",!0);d(this,"proxy_ws");d(this,"proxy_wt");d(this,"proxy_unified");d(this,"checkSystemResult",{result:!0,detail:{isBrowserSupported:!0,isWebRTCSupported:!0,isWebCodecsSupported:!0,isMediaDevicesSupported:!0,isScreenShareSupported:!0,isSmallStreamSupported:!0,isH264EncodeSupported:!0,isVp8EncodeSupported:!0,isH264DecodeSupported:!0,isVp8DecodeSupported:!0}});d(this,"keyPointManager");d(this,"audioManager");d(this,"videoManager");d(this,"callDurationCalculator");d(this,"badCaseDetector");d(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null});d(this,"videoDecodeFallbackType");d(this,"_isUsingCachedSchedule",!1);d(this,"_log",C.createLogger({id:`r${this.seq}`}));d(this,"_joinedTimestamp",0);d(this,"_sdkType");d(this,"heartbeatReport");d(this,"quality");d(this,"enableSEI");d(this,"isDestroyed",!1);this.useStringRoomId=!!e.useStringRoomId,me(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),me(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),me(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new rp({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new sp({room:this}),this.badCaseDetector=new op({room:this}),this.audioManager=new ga(this),this.videoManager=new en(this)}get scriptTransformWorker(){}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(K(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(Ze(e)){let{websocketProxy:t,webtransportProxy:r,loggerProxy:o,scheduleProxy:n,unifiedProxy:a}=e;this.proxy_ws=t,this.proxy_wt=r,this.proxy_unified=a,a?(Ba([a,a]),nr(`https://${a}`)):(o&&nr(o),n&&Ba(n))}E.once(T.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:mt.main,sched_back_domain:mt.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 r of this.quality.downlinkInfo)e.downlinksRTT[r.userId]=r.rtt;return e})}getRemoteVideoStats(){return f(this,arguments,function*(e="main"){let t={};return this.remotePublishedUserMap.forEach(r=>{let o=e==="auxiliary"?r.remoteAuxiliaryTrack:r.remoteVideoTrack;t[r.userId]=o.stat}),t})}checkDestroy(){if(this.isDestroyed)throw new b({code:S.INVALID_OPERATION,message:V({key:w.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Oe.INVALID_DESTROY),new b({code:S.INVALID_OPERATION,message:V({key:w.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,E.emit(T.ROOM_DESTROY,{room:this})}schedule(e,t){return f(this,null,function*(){var o,n,a;let r=L();try{let{isCached:c,result:l,detailCost:h}=yield xl({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=c,this._log.info(`schedule cache:${+c} ${ft(l,{keysToExclude:["username","credential"]})}`),c&&E.once(T.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=v(v({},this.scheduleResult),l),Y((o=l.config)==null?void 0:o.retryCount)&&Nd(l.config.retryCount),K((n=l.config)==null?void 0:n.loggerDomain)&&nr(l.config.loggerDomain),this.videoDecodeFallbackType=((a=l.config)==null?void 0:a.videoDecodeFallback)||this.videoDecodeFallbackType,E.emit(T.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:h}),N.addSuccessEvent({key:521700,cost:L()-r,split:50})}catch(c){throw N.addFailedEvent({key:521700,error:c}),c}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}};var Ep=Pe(je());var fu=Pe(ou());var dp=s=>{let i=ge(s),e={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return i.media.forEach((t,r)=>{var o;if(t.ssrcs&&!g(t.ssrcs[0].id)){let n=Number(t.ssrcs[0].id),a=Number((o=t.ssrcs.filter(c=>c.attribute==="cname")[1])==null?void 0:o.id);switch(r){case 0:e.audioSsrc=n;break;case 1:e.bigVideoSsrc=n,e.bigVideoRtxSsrc=a;break;case 2:e.smallVideoSsrc=n,e.smallVideoRtxSsrc=a;break;case 3:e.auxVideoSsrc=n,e.auxVideoRtxSsrc=a;break}}}),e};function cp(s){var e;let i=[];for(let t=0;t<s.rtp.length;t++){if(["rtx","red","ulpfec"].includes(s.rtp[t].codec))continue;let r=s.fmtp.filter(o=>o.payload===s.rtp[t].payload)[0];i.push({payload:s.rtp[t].payload,codec:s.rtp[t].codec,fmtp:r?r.config:"",rate:s.rtp[t].rate,rtx:((e=s.rtp[t+1])==null?void 0:e.codec)==="rtx"?s.rtp[t+1].payload:0,rtcpfb:((s==null?void 0:s.rtcpFb)||[]).filter(o=>o.payload===s.rtp[t].payload).map(({type:o,subtype:n})=>({id:o,params:n?[n]:[]}))})}return i}function LT(){return f(this,null,function*(){let s=new RTCPeerConnection;s.addTransceiver(m.VIDEO,{direction:m.TRANSCEIVER_DIRECTION_RECVONLY});let i=yield s.createOffer();if(!i.sdp)return[];let e=ge(i.sdp),t=cp(e.media[0]);return s.close(),t})}var lp=(s,i)=>f(void 0,null,function*(){var c;let e=ge(s),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 r=e.media[0],o=e.media[1];r.ext&&(t.audio.extensions=r.ext.map(l=>({id:l.value,uri:l.uri}))),o.ext&&(t.video.extensions=o.ext.map(l=>({id:l.value,uri:l.uri})));let n={codec:r.rtp[0].codec,fmtp:r.fmtp[0].config,payload:r.fmtp[0].payload,rate:r.rtp[0].rate,channels:r.rtp[0].encoding,rtcpfb:[],rtx:0};(c=r.rtcpFb)==null||c.forEach(({payload:l,type:h,subtype:u})=>{if(l===n.payload){let p={id:h,params:[]};u&&p.params.push(u),n.rtcpfb.push(p)}}),t.audio.codecs.push(n);let a=["h264","vp8"];return i&&a.shift(),t.video.codecs=[...cp(o)].filter(l=>a.includes(l.codec.toLocaleLowerCase())),t.video.decoders=(yield LT()).filter(l=>["h264","vp8"].includes(l.codec.toLocaleLowerCase())),t}),up=({serverAbility:s,clientAbility:i,offerSDP:e,enableCustomMessage:t})=>{let r=ge(e),o={extmapAllowMixed:"extmap-allow-mixed",groups:r.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},n={candidates:s.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:m.TRANSCEIVER_DIRECTION_RECVONLY,ext:s.audio.extensions.map(a=>({value:a.id,uri:a.uri})),fingerprint:{type:s.dtls.hash,hash:s.dtls.fingerprint},fmtp:[{payload:s.audio.codecs[0].payload,config:s.audio.codecs[0].fmtp}],icePwd:s.ice.password,iceUfrag:s.ice.ufrag,mid:"0",payloads:String(s.audio.codecs[0].payload),port:r.media[0].port,protocol:r.media[0].protocol,type:m.AUDIO,setup:s.dtls.setup,rtcpFb:s.audio.codecs[0].rtcpfb.map(a=>({payload:s.audio.codecs[0].payload,type:a.id,subtype:a.params[0]})),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:s.audio.codecs[0].payload,codec:s.audio.codecs[0].codec,rate:s.audio.codecs[0].rate,encoding:s.audio.codecs[0].channels}]};return o.media.push(n),[1,2,3].forEach(a=>{o.media.push(_u({mid:a,serverAbility:s,clientAbility:i,parsedOffer:r}))}),t&&o.media.push(r.media.find(a=>a.mid==="dc")),It(o)},_u=({mid:s,serverAbility:i,clientAbility:e,parsedOffer:t,isDownlink:r=!1})=>{let o={candidates:i.candidates.map(n=>({component:1,foundation:"1",generation:0,ip:n.ip,port:n.port,priority:n.priority,transport:n.foundation,type:n.type})),connection:{version:4,ip:"0.0.0.0"},direction:m.TRANSCEIVER_DIRECTION_RECVONLY,ext:i.video.extensions.map(n=>({value:n.id,uri:n.uri})),fingerprint:{type:i.dtls.hash,hash:i.dtls.fingerprint},fmtp:[],icePwd:i.ice.password,iceUfrag:i.ice.ufrag,mid:String(s),payloads:"",port:t.media[0].port,protocol:t.media[0].protocol,type:m.VIDEO,setup:i.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(r){let n=i.video.decoders;(!n||n.length===0)&&(n=i.video.codecs),(!n||n.length===0)&&(n=e.video.decoders),n.forEach(a=>{Br(o,a)})}else{let n=i.video.codecs.findIndex(c=>c.codec.toLowerCase()===(i.useVp8?"vp8":"h264")),a=i.video.codecs[n]||e.video.codecs[0];Br(o,a)}return o},Br=(s,i)=>{s.payloads=`${s.payloads} ${i.payload}`.trim(),s.fmtp.push({payload:i.payload,config:i.fmtp}),s.rtcpFb=[...s.rtcpFb||[],...i.rtcpfb.map(e=>({payload:i.payload,type:e.id,subtype:e.params[0]}))],s.rtp.push({payload:i.payload,codec:i.codec.toUpperCase(),rate:i.rate}),i.rtx&&(s.payloads=`${s.payloads} ${i.rtx}`,s.fmtp.push({payload:i.rtx,config:`apt=${i.payload}`}),s.rtp.push({payload:i.rtx,codec:"rtx",rate:i.rate}))};function PT(s){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"]);s.ext&&(s.ext=s.ext.filter(e=>!i.has(e.uri)))}function xT(s){if(!s.rtcpFb)return;let i=[];s.rtcpFb.forEach((e,t)=>{var r;i.push(e),s.rtcpFb&&((r=s.rtcpFb[t+1])==null?void 0:r.payload)!==e.payload&&e.type!=="rrtr"&&i.push({payload:e.payload,type:"rrtr"})}),s.rtcpFb=i}function wT(s){s.type===m.VIDEO&&s.fmtp&&s.fmtp.forEach(i=>{i.config.includes("apt")||(i.config+=";sps-pps-idr-in-keyframe=1")})}function UT(s){s.type===m.AUDIO&&s.fmtp&&s.fmtp.forEach(i=>{i.config+=";sprop-stereo=1;stereo=1"})}var hp=(s,i,e)=>{let t=fu.default.parse(s);return t.media.forEach((r,o)=>{var n;if((r.type===m.AUDIO||r.type===m.VIDEO)&&(xT(r),wT(r),UT(r),PT(r),r.type===m.VIDEO)){if(o<4)r.payloads="",r.fmtp=[],r.rtp=[],r.rtcpFb=[],i.video.codecs.forEach(a=>Br(r,a));else if(e){r.payloads="",r.fmtp=[],r.rtp=[],r.rtcpFb=[];let a=e.video.decoders;(!a||a.length===0)&&(a=e.video.codecs),(!a||a.length===0)&&(a=i.video.decoders),a.forEach(c=>Br(r,c))}}(n=r.payloads)!=null&&n.includes("datachannel")&&t.groups&&r.mid&&(t.groups[0].mids=t.groups[0].mids.replace(r.mid,"dc"),r.mid="dc")}),fu.default.write(t)};var mp=Pe(je());var ud=class extends mp.EventEmitter{constructor(e){super();this.room=e;d(this,"mainFpsHealth",1);d(this,"mainBitrateHealth",1);d(this,"badMainBitrateHealthCount",0);d(this,"lastEmitBadHealthTime",0);d(this,"log");!pe&&Ot&&E.on("262",this.onVideoCodecChanged,this),this.log=e.getLogger().createChild({id:"h-d"})}onVideoCodecChanged({remoteUserId:e,streamType:t,isHWCodec:r,codec:o}){if(!(e||t===7||o!=="h264")){if(!r){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 r=t.uint32_video_enc_fps/t.uint32_video_capture_fps;t.uint32_video_stream_type===2&&(this.mainFpsHealth=r)}if(t.uint32_video_codec_bitrate&&t.uint32_video_stream_type===2){let{localMainVideoTrack:r}=this.room;r&&(this.mainBitrateHealth=t.uint32_video_codec_bitrate/1e3/r.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(){E.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};d(ud,"EVENT_BAD_HEALTH","bad_health");var pp=ud;function fp({seiMessageList:s,isAudio:i,isMain:e}){return new TransformStream({transform(t,r){let o=t;i?audioEncodePipeline.forEach(n=>{o=n({frame:o})}):videoEncodePipeline.forEach(n=>{o=n({frame:o,seiMessageList:s,onDump:()=>{self.postMessage({type:"dump",isAudio:i,data:o.data,userId:"",streamType:e?"main":"auxiliary"})}})}),r.enqueue(o)}})}function _p(s,i,e){return new TransformStream({transform(t,r){let o=t;videoDecodePipeline.forEach(n=>{o=n({frame:o,onSEI:a=>{a.forEach(c=>{self.postMessage({type:"sei",seiPayloadType:c.seiPayloadType,data:c.seiPayload.buffer,userId:s,streamType:i})})},onDump:()=>{self.postMessage({type:"dump",isAudio:e,data:o.data,userId:s,streamType:i})}})}),r.enqueue(o)}})}function gp(s){let i=[Di],e=[ql,Wl,Jl,Gl,fp,_p],t=()=>{let l=[],h=[],u=[];self.onmessage=p=>{p.data.type==="sei"&&(p.data.isMain?(l.push(p.data.data),p.data.small&&u.push(p.data.data)):h.push(p.data.data))},self.onrtctransform=p=>{let{options:_}=p.transformer,I=_.isReceiver?_p(_.userId,_.streamType,_.isAudio):fp({isAudio:_.isAudio,seiMessageList:_.isMain?_.small?u:l:h,isMain:_.isMain});p.transformer.readable.pipeThrough(I).pipeTo(p.transformer.writable)}},r=`const videoEncodePipeline=[${s.videoEncodePipeline.toString()}];
|
|
110
110
|
const videoDecodePipeline=[${s.videoDecodePipeline.toString()}];
|
|
111
111
|
const audioEncodePipeline = [${s.audioEncodePipeline.toString()}];
|
|
112
112
|
const audioDecodePipeline = [${s.audioDecodePipeline.toString()}];`,o=`(()=>{${i.map(l=>`const ${l.name}=(()=>${l.toString()})()`).join(`
|
|
@@ -115,4 +115,4 @@ ${e.map(l=>l.toString()).join(`
|
|
|
115
115
|
`)};(${t})();${r}})()`,n=new Blob([o],{type:"text/javascript"}),a=URL.createObjectURL(n),c=new Worker(a);return URL.revokeObjectURL(a),c}var ai=(l=>(l.TRACK="track",l.DATA_CHANNEL_MESSAGE="data_channel_msg",l[l.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",l[l.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",l.RECONNECTED="spc-reconnected",l.RECONNECT_FAILED="spc-reconnect-failed",l.ERROR="error",l.SEI_MESSAGE="sei-message",l.DUMP="dump",l))(ai||{}),Sp=0,Ip=!1,VT=new Set,BT=s=>Sp>2&&!Ip&&VT.size===0&&s,FT=1,Vt=class extends Ep.default{constructor({signalChannel:e,room:t,enableCustomMessage:r}){super();d(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0});d(this,"currentState","DISCONNECTED");d(this,"_room");d(this,"_signalChannel");d(this,"_peerConnection",null);d(this,"_datachannel",null);d(this,"_enableCustomMessage");d(this,"_log");d(this,"_downlinkMIDMap",new Map);d(this,"_downlinkMIDUserIDMap",new Map);d(this,"_reconnectionTimer",-1);d(this,"reconnectionCount",0);d(this,"clientAbility");d(this,"_serverAbility",null);d(this,"addDownlinkQueue",new Set);d(this,"removeDownlinkQueue",new Set);d(this,"_parsedAnswer",null);d(this,"_updateSDPPromise",null);d(this,"_waitForPCConnectedPromise");d(this,"clearConnectTimeout");d(this,"_isSDPLogged",!1);d(this,"enableInsertableStreams",!1);d(this,"insertableStreamsAbortMap",new Map);d(this,"receiverRemoteTrackMap",new WeakMap);d(this,"scriptTransformWorker");d(this,"_isRelayTried",!1);d(this,"_rttOverCount",0);this._room=t,this._enableCustomMessage=r,this._signalChannel=e,this._log=C.createLogger({id:`spc${FT++}`,userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(Ri?this.enableInsertableStreams=!0:this.initScriptTransformWorker()),this._room.healthDetector.on("1",this.onBadHealth,this)}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 r;(r=this.insertableStreamsAbortMap.get(e))==null||r.abort("destory"),this.insertableStreamsAbortMap.set(e,t)}get isVP8EncodeSupported(){let e=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(e=e&&this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="vp8")),e}get videoCodec(){var t,r;let e=(t=this._parsedAnswer)==null?void 0:t.media[1].rtp.find(o=>["h264","vp8"].includes(o.codec.toLowerCase()));return e?e.codec.toLowerCase():(r=this._serverAbility)!=null&&r.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?dp(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}onBadHealth({isAux:e}){this.useHWEncoder(!1,e?7:2)}initScriptTransformWorker(){Yn&&(this.scriptTransformWorker=gp({videoEncodePipeline:this._room.videoManager.encodePipeline,videoDecodePipeline:this._room.videoManager.decodePipeline,audioEncodePipeline:this._room.audioManager.encodePipeline,audioDecodePipeline:this._room.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=e=>{e.data.type==="sei"&&this.emit("sei-message",e.data),e.data.type==="dump"&&this.emit("dump",e.data)},this.scriptTransformWorker.onerror=e=>{this._log.error("scriptTransformWorker error: ",e)})}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{return this._peerConnection=new RTCPeerConnection({encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"}),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let r=this._peerConnection.iceConnectionState;this._log.debug(`ice state: ${r}`),r==="checking"&&this.stat.iceStartTime===0?this.stat.iceStartTime=Date.now():r==="connected"&&this.stat.iceEndTime===0?(this.stat.iceEndTime=Date.now(),N.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):r==="failed"&&N.addFailedEvent({key:521711})},this._peerConnection.onsignalingstatechange=()=>{var o;let r=((o=this._peerConnection)==null?void 0:o.signalingState)||"";this._log[r==="closed"?"debug":"info"](`signaling state: ${r}`)},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=r=>this.emit("track",r),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=r=>{let o=new Tu(r.data);this.emit("data_channel_msg",{data:o})},this._datachannel.onerror=r=>{this._log.warn("datachannel error",r)}),this._peerConnection.addTransceiver(m.AUDIO,{direction:m.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:m.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:m.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:m.TRANSCEIVER_DIRECTION_SENDONLY}),e=yield this._peerConnection.createOffer(),this.clientAbility=yield lp(e.sdp,((t=this._room.scheduleResult.config)==null?void 0:t.remove264FromSDP)||!1),yield this.setOffer(e),this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:r}=this;r&&(this._log.debug(`dtls state: ${r.state}`),r.state==="connecting"&&this.stat.dtlsStartTime===0?this.stat.dtlsStartTime=Date.now():r.state==="connected"&&this.stat.dtlsEndTime===0&&(this.stat.dtlsEndTime=Date.now()))}),N.addSuccessEvent({key:521707}),this.clientAbility}catch(r){throw N.addFailedEvent({key:521707,error:r}),this._log.error(`initialize failed ${r}
|
|
116
116
|
offer: ${e==null?void 0:e.sdp}`),r}})}setPriority(e="high"){if(this._peerConnection)try{this._peerConnection.getSenders().forEach(r=>{let o=r.getParameters();o.encodings[0]&&(o.encodings[0].priority=e,o.encodings[0].networkPriority=e,r.setParameters(o).catch(n=>{this._log.warn("setPriority error ",n)}))})}catch(t){this._log.warn("setPriority error ",t)}}connect(e,t=!1){return f(this,null,function*(){var r,o;try{if(this.currentState==="CONNECTED")return;let n=L(),a={type:"answer",sdp:up({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(a),yield this.waitForPeerConnectionConnected();let c=((r=this._room.scheduleResult.config)==null?void 0:r.priority)||((o=this._room.joinParams)==null?void 0:o.priority)||new URLSearchParams(location.search).get("priority");c&&this.setPriority(c),t||N.addSuccessEvent({key:521703,cost:L()-n})}catch(n){let a=n instanceof b&&n.code===S.API_CALL_ABORTED;throw a||this._log.error(`connect failed: ${n}`,e),this.reset(),!a&&!this.isReconnecting&&(N.addFailedEvent({key:521703,error:n}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),n}})}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(Ee.CONNECTED,this.reconnect,this);return}try{this.reconnectionCount++,this._log.warn(`reconnect() trying [${this.reconnectionCount}]`),this.reset();let e=yield this.initialize(),t=yield this._signalChannel.sendWaitForResponse({command:q.REBUILD_PEER_CONNECTION,responseCommand:B.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),N.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),E.emit(T.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(e){if(!this.isReconnecting)return;if(e!=null&&e.message.includes("timeout")){let t=yt(this.reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${t/1e3}s`),yield fi(t,r=>{this._reconnectionTimer=r}),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error(`reconnect() failed ${e==null?void 0:e.code} ${e}`),N.addFailedEvent({key:521704,error:e}),this.reconnectionCount>=ui()&&this._log.warn(`SDK has tried reconnect for ${ui()} 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.isReconnecting||(this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect())})}stopReconnection(){var e;this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),(e=this.clearConnectTimeout)==null||e.call(this),this._signalChannel.off(Ee.CONNECTED,this.reconnect,this),this.currentState==="RECONNECTING"&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&((e=this._peerConnection)==null?void 0:e.connectionState)===ce.CLOSED&&this.startReconnection()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(e){var o;let t=((o=this._peerConnection)==null?void 0:o.iceConnectionState)||"closed",r=this.getDTLSTransportState();this._log.info(`connectionState: ${e.target.connectionState} ICE: ${t} DTLS: ${r}`),e.target.connectionState===ce.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===ce.FAILED||e.target.connectionState===ce.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(e.target.connectionState===ce.CONNECTED||e.target.connectionState===ce.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),E.emit(T.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 Ct;let e=null;return!Ki()||this._peerConnection.getSenders().length===0?Ct:(e=this._peerConnection.getSenders()[0].transport,!Sr()||this._peerConnection.getReceivers().length===0?Ct:e?e.state:Ct)}emitConnectionStateChangedEvent(e){e!==this.currentState&&(this.currentState==="RECONNECTING"&&e==="CONNECTING"||(this.emit(ai.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,r]of e)if(Yi(r)){let o=e.get(r.localCandidateId),n=e.get(r.remoteCandidateId);o&&(this._log.info(`local candidate: ${o.candidateType} ${o.protocol}:${o.ip||o.address}:${o.port} ${o.networkType||""} ${o.candidateType==="relay"?`relayProtocol:${o.relayProtocol}`:""}`),o.networkType&&Tn(o.networkType)),n&&this._log.info(`remote candidate: ${n.candidateType} ${n.protocol}:${n.ip||n.address}:${n.port}`);break}})}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise?this._waitForPCConnectedPromise:(this._waitForPCConnectedPromise=new Promise((e,t)=>{if(this.currentState==="CONNECTED")return e();let r=c=>{c.state==="CONNECTED"&&(clearTimeout(a),n(),e())},o=({room:c})=>{c===this._room&&(clearTimeout(a),n(),t(new b({code:S.API_CALL_ABORTED,message:V({key:w.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{E.off(T.LEAVE_SUCCESS,o,this),this.off(ai.CONNECTION_STATE_CHANGED,r,this)},a=setTimeout(()=>{n();let c=new b({code:S.API_CALL_TIMEOUT,message:"connection timeout"});Sp+=1,BT(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),Ip=!0,this.emit(ai.FIREWALL_RESTRICTION)),t(c)},qs);this.clearConnectTimeout=()=>{n(),clearTimeout(a),delete this.clearConnectTimeout},E.on(T.LEAVE_SUCCESS,o,this),this.on(ai.CONNECTION_STATE_CHANGED,r,this)}),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally(()=>{this._waitForPCConnectedPromise=null,delete this.clearConnectTimeout}),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:r}){if(!this._peerConnection)return;this._log.info(`updateLocalAndRemoteSDPConfig ${t} ${JSON.stringify(e)}`);let o=this._peerConnection.getTransceivers().slice(4).filter(p=>p.direction==="inactive").slice(0,3).map(p=>(p.direction=m.TRANSCEIVER_DIRECTION_RECVONLY,Number(p.mid)));this._parsedAnswer||(this._parsedAnswer=ge(this._peerConnection.remoteDescription.sdp));let n=this._parsedAnswer.media.filter(p=>{var _;return(_=p.ssrcs)==null?void 0:_.find(I=>{var R;return(R=I.value)==null?void 0:R.includes(r)})}),a,c,l;if(n.length===3)a=n[0],c=n[1],l=n[2];else if(o.length===3)a=this._parsedAnswer.media.find(p=>Number(p.mid)===Number(o[0])),c=this._parsedAnswer.media.find(p=>Number(p.mid)===Number(o[1])),l=this._parsedAnswer.media.find(p=>Number(p.mid)===Number(o[2]));else if(o.length===0){this._peerConnection.addTransceiver(m.AUDIO,{direction:m.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:m.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:m.TRANSCEIVER_DIRECTION_RECVONLY}),a=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let p=_u({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:ge(this._peerConnection.localDescription.sdp),isDownlink:!0});c=JSON.parse(JSON.stringify(p)),l=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),l.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(l)}a.direction=m.TRANSCEIVER_DIRECTION_SENDONLY;let h=`${r}-${e.audio}`;a.ssrcs=[{id:e.audio,attribute:"cname",value:`${h}`},{id:e.audio,attribute:"msid",value:`${h}-${m.MAIN} ${h}-audio`}],c.direction=m.TRANSCEIVER_DIRECTION_SENDONLY,c.ssrcs=[{id:e.video,attribute:"cname",value:`${h}`},{id:e.video,attribute:"msid",value:`${h}-${m.MAIN} ${h}-bigvideo`},{id:e.videoRtx,attribute:"cname",value:`${h}`},{id:e.videoRtx,attribute:"msid",value:`${h}-${m.MAIN} ${h}-bigvideo`}],c.ssrcGroups=[{semantics:"FID",ssrcs:`${e.video} ${e.videoRtx}`}],l.direction=m.TRANSCEIVER_DIRECTION_SENDONLY;let u=`${h}-aux`;l.ssrcs=[{id:e.auxiliary,attribute:"cname",value:u},{id:e.auxiliary,attribute:"msid",value:`${u} ${h}-aux${m.VIDEO}`},{id:e.auxiliaryRtx,attribute:"cname",value:`${u} ${h}-aux${m.VIDEO}`},{id:e.auxiliaryRtx,attribute:"msid",value:`${u} ${h}-aux${m.VIDEO}`}],l.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,l.mid]),this._downlinkMIDUserIDMap.set(a.mid,t),this._downlinkMIDUserIDMap.set(c.mid,t),this._downlinkMIDUserIDMap.set(l.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),r=!1;this._peerConnection.getTransceivers().forEach(o=>{t!=null&&t.includes(Number(o.mid))&&(r=!0,o.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=ge(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(o=>{t!=null&&t.includes(Number(o.mid))&&(r=!0,o.direction="inactive",o.ssrcs=[],o.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&r&&(yield this.updateSDP()),this._downlinkMIDMap.delete(e),t==null||t.forEach(o=>this._downlinkMIDUserIDMap.delete(o)),this._log.info(`removeDownlink(${e}) done`)})}setBandwidth(e){return f(this,null,function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:r,smallVideo:o,auxVideo:n}=e;try{if(Co()){let a=this._peerConnection.getSenders().slice(0,4);for(let l=0;l<a.length;l++){let h=a[l],u;l===0&&t?u=t:l===1&&r?u=r:l===2&&o?u=o:l===3&&n&&(u=n),u&&(yield this.setSenderMaxBitrate(h,u))}let c=!1;r&&a[1].track&&(c=this.setStartBitrate(1,r)),n&&a[3].track&&(c=this.setStartBitrate(3,n)||c),c&&(yield this.updateSDP())}else yield this.setBandwidthBySDP(e);this._log.info(`setBandwidth ${JSON.stringify(e)}`)}catch(a){this._log.error(`failed to set bandwidth: ${a}`)}})}setStartBitrate(e,t){var r,o;return(r=this._peerConnection)!=null&&r.remoteDescription&&(this._parsedAnswer||(this._parsedAnswer=ge(this._peerConnection.remoteDescription.sdp)),(o=this._parsedAnswer.media[e])!=null&&o.fmtp[0])?(this._parsedAnswer.media[e].fmtp[0].config+=`;x-google-start-bitrate=${t>5e3?5e3:t}`,!0):!1}setSenderMaxBitrate(e,t){let r=e.getParameters();return(!r.encodings||r.encodings.length===0)&&(r.encodings=[{}]),t==="unlimited"?delete r.encodings[0].maxBitrate:r.encodings[0].maxBitrate=t*1e3,e.setParameters(r)}setBandwidthBySDP({audio:e,bigVideo:t,smallVideo:r,auxVideo:o}){if(!this._peerConnection||!this._peerConnection.localDescription)return;let n=ge(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=ge(this._peerConnection.remoteDescription.sdp));let a=ae?"TIAS":"AS";e&&(n.media[0].bandwidth=[{type:a,limit:ae?e*1e3:e}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:ae?e*1e3:e}]),t&&(n.media[1].bandwidth=[{type:a,limit:ae?t*1e3:t}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:ae?t*1e3:t}]),r&&(n.media[2].bandwidth=[{type:a,limit:ae?r*1e3:r}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:ae?r*1e3:r}]),o&&(n.media[3].bandwidth=[{type:a,limit:ae?o*1e3:o}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:ae?o*1e3:o}]);let c={type:"offer",sdp:It(n)};return this.updateSDP({localDescription:c})}setScaleResolutionDownBy(e,t,r){let o=e.getParameters();(!o.encodings||o.encodings.length===0)&&(o.encodings=[{}]);let n=o.encodings[0].scaleResolutionDownBy;if(g(n)?t===1:t===n)return;let a=`setScaleResolutionDownBy ${r} ${t}`;return n&&(a+=` prevScale: ${n}`),this._log.warn(a),o.encodings[0].scaleResolutionDownBy=t,e.setParameters(o)}updateSDP({localDescription:e}={}){if(!this._parsedAnswer)return Promise.resolve();let t=It(this._parsedAnswer);return this._updateSDPPromise=new Promise((r,o)=>f(this,null,function*(){var n,a;try{!e&&this._peerConnection&&(this._log.info("creating offer"),e=yield this._peerConnection.createOffer()),e&&(yield this.setOffer(e)),yield this.setAnswer({type:"answer",sdp:t}),this._updateSDPPromise=null,r()}catch(c){this._log.error(c),!this._isSDPLogged&&this._peerConnection&&(this._log.warn(`current offer: ${this.filterSDPDirection((n=this._peerConnection.localDescription)==null?void 0:n.sdp)}
|
|
117
117
|
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)}
|
|
118
|
-
next answer: ${this.filterSDPDirection(t)}`),this._log.warn(`offer: ${e==null?void 0:e.sdp}`),this._log.warn(`answer: ${t}`),this._log.warn(`transceivers: ${JSON.stringify(this._peerConnection.getTransceivers().map(({mid:l,currentDirection:h,direction:u,stopped:p})=>({mid:l,currentDirection:h,direction:u,stopped:p})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._isSDPLogged=!0),this._updateSDPPromise=null,o(c)}})),this._updateSDPPromise}setTransceiverDirection(e,t){return f(this,null,function*(){if(!ae||!this._peerConnection||!this._parsedAnswer)return;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let r=this._peerConnection.getTransceivers();t.forEach(o=>{r[o].direction!==e&&(r[o].direction=e)});for(let o of t){let n=this._parsedAnswer.media[o].direction;e===z.INACTIVE&&n===z.RECVONLY&&(this._parsedAnswer.media[o].direction=e),e===z.SENDONLY&&n===z.INACTIVE&&(this._parsedAnswer.media[o].direction=z.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(e=""){return ge(e).media.map(r=>r.direction)}setOffer(e){this._log.info("setting offer");let t=hp(e.sdp,this.clientAbility,this._serverAbility);return this._log.debug(t),this._peerConnection.setLocalDescription({type:"offer",sdp:t})}setAnswer(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._peerConnection.setRemoteDescription(e)}switchVideoEncoder(e){return f(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach(r=>{var o;if(r.type===m.VIDEO){let n=this._serverAbility.video.codecs.find(a=>a.codec.toLowerCase()===e);n&&!((o=r.payloads)!=null&&o.includes(String(n.payload)))&&(r.fmtp=[],r.payloads="",r.rtp=[],r.rtcpFb=[],Br(r,n),t=!0)}}),t&&(this._log.warn(`switch video encoder to ${e}`),yield this.updateSDP())})}useHWEncoder(e=!0,t){return f(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let r=!1,o=[];g(t)?o=this._parsedAnswer.media.slice(1,4):t===2?o.push(this._parsedAnswer.media[1]):t===3?o.push(this._parsedAnswer.media[2]):t===7&&o.push(this._parsedAnswer.media[3]),o.forEach(n=>{var a;if(n.type===m.VIDEO){let c;e&&this.is42001fSupported?c=this.clientAbility.video.codecs.find(l=>l.fmtp.includes("42001f")):e||(c=this._serverAbility.video.codecs.find(l=>l.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264"))),c&&!((a=n.payloads)!=null&&a.includes(String(c.payload)))&&(n.fmtp=[],n.payloads="",n.rtp=[],n.rtcpFb=[],Br(n,c),r=!0)}}),r&&(this._log.warn(`use ${e?"hw":"sw"} encoder`),yield this.updateSDP())})}sendDataChannelMessage(e){var t;(t=this._datachannel)==null||t.send(e)}reset(){this._peerConnection&&(this._peerConnection.close(),this._peerConnection.removeEventListener("track",this._peerConnection._onaddstreampoly,this),this._peerConnection._onaddstreampoly=null,this._peerConnection=null),this._waitForPCConnectedPromise=null,this._parsedAnswer=null}close(){this._log.info("close pc"),this.removeRTCListener(),this.insertableStreamsAbortMap.forEach(e=>Wt(e.abort)&&e.abort("destroy")),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners(),this._room.healthDetector.off("1",this.onBadHealth,this)}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map(r=>t[r])}get isUsingRelay(){return this._room.getIceTransportPolicy()==="relay"}detectTCPAndUDP({uplinkRTT:e,downlinkRTT:t}){var h;if(this.currentState!=="CONNECTED"||this._isRelayTried&&!this._room.forceRelay||this._room.getIceServers().length===0)return;let r=this._signalChannel.rtt,o=Math.max(e,t),{rttRatioThreshold:n,rttThreshold:a}=((h=this._room.scheduleResult.config)==null?void 0:h.useTurnTcpInfo)||{};if(!n||!a||!r||!o)return;let c=Math.floor(o/r),l=(this._isRelayTried||c>n)&&o>a;if(!l){this._rttOverCount=0;return}++this._rttOverCount<5||(this._log.warn(`detectTCPAndUDP ws-rtt: ${r} upRTT: ${e} downRTT: ${t} ratio: ${c} over-count: ${this._rttOverCount} isOver: ${l} isRelayTried: ${this._isRelayTried} force-relay: ${this._room.forceRelay}`),!this.isUsingRelay&&!this._isRelayTried?(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0)):this._room.forceRelay&&this.switchRelay(!1))}switchRelay(e,t=!1){return f(this,null,function*(){if(this.isUsingRelay===e)return;let r=e?"relay":"udp",o=e?521709:521710;try{this._room.forceRelay=e,this._log.warn(`switchRelay ${r}`);let n=Date.now();yield this.doSwitchRelay(r),this._log.warn(`switchRelay ${r} success`),N.addSuccessEvent({key:o,cost:Date.now()-n})}catch(n){this._log.warn(`switchRelay ${r} failed`,n),N.addFailedEvent({key:o,error:n}),t?this._room.reJoin():yield this.switchRelay(!e,!0)}})}doSwitchRelay(e){return new Promise((t,r)=>{let o=setTimeout(()=>{this.stopReconnection(),r(new Error(`switch ${e} timeout`))},1e4);this.startReconnection().then(t,r).finally(()=>clearTimeout(o))})}removeRTCListener(){this._peerConnection&&(this._peerConnection.oniceconnectionstatechange=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.onsignalingstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}};y([fa("reconnect")],Vt.prototype,"startReconnection",1),y([vi(e=>e.userId)],Vt.prototype,"addDownlink",1),y([vi(e=>e)],Vt.prototype,"removeDownlink",1),y([ii(!0)],Vt.prototype,"updateSDP",1),y([rt(521712,!1)],Vt.prototype,"setOffer",1),y([rt(521713,!1)],Vt.prototype,"setAnswer",1);var gu=class{constructor(i){d(this,"tag");d(this,"len");d(this,"data");let e=new DataView(i);this.tag=e.getUint16(),this.len=e.getUint16(2),this.data=new Uint8Array(i).slice(4,4+this.len).buffer}},Tu=class{constructor(i){d(this,"tinyId");d(this,"data");let e=new DataView(i),t=0,r=[];for(;t<e.byteLength;){let o=e.getUint16(t+2),n=new gu(new Uint8Array(i).slice(t,t+2+2+o).buffer);r.push(n),t+=4+o}r.forEach(o=>{o.tag===1?this.tinyId=new TextDecoder().decode(o.data):o.tag===2&&(this.data=o.data)})}},Tp=new Set;function Fr(){let s=Math.floor(Math.random()*4294967296);return Tp.has(s)?Fr():(Tp.add(s),s)}var Ap=Pe(je());var Hr=class extends Ap.default{constructor(e){super();d(this,"userId");d(this,"tinyId");d(this,"_sdpSemantics");d(this,"_isUplink");d(this,"_room");d(this,"_log");d(this,"_currentState","DISCONNECTED");d(this,"_prevTime",-1);this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=C.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:(E.emit(T.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 tn=class extends Hr{constructor(e){super(k(v({},e),{isUplink:!0}));d(this,"localMainAudioTrack",null);d(this,"localMainVideoTrack",null);d(this,"localAuxAudioTrack",null);d(this,"localAuxVideoTrack",null);d(this,"_isPublishingAux",!1);d(this,"_publishingLocalAudioTrack");d(this,"_publishingLocalVideoTrack");d(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});d(this,"_flag",0);d(this,"_checkPublishStateTimeoutId",-1);this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:r,smallVideoSsrc:o,smallVideoRtxSsrc:n,auxVideoSsrc:a,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:r||0,small:o||0,smallRtx:n||0,auxiliary:a||0,auxiliaryRtx:c||0}}get flag(){return this._flag}set flag(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}checkPublishState(e=!1){if(!e&&this._checkPublishStateTimeoutId>0)return;let{publishState:t,serverPublishState:r}=this,o=Object.keys(t).find(n=>t[n]!==r[n]);if(o)if(e)this._log.warn(`publish state not matched, ${o} local:${t[o]} server:${r[o]} ${Ei()} ${_r()}`),N.addCount({key:521e3});else{this._checkPublishStateTimeoutId=re.run("timeout",()=>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,r,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(Qt()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((r=a[1])!=null&&r.track),e.smallVideo=!!((o=a[2])!=null&&o.track),e.auxVideo=!!((n=a[3])!=null&&n.track)):a.forEach(c=>{c.track&&(c.track.kind===m.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}get publishingState(){let{publishState:e}=this,t=v({},e);return this._publishingLocalAudioTrack&&(t.audio=!0),this._publishingLocalVideoTrack&&(this._isPublishingAux?t.auxVideo=!0:(t.bigVideo=!0,this._publishingLocalVideoTrack.small&&(t.smallVideo=!0))),t}get serverPublishState(){return{audio:!!(this.flag&$i),bigVideo:!!(this.flag&Hi),smallVideo:!!(this.flag&Ws),auxVideo:!!(this.flag&ar)}}get muteState(){var e,t,r;return{audio:!!((e=this.localMainAudioTrack)!=null&&e.muted),bigVideo:!!((t=this.localMainVideoTrack)!=null&&t.muted),auxVideo:!!((r=this.localAuxVideoTrack)!=null&&r.muted)}}initialize(){this.installEvents()}close(e){var r;let t=((r=this._peerConnection)==null?void 0:r.getSenders())||[];for(let o of t)o.replaceTrack(null);super.close(e),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}installSPCEvents(){var e,t;(e=this.singlePC)!=null&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(t=this.singlePC)==null||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallSPCEvents(){var e;(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}emitConnectionStateChangedEvent(e,t){var n,a,c;let r=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:r,state:e}))),o}onVideoEncodeFailed(e){var t,r;e&&e.isMediaTrackActive&&this.videoCodec==="h264"&&(this._log.warn("h264 encoder not working"),(t=this.singlePC)!=null&&t.isVP8EncodeSupported&&(this._log.warn("switch to vp8"),(r=this.singlePC)==null||r.switchVideoEncoder("vp8")))}publish(o){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){var l,h,u,p,_,I,R;if(!this.singlePC)return;this.installEvents(),yield this.singlePC.waitForPeerConnectionConnected();let{publishState:n,muteState:a}=this;if(e&&(this._publishingLocalAudioTrack=e,n.audio=!0,a.audio=e.muted),t){if(!this.singlePC.isH264EncodeSupported&&!this.singlePC.isVP8EncodeSupported)throw new b({code:S.NOT_SUPPORTED_H264,message:V({key:w.NOT_SUPPORTED_H264ENCODE})});pe&&fr()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn("fallback video to 480p"),t.setProfile(pt["480p_2"]),yield t.applyProfile()),this._publishingLocalVideoTrack=t,r?(n.auxVideo=!0,a.auxVideo=t.muted):(n.bigVideo=!0,a.bigVideo=t.muted)}this._isPublishingAux=r;let c;if(t&&!r&&t.small&&(c=this._room.videoManager.smallTrack,n.smallVideo=!0),yield this._signalChannel.sendWaitForResponseWithRetry({command:q.SPC_PUBLISH,responseCommand:B.SPC_PUBLISH_RESULT,data:k(v({},this.singlePC.uplinkSSRC),{state:n,muteState:a}),retries:3}),yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:c,isAuxiliary:r}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,t){this[r?"localAuxVideoTrack":"localMainVideoTrack"]=t;let{scaleResolutionDownBy:D}=t;yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[r?3:1],D,t.streamType)}e&&(this[r?"localAuxAudioTrack":"localMainAudioTrack"]=e),yield this.singlePC.setBandwidth({audio:((l=this.localMainAudioTrack)==null?void 0:l.profile.bitrate)||((h=this.localAuxAudioTrack)==null?void 0:h.profile.bitrate),bigVideo:(u=this.localMainVideoTrack)==null?void 0:u.profile.bitrate,smallVideo:(_=(p=this.localMainVideoTrack)==null?void 0:p.small)==null?void 0:_.bitrate,auxVideo:(I=this.localAuxVideoTrack)==null?void 0:I.profile.bitrate}),this.sendMediaSettings(),this.installTrackMuteEvents(e,t),(this._room.preferHW||(R=this._room.scheduleResult.config)!=null&&R.preferHW)&&t&&t.profile.width*t.profile.height>=1280*720&&this.singlePC.useHWEncoder(!0,r?7:2)})}publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:o}){if(!gt())return;this._log.info("publish by transceiver");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack,c=this._peerConnection.getTransceivers(),l=[],h=[],u=(_,I,R)=>{var G,te;let D=c[I].sender.replaceTrack(R);h.push(I),(G=this.singlePC)!=null&&G.enableInsertableStreams&&D.then(()=>this.createEncodedStreams(c[I].sender,_)),(te=this.singlePC)!=null&&te.scriptTransformWorker&&this.initSenderTransfrom(c[I].sender,_),l.push(D)};a&&u(e.mediaType,0,a),n&&u(t.mediaType,o?3:1,n),r&&u(8,2,r);let p=this.singlePC.setTransceiverDirection(z.SENDONLY,h);return l.push(p),Promise.all(l)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._publishingLocalAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._publishingLocalVideoTrack;case 2:return this.localAuxVideoTrack||this._publishingLocalVideoTrack;default:return null}}createEncodedStreams(e,t){var a,c;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let r=e.createEncodedStreams(),o=new AbortController;(a=this.singlePC)==null||a.addAbortController(e,o),((c=this.getTrackByMediaType(t))!=null&&c.enableEncodeFrame?r.readable.pipeThrough(new TransformStream({transform:(l,h)=>{var p;let u=this.getTrackByMediaType(t);h.enqueue((p=this.singlePC)!=null&&p.isUsingH264&&u?u.encodeFrame(l,t===8):l)}}),o):r.readable).pipeTo(r.writable,o).catch(l=>{this._log.debug("encoded stream error",l),l!=="destory"&&this._log.warn(l)})}initSenderTransfrom(e,t){if(!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker)return;let r=t!==2,o=t===8;e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:t===1,isMain:r,isSmall:o}))}enableSmall(e){return f(this,null,function*(){var r;if(!this.singlePC)return;let t=this._peerConnection.getTransceivers();if(e){if(this._room.videoManager.smallTrack){let{sender:o}=t[2];(r=this.singlePC)!=null&&r.enableInsertableStreams&&this.createEncodedStreams(o,8),yield o.replaceTrack(this._room.videoManager.smallTrack),yield this.singlePC.setTransceiverDirection(z.SENDONLY,[2])}}else yield t[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(z.INACTIVE,[2]);this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){let o=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localMainAudioTrack&&!this.localAuxAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=k(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=k(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.singlePC.setTransceiverDirection(z.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return f(this,null,function*(){let t={state:this.publishingState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponseWithRetry({command:q.PUBLISH_STATE_CHANGE,data:t,responseCommand:B.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:q.UNPUBLISH,commandDesc:"unpublish",responseCommand:B.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===S.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let r=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:o,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:o=this._publishingLocalVideoTrack),zt){if(r&&r.outMediaTrack){let a=r.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=o.profile.bitrate*1e3,o.small&&(this._mediaSettings.smallVideoWidth=o.small.width,this._mediaSettings.smallVideoHeight=o.small.height,this._mediaSettings.smallVideoFps=o.small.frameRate,this._mediaSettings.smallVideoBps=o.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else r&&r.outMediaTrack&&(this._mediaSettings.audioChannel=r.profile.channelCount,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=r.profile.sampleRate),o&&o.outMediaTrack&&(this._mediaSettings.videoWidth=o.profile.width,this._mediaSettings.videoHeight=o.profile.height,this._mediaSettings.videoFps=o.profile.frameRate,this._mediaSettings.videoBps=o.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:q.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:B.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?m.AUXILIARY:m.MAIN} stream`),Qt()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return f(this,null,function*(){var o;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===m.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)!=null&&o.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===z.INACTIVE&&(yield this.singlePC.setTransceiverDirection(z.SENDONLY,[n]))}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?m.AUXILIARY:m.MAIN} stream`),Qt()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return f(this,null,function*(){if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===m.AUDIO)yield r[0].sender.replaceTrack(null);else{let o=t?3:1;yield r[o].sender.replaceTrack(null),o===1&&this._room.videoManager.hasSmall&&(yield r[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(z.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(e){return f(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders(),r=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!r||t.find(a=>a.track===r))return!1;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${r.kind} track ${r.id} ${r.label} on ${o?m.AUXILIARY:m.MAIN} stream`),r.kind===m.AUDIO&&t[0]&&(yield t[0].replaceTrack(r)),r.kind===m.VIDEO&&(!o&&t[1]&&(yield t[1].replaceTrack(r)),o&&t[3]&&(yield t[3].replaceTrack(r))),!0})}setBandwidth(o){return f(this,arguments,function*({bandwidth:e,type:t,videoType:r}){if(this.singlePC){let n={};t===m.AUDIO?n.audio=e:r==="big"?n.bigVideo=e:r==="small"?n.smallVideo=e:n.auxVideo=e,yield this.singlePC.setBandwidth(n)}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info(`send muted state: ${JSON.stringify(this.muteState)}`),this._signalChannel.sendWaitForResponseWithRetry({command:q.UPDATE_MUTE_STAT,responseCommand:B.MUTE_RESULT,data:this.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&E.emit(T.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=m.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===m.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===m.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===m.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===m.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===dr?(this._log.error(Oe.NOT_SUPPORTED_H264ENCODE),new b({code:S.NOT_SUPPORTED_H264,message:V({key:w.NOT_SUPPORTED_H264ENCODE})})):new b({code:S.UNKNOWN,message:V({key:w.SIGNAL_RESPONSE_FAILED,data:{signalResponse:B.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}))})}};y([Qe(function({localVideoTrack:e}){e==null||e.once("6",this.onVideoEncodeFailed,this)})],tn.prototype,"publish",1),y([Qe(function({localVideoTrack:e}){e==null||e.off("6",this.onVideoEncodeFailed,this)})],tn.prototype,"unpublish",1);var Eu=tn;function Cp(s){return Object.keys(s).filter(i=>s[i])}var xs=class extends Hr{constructor(e){super(k(v({},e),{isUplink:!1}));d(this,"_flag",0);d(this,"isRobot",!1);d(this,"role","anchor");d(this,"remoteAudioTrack");d(this,"remoteVideoTrack");d(this,"remoteAuxiliaryTrack");d(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});d(this,"jitterBufferTimeoutId",-1);this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new Oi(this._room,this),this.remoteVideoTrack=new oi(this._room,this),this.remoteAuxiliaryTrack=new Cs(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 pi(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===m.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){clearTimeout(this.jitterBufferTimeoutId),super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){this.singlePC&&(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){this.singlePC&&(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){var h,u;let t=e.streams[0],{track:r,receiver:o}=e;if(!t.id.includes(this.tinyId))return;let a=t.id.includes("aux")?"auxiliary":"main";this._log.debug(`ontrack ${a} ${r.kind}`);let c=m.AUDIO;r.kind===m.VIDEO&&(c=a===m.MAIN?m.VIDEO:m.AUXILIARY);let l=this.remoteAudioTrack;c===m.VIDEO?l=this.remoteVideoTrack:c===m.AUXILIARY&&(l=this.remoteAuxiliaryTrack),(h=this.singlePC)==null||h.receiverRemoteTrackMap.set(o,l),(u=this.singlePC)!=null&&u.scriptTransformWorker&&this.initReceiverTransform(o,a,r.kind===m.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(o),l.setInputMediaStreamTrack(r)}createEncodedStreams(e){if(!this.singlePC.insertableStreamsAbortMap.has(e)){let t=e.createEncodedStreams(),r=new AbortController,o={abortController:r,enqueue:n=>{var c,l;let a=(c=this.singlePC)==null?void 0:c.receiverRemoteTrackMap.get(e);return!a||a.kind==="video"&&!((l=this.singlePC)!=null&&l.isUsingH264)?n:a.decodeFrame(n)}};t.readable.pipeThrough(new TransformStream({transform:(n,a)=>{let c=o.enqueue(n);c&&a.enqueue(c)}})).pipeTo(t.writable,r).catch(n=>{n!=="destory"&&this._log.warn(n)}),this.singlePC.addAbortController(e,r)}}initReceiverTransform(e,t,r){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:r,userId:this.userId,streamType:t}))}subscribe(e,t){return f(this,null,function*(){try{if(this._log.info(`subscribe ${t} ${Cp(e)}`),this.hasSSRC){let r="subscribe_change";Object.values(e).find(o=>o===!0)||(r="unsubscribe"),yield this.sendSubscription(r,e)}else yield this.doSubscribe(e),this.checkTrackEnded(e)}catch(r){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${r.message} ${JSON.stringify(this.muteState)}`),new b({code:S.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):r}})}checkTrackEnded(e){var t,r,o;if((e.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||e.video&&((r=this.remoteVideoTrack.mediaTrack)==null?void 0:r.readyState)==="ended"||e.auxiliary&&((o=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:o.readState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),Ot&&kt<92)return;this.singlePC.startReconnection()}}unsubscribe(r){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 o=v({},this.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(c=>c===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${Cp(o)}]`),n==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(n,o),n==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},o=q.UNSUBSCRIBE,n=B.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=q.SUBSCRIBE_CHANGE,n=B.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:o,data:r,responseCommand:n,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let c=new b({code:a.code,message:V({key:w.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 r={audioSsrc:Fr(),bigVideoSsrc:Fr(),bigVideoRtxSsrc:Fr(),auxVideoSsrc:Fr(),auxVideoRtxSsrc:Fr()},{audioSsrc:o,bigVideoSsrc:n,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:l}=r;this.ssrc={audio:o,video:n,videoRtx:a,auxiliary:c,auxiliaryRtx:l},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});try{let h=yield this._signalChannel.sendWaitForResponseWithRetry({command:q.SPC_SUBSCRIBE,responseCommand:B.SPC_SUBSCRIBE_RESULT,data:{srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:!1,ssrc:r},retries:3,retryTimeout:0});if(h.data.code!==0)throw new b({code:h.data.code,message:h.data.message})}catch(h){throw yield this.removeDownlink(),h}return}this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc})}finally{let r=this._room.scheduleResult.config;Kn&&(r!=null&&r.jitterDelay||r!=null&&r.jitterDelayAux)&&this.setJitterBufferDelay({mainDelay:r.jitterDelay,auxDelay:r.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&&e.jitterDelay||e!=null&&e.jitterDelayAux)&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)})}setJitterBufferDelay({mainDelay:e,auxDelay:t}){if(!Kn||!this.singlePC||!this._peerConnection||gi(e)&&gi(t))return Promise.resolve();this._log.info(`set jitterBuffer main: ${e} aux: ${t}`);let r=this.singlePC.getReceiversByUserId(this.userId);return Y(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),Y(t)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=t,gi(e)&&(this.remoteAudioTrack.jitterBufferDelay=t)),new Promise(o=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:o})})}doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:o}){try{if(e===0&&t===0)return r.forEach(a=>a.jitterBufferTarget=0),o();if(r.forEach(a=>{var u;let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack||gi(e)&&a.track===this.remoteAudioTrack.outMediaTrack;if(c&&gi(t)||!c&&gi(e))return;let l=c?t||0:e,h=(a.jitterBufferTarget||0)+100;h>l||(a.jitterBufferTarget=h,this._log.debug(`set ${c?"aux ":""}${(u=a==null?void 0:a.track)==null?void 0:u.kind} jitterBuffer delay ${h} -> ${l}`))}),!r.find(a=>{let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack?t||0:e;return a.jitterBufferTarget<c}))return this._log.info(`set jitterBuffer main: ${e} aux: ${t} done`),o();this.jitterBufferTimeoutId=setTimeout(()=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:o})},1e3)}catch(n){this._log.warn(`set jitterBuffer delay error: ${n}`),clearTimeout(this.jitterBufferTimeoutId),o()}}get audioReceiver(){var e;return((e=this.singlePC)==null?void 0:e.getReceiversByUserId(this.userId)[0])||null}};y([ii(),J(e=>function(...t){return new Promise((r,o)=>{let n=a=>{this.off("closed",n),o(new b({code:S.API_CALL_ABORTED,message:V({key:w.CONNECTION_ABORTED,data:a})}))};this.on("closed",n),e.apply(this,t).then(r,o).finally(()=>{this.off("closed",n)})})})],xs.prototype,"subscribe",1),y([ii()],xs.prototype,"unsubscribe",1),y([vi(()=>"jitter")],xs.prototype,"setJitterBufferDelay",1);var Rp=xs;function yp(){return J(s=>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;E.emit("61",{room:this});let e=s.apply(this,i);return i.forEach(t=>t.publish(this,e)),e})})}function bp(){return J(s=>function(...i){let e=s.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var Np=Pe(je());function HT(){return Math.floor(Math.random()*16383)}var md=class md extends Np.EventEmitter{constructor(e,t){super();this.room=e;this.signalChannel=t;d(this,"log");d(this,"cmdIdSeqMap",new Map);d(this,"messageMap",new Map);this.log=C.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(B.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",r=>{[...this.messageMap.keys()].forEach(o=>{o.split("_").slice(0,-1).join("_")===r&&this.messageMap.delete(o)})})}send({cmdId:e,data:t}){let r=this.cmdIdSeqMap.get(e)||HT(),o={cmdId:e,msg:btoa(String.fromCharCode(...new Uint8Array(t))),ordered:!0,reliable:!0,streamSeq:r};this.cmdIdSeqMap.set(e,r+1),this.signalChannel.send(q.SEND_CUSTOM_MSG,o),this.log.debug(`send custom msg: ${JSON.stringify(o)}`)}onReceiveMsg(e){let{data:t}=e.data,r=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(r){let o={userId:r,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),n=>n.charCodeAt(0)).buffer};if(t.ordered){let n=`${r}_${o.cmdId}`,a=this.messageMap.get(n);if(!a||a.lastSeq===0)a||(a={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(n,a),setTimeout(()=>this.emitMessage(o,!0),100)),a.cachedMessageMap.set(o.seq,{message:o});else if(Math.abs(a.lastSeq-o.seq)>md.SEQ_INTERVAL)this.messageMap.set(n,{lastSeq:o.seq,cachedMessageMap:new Map}),this.emitMessage(o);else if(o.seq>a.lastSeq){if(o.seq===a.lastSeq+1)this.emitMessage(o);else if(!a.cachedMessageMap.has(o.seq)){let c=setTimeout(()=>this.emitMessage(o,!0),5e3);a.cachedMessageMap.set(o.seq,{message:o,timeoutId:c})}}else this.log.debug(`drop message ${o.userId}-${o.cmdId}-${o.seq}`)}else this.emit("message",o)}else{this.log.warn(`receive msg from unknown user, wait peer-join tinyId: ${t.srcTinyId}`);let o=n=>{n.tinyId===t.srcTinyId&&(this.room.off("peer-join",o),this.onReceiveMsg(e))};this.room.on("peer-join",o),fi(2e3).then(()=>this.room.off("peer-join",o))}}emitMessage(e,t=!1){var a;let r=this.messageMap.get(`${e.userId}_${e.cmdId}`),o=e;if(r){if(t){let c=[...r.cachedMessageMap.values()].sort((l,h)=>l.message.seq-h.message.seq);c[0]&&(o=c[0].message)}r.lastSeq!==0&&o.seq-r.lastSeq>1&&this.log.debug(`msg lost userId: ${o.userId} seq: ${r.lastSeq} -> ${o.seq}`),r.lastSeq=o.seq,clearTimeout((a=r.cachedMessageMap.get(o.seq))==null?void 0:a.timeoutId),r.cachedMessageMap.delete(o.seq)}this.log.debug(`receive custom msg: ${JSON.stringify(o)}`),this.emit("message",o);let n=r==null?void 0:r.cachedMessageMap.get(o.seq+1);n&&this.emitMessage(n.message)}};d(md,"SEQ_INTERVAL",300);var hd=md;var{isString:vp,isUndefined:ws,getNetworkType:$T,isEmpty:rn}=nt,Bt=class extends ld{constructor(e){super(e);d(this,"_businessInfo");d(this,"userManager");d(this,"_version");d(this,"_heartbeat",-1);d(this,"_lastHeartBeatTime",-1);d(this,"_stats");d(this,"_joinTimeout",-1);d(this,"_firstPublishedList",null);d(this,"_joinReject",null);d(this,"_isRelayChanged",!1);d(this,"sdpSemantics");d(this,"signalChannel",null);d(this,"uplinkConnection",null);d(this,"singlePC",null);d(this,"enableSPC",hs);d(this,"_changeBigSmallRecords",new Map);d(this,"networkQuality");d(this,"_iceTransportPolicy");d(this,"forceRelay",!1);d(this,"_turnServers",[]);d(this,"_syncUserListInterval",-1);d(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160});d(this,"enableSEI",!1);d(this,"_enableAudioVolumeEvaluation",!1);d(this,"_audioVolumeIntervalId",0);d(this,"_enableMultiAuxStream",!1);d(this,"_pureAudioPushMode",!1);d(this,"_customMessageManager");d(this,"preferHW",!1);d(this,"healthDetector");d(this,"_updateAudioLevelTaskId",-1);this._stats=new Ko(this,this._log),this.userManager=new xa(this.userId,this._log),this._version=Re,this.sdpSemantics=Gr,ws(e.sdpSemantics)?Yt.isUnifiedPlanDefault()&&(this.sdpSemantics=Gi):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${$T()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=ws(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&hs,!ws(e.enableSPC)&&hs&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new pp(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,r){return f(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",o=>{this.emit("peer-join",o)}),this.userManager.on("2",o=>{this.closeDownLinkConnection(o,"remote user exitRoom"),this.emit("peer-leave",o)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",n=>{var o=Cu(n,[]);E.emit(T.REMOTE_PUBLISH_STATE_CHANGED,v({room:this},o)),this.emit("remote-publish-state-changed",v({},o))}),this.joinParams=e,new Promise((o,n)=>f(this,null,function*(){var a,c;this._joinReject=n;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(h){if(h instanceof b&&h.code===S.SPC_INITIALIZED_FAILED)(a=this.signalChannel)==null||a.destroy(),yield this.initialize();else return n(h)}let l=L();yield this.doJoin(e,(c=this.singlePC)==null?void 0:c.clientAbility),N.addSuccessEvent({key:521708,cost:L()-l}),o(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(l){N.addFailedEvent({key:521708,error:l}),n(l)}this._joinReject=null}))})}initSinglePC(){return f(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new Vt({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",e=>this.emit("sei-message",e)),this.singlePC.on("dump",e=>this.emit("dump",e)),this.singlePC.once("error",()=>this.fallbackToMPC());try{return yield this.singlePC.initialize()}catch(e){throw this.fallbackToMPC(),new b({code:S.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((r,o)=>f(this,null,function*(){var c,l,h;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(Ee.SETUP_FAILED,u=>{this.clearJoinTimeout(),E.emit(T.JOIN_SIGNAL_CONNECTION_END,{room:this,error:u}),o(u)}),me((l=(c=this.scheduleResult)==null?void 0:c.config)==null?void 0:l.singlePC)&&hs&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2);let n={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:e.role,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:Kd(),netType:ur(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0};this._log.debug(`join room signal data: ${JSON.stringify(n)}`);let a=5e3;(h=this.scheduleResult.config)!=null&&h.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(a=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{o(new b({code:S.JOIN_ROOM_FAILED,message:V({key:w.JOIN_ROOM_TIMEOUT})}))},a),E.emit(T.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?q.SPC_JOIN_ROOM:q.JOIN_ROOM,n),this.signalChannel.once(B.JOIN_ROOM_RESULT,u=>{this.clearJoinTimeout();let{code:p,message:_,data:I,tinyId:R}=u.data;E.emit(T.JOIN_RECEIVED_CMD_RES,{room:this,code:p}),p===0?(this._log.info("Join room success, start heartbeat"),R&&(this.tinyId=R),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=I.publishers,this.singlePC&&this.singlePC.connect(k(v({},I.ability),{useVp8:I.ability.useVp8||!!e.useVp8})).catch(()=>{}),r()):(this._log.error(`Join room failed result: ${p} error: ${_}`),o(new b({code:S.JOIN_ROOM_FAILED,extraCode:p,message:V({key:w.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,r=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,r.push(this.initSinglePC().then(o=>(t=o,o)))),this.signalChannel&&(this.signalChannel.race=e,this.signalChannel.close(),r.push(this.signalChannel.connect())),yield Promise.all(r),yield this.doJoin(k(v({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),t),this._log.warn("reJoin success"),ee.logSuccessEvent({userId:this.userId,eventType:Ke.REJOIN}),this.singlePC){let o=n=>{var a;n.state==="CONNECTED"&&((a=this.singlePC)==null||a.off(ai.CONNECTION_STATE_CHANGED,o),this.uplinkConnection instanceof Eu&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(c=>{c.installEvents(),c.onSinglePCReconnected()}))};this.singlePC.on(ai.CONNECTION_STATE_CHANGED,o),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof Yo&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(t){this._log.warn(`reJoin fail ${t}`),this.reset(),ee.logFailedEvent({userId:this.userId,eventType:Ke.REJOIN,error:t}),this.emit("error",new b({code:S.JOIN_ROOM_FAILED,message:V({key:w.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}})}initialize(){return f(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),r=this.signalChannel||Hm(this.userId),o=!!(r&&r.isConnected&&r.keepAlive),n;return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(n=this.scheduleResult.domains[0]),this._log.info(`${o?"reuse":"setup"} signal channel`),o?(r.url=e,r.backupUrl=t,r.room=this,this.signalChannel=r):(this.signalChannel=new Os({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,race:this.enableSPC&&!this.proxy_ws,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?n:void 0}),this._customMessageManager=new hd(this,this.signalChannel),this._customMessageManager.on("message",a=>{this.emit("custom-message",a)})),this.networkQuality||(this.networkQuality=new Ps({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(Ps.EVENT_NETWORK_QUALITY,a=>{var c;this.emit("network-quality",a),(c=this.singlePC)==null||c.detectTCPAndUDP(a)})),Be(this,this.signalChannel).add(Ee.CONNECTION_STATE_CHANGED,a=>{E.emit(T.SIGNAL_CONNECTION_STATE_CHANGED,v({room:this},a)),this.emit("signal-connection-state-changed",a)}).add(Ee.RECONNECT_FAILED,a=>{this.reset(),this.emit("error",a)}).add(B.PEER_JOIN,a=>{let{srcTinyId:c,userId:l,role:h}=a.data.data;this.userManager.addUser({userId:l,tinyId:c,role:h})}).add(B.PEER_LEAVE,a=>{let{userId:c,reason:l=0}=a.data.data;this.userManager.deleteUser(c,l)}).add(B.UPDATE_REMOTE_MUTE_STAT,a=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(a.data)}).add(B.CLIENT_BANNED,a=>{let c=a.data.data,{reason:l}=c;if(ee.uploadEvent({log:`stat-banned:${l}`,userId:this.userId}),l==="user_time_out"){this._log.warn(`${l} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[l==="kick"?"error":"info"](`user was banned because of [${l}]`),this.reset(),this.emit("banned",{reason:l})}),this.signalChannel.once(Ee.SETUP_SUCCESS,a=>{this.tinyId=a.signalInfo.tinyId,E.emit(T.JOIN_SIGNAL_CONNECTION_END,{room:this})}),E.emit(T.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),o&&E.emit(T.JOIN_SIGNAL_CONNECTION_END,{room:this}),o})}setSignalChannel(e){this.signalChannel=e,e||Se(this)}leave(){return f(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),E.emit(T.LEAVE_SEND_CMD,{room:this}),(e=this.signalChannel)==null||e.send(q.LEAVE_ROOM)})}clearNetworkQuality(){this.networkQuality&&(this.networkQuality.stop(),delete this.networkQuality)}closeConnections(){this.remotePublishedUserMap.forEach(e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=re.run("ric",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 n;let e=this.badCaseDetector.getMonitorFreeze(),t=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});this.badCaseDetector.resetMonitor();let r=(n=this.signalChannel)!=null&&n.isConnected?hm(this.userId):[],o=k(v({str_sdk_version:Hs,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:r,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},t),{msg_device_info:v({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:ur()},t.msg_device_info)});if(this.heartbeatReport=o,E.emit(T.HEARTBEAT_REPORT,{room:this,report:o}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(q.ON_QUALITY_REPORT,o);let a=Date.now();this._lastHeartBeatTime>0&&a-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${a-this._lastHeartBeatTime}`),this._lastHeartBeatTime=a,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",k(v({},o),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.filter(r=>r.flag!==Cd).map(({userId:r,srcTinyId:o,flag:n})=>{r===this.userId&&this.uplinkConnection&&(this.uplinkConnection.flag=n);let a=this.remotePublishedUserMap.get(r);return a&&this.checkSubscribeBigSmallVideo(a),{userId:r,tinyId:o,flag:n}});e.data.mixRobotList.forEach(({userId:r,srcTinyId:o,flag:n,mixUserList:a})=>{t.unshift({userId:r,tinyId:o,flag:n,isRobot:!0,mixUserList:a})}),E.emit(T.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 Yo&&(this.uplinkConnection=null)),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:t,flag:r,isRobot:o}){let n=new(this.singlePC?Rp:du)({userId:e,tinyId:t,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:o});this.userManager.addRemotePublishedUser(n),this.installDownlinkEvents(n,e),this.emit("remote-published",n)}closeDownLinkConnection(e,t="remote user unpublished"){let r=this.remotePublishedUserMap.get(e);r&&(r.close(t),this.emit("remote-unpublished",r))}installDownlinkEvents(e,t){e.on("error",r=>{let o=r.getCode();o!==S.ICE_TRANSPORT_ERROR&&(o===S.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",r))}),e.on("connection-state-changed",r=>{this.emit("media-connection-state-changed",k(v({},r),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=re.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){re.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then(e=>{this.userManager.setUserList(e)}).catch(e=>{this._log.debug(`sync user list failed: ${e}`)})}getUserList(){var e;return(e=this.signalChannel)!=null&&e.isConnected?this.signalChannel.sendWaitForResponse({command:q.GET_USER_LIST,responseCommand:B.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:t})=>{let{code:r,message:o}=t;if(r===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:c,role:l})=>({userId:a,tinyId:c,role:l}));throw V({key:w.SIGNAL_RESPONSE_FAILED,data:{signalResponse:B.USER_LIST_RES,code:r,message:o}})}):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this.signalChannel&&!this.signalChannel.isOnline||!iu)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let e=this.getAllConnections();if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(e[t].getReconnectionCount()<6)return!1;return!0}checkConnectionsToReconnect(){var e;this.singlePC?((e=this.singlePC.getPeerConnection())==null?void 0:e.connectionState)===ce.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(r=>{if(r instanceof Ye&&!r.getIsReconnecting()){let o=r.getPeerConnection();o&&o.connectionState===ce.CLOSED&&(this._log.warn(`[${r.getUserId()}] pc is closed but not reconnect`),r.startReconnection())}})}fallbackToMPC(){return f(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),ee.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 Yo({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),t.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localMainAudioTrack,localVideoTrack:t.localMainVideoTrack,isAuxiliary:!1})),t.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localAuxAudioTrack,localVideoTrack:t.localAuxVideoTrack,isAuxiliary:!0})),t.close()}for(let t of[...this.remotePublishedUserMap.values()]){let r=new du({userId:t.userId,tinyId:t.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:t.flag,remoteAudioTrack:t.remoteAudioTrack,remoteVideoTrack:t.remoteVideoTrack,remoteAuxiliaryTrack:t.remoteAuxiliaryTrack});this.installDownlinkEvents(r,t.userId),this.remotePublishedUserMap.set(t.userId,r),t.isMainStreamSubscribed&&(yield r.subscribe(t.subscribeState,"main")),t.isAuxStreamSubscribed&&(yield r.subscribe(t.subscribeState,"auxiliary"))}})}destroy(){this.isDestroyed||(this.signalChannel&&(this._log.info("destroying SignalChannel"),this.signalChannel.close(),this.signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new b({code:S.INVALID_OPERATION,message:V({key:w.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),re.clearTask(this._audioVolumeIntervalId))}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:q.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:B.SWITCH_ROLE_RES,retries:1};return this._log.info(`switchRole signal data: ${JSON.stringify(t.data)}`),this.signalChannel.sendWaitForResponseWithRetry(t).then(r=>{let{code:o,message:n}=r.data;if(o!==0)throw new b({code:S.SWITCH_ROLE_FAILED,message:V({key:w.SWITCH_ROLE_FAILED,data:{message:n,code:o}})});this.role=e}).catch(r=>{throw r instanceof b&&r.getCode()===S.API_CALL_TIMEOUT&&(r=new b({code:S.SWITCH_ROLE_FAILED,message:V({key:w.SWITCH_ROLE_TIMEOUT})})),this._log.error(r),r})}publish(...e){return f(this,null,function*(){let t={},r={};e.forEach(c=>{c instanceof ht&&(c instanceof si?r.audio=c:t.audio=c),c instanceof $e&&(c instanceof st&&c.mediaType===2?r.video=c:t.video=c)});let o=rn(t),n=rn(r);(!o||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new Eu({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new Yo({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",c=>{this.emit("media-connection-state-changed",k(v({},c),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",c=>{let l=c.getCode();l!==S.ICE_TRANSPORT_ERROR&&(l===S.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",c))}));let a=e.map(c=>c.kind).join(",");o||(this._log.info(`publish() => main ${a}`),yield this.uplinkConnection.publish({localAudioTrack:t.audio,localVideoTrack:t.video,isAuxiliary:!1}),this._log.info("main is published")),n||(this._log.info(`publish() => aux ${a}`),yield this.uplinkConnection.publish({localAudioTrack:r.audio,localVideoTrack:r.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={},r={};e.forEach(o=>{!o.mediaTrack||!o.isPublished||(o instanceof ht&&(o instanceof si?r.audio=o:t.audio=o),o instanceof $e&&(o instanceof st&&o.mediaType===2?r.video=o:t.video=o))});try{let o=e.map(n=>n.kind).join(",");rn(t)||(this._log.info(`unpublish() => main ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:t.audio,localVideoTrack:t.video})),rn(r)||(this._log.info(`unpublish() => aux ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:r.audio,localVideoTrack:r.video}))}catch(o){}this.localTracks.size===0&&this.closeUplink("you unpublished")})}addTrack(e){if(!this.uplinkConnection||!e.mediaTrack)return Promise.resolve();let t=this.uplinkConnection.addTrack(e);return e.publish(this,t),t}removeTrack(e){return!this.uplinkConnection||!e.mediaTrack?Promise.resolve():this.uplinkConnection.removeTrack(e).then(t=>(e.unpublish(),t))}replaceTrack(e){return!this.uplinkConnection||!e.mediaTrack||!Cc()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{t&&E.emit(T.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:m.VIDEO,videoType:m.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(...e){return f(this,null,function*(){if(e=e.filter(n=>!n.isSubscribed),e.length===0)return;let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";try{let n=v({},r.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:n.audio=!0;break;case 4:n.video=!0;break;case 8:n.smallVideo=!0;break;case 2:n.auxiliary=!0;break}});let a=this._changeBigSmallRecords.get(t);a&&a.options.smallVideo&&r.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),E.emit(T.SUBSCRIBE_START,{room:this,streamType:o,remotePublishedUser:r,subscribeState:n}),this._log.info(`subscribe() => ${t} ${o} [${id(n)}] prev: [${id(r.subscribeState)}]`),yield r.subscribe(n,o),this._log.info(`subscribe ${t} ${o} done`);for(let c of e)c.mediaTrack||(yield c.waitHasMediaTrack());E.emit(T.SUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:r})}catch(n){let a=n instanceof b?n.getCode():S.UNKNOWN,c=n;throw n instanceof b?a===S.REMOTE_STREAM_NOT_EXIST&&(c=new b({code:S.API_CALL_ABORTED,message:V({key:w.API_CALL_ABORTED,data:{message:n.message,userId:t,streamType:o}})}),this._log.warn(c)):(c=new b({code:a,message:V({key:w.SUBSCRIBE_FAILED,data:{message:n.message,userId:t,streamType:o}})}),this._log.error(c)),c}})}unsubscribe(...e){return f(this,null,function*(){let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${t} ${o}`);try{yield r.unsubscribe({remoteTracks:e,streamType:o})}catch(n){this._log.warn(`unsubscribe() => failed ${n}`)}e.forEach(n=>{n.unsubscribe(),n.mediaType===8&&n.setMediaType(4)}),E.emit(T.UNSUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:r})})}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)),E.emit(T.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&re.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=re.run("intervalInWorker",()=>{var o;Ar.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];(o=this.remotePublishedUserMap)==null||o.forEach(n=>{if(n.muteState.hasAudio){!Ar.isRunning&&n.muteState.audioAvailable&&n.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(n):n.remoteAudioTrack.volume=0;let a=Math.floor(n.remoteAudioTrack.getAudioLevel()*100);r.push({userId:n.userId,volume:a})}}),this.emit("audio-volume",r)},{delay:e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return f(this,null,function*(){var n;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||this._updateAudioLevelTaskId!==-1)return;let r=(n=this.uplinkConnection.getPeerConnection())==null?void 0:n.getSenders()[0];if(!r)return;let o=Math.max(e,500);this._log.warn(`updateAudioLevelFromSenderStat ${o}`),this._updateAudioLevelTaskId=re.run("intervalInWorker",()=>f(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack){this.stopUpdateAudioLevelFromSenderStat();return}let a=yield r.getStats();if(this._updateAudioLevelTaskId<0)return;let c=this.uplinkConnection.localMainAudioTrack;a.forEach(l=>{l.type==="media-source"&&l.audioLevel&&(c.volume=l.audioLevel)})}),{delay:o,backgroundTask:t})})}stopUpdateAudioLevelFromSenderStat(){var e;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),re.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,(e=this.uplinkConnection)!=null&&e.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(e){var o;let{audioReceiver:t}=e;if(!Rc||!t)return;let r=(o=t.getSynchronizationSources()[0])==null?void 0:o.audioLevel;Y(r)?e.remoteAudioTrack.volume=Math.min(r*2,1):t.getStats().then(n=>{n.forEach(a=>{a.type==="inbound-rtp"&&Y(a.audioLevel)&&(e.remoteAudioTrack.volume=a.audioLevel)})})}getLocalAudioStats(){return f(this,null,function*(){var t;let e={};return e[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},(t=this.uplinkConnection)!=null&&t.localMainAudioTrack&&(e[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),e})}getLocalVideoStats(){return f(this,null,function*(){var t,r;let e={};return e[this.userId]=((r=(t=this.uplinkConnection)==null?void 0:t.localMainVideoTrack)==null?void 0:r.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},e})}getTransportStats(){return 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 r=yield this._stats.getReceiverStats(t);e.downlinksRTT[r.userId]=r.rtt}return e})}getRemoteVideoStats(e){return f(this,null,function*(){let t={};for(let[r,o]of this.remotePublishedUserMap)e==="main"&&o.muteState.hasVideo&&(t[r]=o.remoteVideoTrack.stat),e==="auxiliary"&&o.muteState.hasAuxiliary&&(t[r]=o.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return f(this,null,function*(){let e={};for(let[t,r]of this.remotePublishedUserMap)r.muteState.hasAudio&&(e[t]=r.remoteAudioTrack.stat);return e})}setTurnServer(e,t){this._log.info(`set turn server: ${JSON.stringify(e)} ${t||""}`);let r=[];Array.isArray(e)?e.forEach(o=>r.push(nt.getTurnServer(o))):nt.isPlainObject(e)&&r.push(nt.getTurnServer(e)),this._turnServers=r,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:q.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:B.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:q.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:B.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?q.START_PUBLISH_TENCENT_CDN:q.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?B.START_PUBLISH_TENCENT_CDN_RES:B.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?q.STOP_PUBLISH_TENCENT_CDN:q.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?B.STOP_PUBLISH_TENCENT_CDN_RES:B.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:q.START_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:B.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:q.UPDATE_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:B.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:q.STOP_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:B.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"})}sendAbilityStatus(e){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:q.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:B.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(r=>{})}getIceServers(){return this._turnServers.length===0&&this.scheduleResult.iceServers?this.scheduleResult.iceServers:this._turnServers}getIceTransportPolicy(){return this.forceRelay?"relay":this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=nt.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:r,muteState:{hasSmall:o,hasVideo:n}}=e;if(!o&&!n||!t.video&&!t.smallVideo)return;let a=this._changeBigSmallRecords.get(r);if(!a||a.isSubscribing||a.reSubscribeCount<=0)return;let{options:c,reSubscribeCount:l}=a;if(c.video&&t.video||c.smallVideo&&t.smallVideo&&o)return;let h={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:c.video,smallVideo:c.smallVideo};try{if(!o&&h.smallVideo&&(h.video=!0,h.smallVideo=!1),h.smallVideo===t.smallVideo&&h.video===t.video)return;a.isSubscribing=!0,a.reSubscribeCount=l-1,yield e.subscribe(h,"main"),e.remoteVideoTrack.setMediaType(h.smallVideo?8:4),this._log.info(`change [${r}] to ${h.smallVideo?"small":"big"} video successfully. count ${Wr-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=Wr}catch(u){this._log.info(`change [${r}] to ${h.smallVideo?"small":"big"} video failed. count ${Wr-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(r)}})}changeType(e,t){let o={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:Wr};this._changeBigSmallRecords.set(t.userId,o),this._log.info(`set [${t.userId}] video prefer type: ${e?"small":"big"}`);let n=this.remotePublishedUserMap.get(t.userId);n&&this.checkSubscribeBigSmallVideo(n)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(vp(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!ws(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new b({code:S.INVALID_PARAMETER,message:V({key:w.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(!ws(e.userDefineRecordId)){let r=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(r)===null)throw new b({code:S.INVALID_PARAMETER,message:V({key:w.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!ws(e.userDefinePushArgs))if(vp(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:S.INVALID_PARAMETER,message:V({key:w.INVALID_USER_DEFINE_PUSH_ARGS})});rn(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){return f(this,null,function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&Ri)return this.singlePC.enableInsertableStreams=!0,yield this.singlePC.waitForPeerConnectionConnected(),yield this.singlePC.startReconnection()})}sendSignalMessage(e){var t;return this.signalChannel?(t=this.signalChannel)==null?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new b({code:S.INVALID_OPERATION,message:"not join"}))}get enableCodecPipeline(){return this.videoManager.encodePipeline.length>0||this.videoManager.decodePipeline.length>0||this.audioManager.encodePipeline.length>0||this.audioManager.decodePipeline.length>0}get scriptTransformWorker(){var e;return(e=this.singlePC)==null?void 0:e.scriptTransformWorker}};y([le(["left",Q.INIT],"joined"),tt({settings:{retries:1,timeout:0},onRetrying(e){this._log.warn(`join retry ${e}`)},onRetryFailed(e){this._log.error("join failed",e)},onError(e,t){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),wt(!0),this.reset(),t()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),t()):(this.reset(),t())}}),wm()],Bt.prototype,"join",1),y([le("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),Um(),fa("leave room"),Oo({fnName:"publish",validateArgs:!1}),Oo({fnName:"unsubscribe",validateArgs:!1})],Bt.prototype,"leave",1),y([ii(),yp(),tt({settings:{retries:ui,timeout:e=>yt(e)},onError(e,t,r){var o;(o=e.message)!=null&&o.includes("timeout")?(this._log.warn("publish timeout"),t()):(this._log.error(`publish failed: ${e}`),r(e),E.emit(T.PUBLISH_FAILED,{room:this}))}})],Bt.prototype,"publish",1),y([Oo({fnName:"publish"}),Kh("api-call"),ii(),bp(),Qe(function(){var e,t;this.localTracks.size===0&&Ki()&&((t=(e=this.singlePC)==null?void 0:e.getPeerConnection())==null||t.getSenders().forEach(r=>r.track&&r.replaceTrack(null)))})],Bt.prototype,"unpublish",1),y([ha(e=>{if(e.code!==S.API_CALL_ABORTED)throw e}),vi(e=>e.userId)],Bt.prototype,"replaceTrack",1),y([vi((...e)=>e[0].userId),Ta(),Vm(),tt({settings:{retries:ui,timeout:e=>yt(e)},onError(e,t,r,o){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error(`subscribe failed: ${e}`),r(e),E.emit(T.SUBSCRIBE_FAILED,{room:this,remoteTracks:o}))}})],Bt.prototype,"subscribe",1),y([Oo({fnName:"subscribe",callback(...e){this.singlePC||e.forEach(t=>{let r=this.remotePublishedUserMap.get(t.userId);r&&!r.isMainStreamSubscribed&&!r.isAuxStreamSubscribed&&r.close("you unsubscribed")})}}),vi((...e)=>e[0].userId)],Bt.prototype,"unsubscribe",1);Qo.create=Qo._create.bind(Qo,Bt);var r1=Qo;export{r1 as default};
|
|
118
|
+
next answer: ${this.filterSDPDirection(t)}`),this._log.warn(`offer: ${e==null?void 0:e.sdp}`),this._log.warn(`answer: ${t}`),this._log.warn(`transceivers: ${JSON.stringify(this._peerConnection.getTransceivers().map(({mid:l,currentDirection:h,direction:u,stopped:p})=>({mid:l,currentDirection:h,direction:u,stopped:p})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._isSDPLogged=!0),this._updateSDPPromise=null,o(c)}})),this._updateSDPPromise}setTransceiverDirection(e,t){return f(this,null,function*(){if(!ae||!this._peerConnection||!this._parsedAnswer)return;this._log.info(`setting transceiver ${t.join(",")} direction to ${e}`);let r=this._peerConnection.getTransceivers();t.forEach(o=>{r[o].direction!==e&&(r[o].direction=e)});for(let o of t){let n=this._parsedAnswer.media[o].direction;e===z.INACTIVE&&n===z.RECVONLY&&(this._parsedAnswer.media[o].direction=e),e===z.SENDONLY&&n===z.INACTIVE&&(this._parsedAnswer.media[o].direction=z.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(e=""){return ge(e).media.map(r=>r.direction)}setOffer(e){this._log.info("setting offer");let t=hp(e.sdp,this.clientAbility,this._serverAbility);return this._log.debug(t),this._peerConnection.setLocalDescription({type:"offer",sdp:t})}setAnswer(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._peerConnection.setRemoteDescription(e)}switchVideoEncoder(e){return f(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach(r=>{var o;if(r.type===m.VIDEO){let n=this._serverAbility.video.codecs.find(a=>a.codec.toLowerCase()===e);n&&!((o=r.payloads)!=null&&o.includes(String(n.payload)))&&(r.fmtp=[],r.payloads="",r.rtp=[],r.rtcpFb=[],Br(r,n),t=!0)}}),t&&(this._log.warn(`switch video encoder to ${e}`),yield this.updateSDP())})}useHWEncoder(e=!0,t){return f(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let r=!1,o=[];g(t)?o=this._parsedAnswer.media.slice(1,4):t===2?o.push(this._parsedAnswer.media[1]):t===3?o.push(this._parsedAnswer.media[2]):t===7&&o.push(this._parsedAnswer.media[3]),o.forEach(n=>{var a;if(n.type===m.VIDEO){let c;e&&this.is42001fSupported?c=this.clientAbility.video.codecs.find(l=>l.fmtp.includes("42001f")):e||(c=this._serverAbility.video.codecs.find(l=>l.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264"))),c&&!((a=n.payloads)!=null&&a.includes(String(c.payload)))&&(n.fmtp=[],n.payloads="",n.rtp=[],n.rtcpFb=[],Br(n,c),r=!0)}}),r&&(this._log.warn(`use ${e?"hw":"sw"} encoder`),yield this.updateSDP())})}sendDataChannelMessage(e){var t;(t=this._datachannel)==null||t.send(e)}reset(){this._peerConnection&&(this._peerConnection.close(),this._peerConnection.removeEventListener("track",this._peerConnection._onaddstreampoly,this),this._peerConnection._onaddstreampoly=null,this._peerConnection=null),this._waitForPCConnectedPromise=null,this._parsedAnswer=null}close(){this._log.info("close pc"),this.removeRTCListener(),this.insertableStreamsAbortMap.forEach(e=>Wt(e.abort)&&e.abort("destroy")),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners(),this._room.healthDetector.off("1",this.onBadHealth,this)}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map(r=>t[r])}get isUsingRelay(){return this._room.getIceTransportPolicy()==="relay"}detectTCPAndUDP({uplinkRTT:e,downlinkRTT:t}){var h;if(this.currentState!=="CONNECTED"||this._isRelayTried&&!this._room.forceRelay||this._room.getIceServers().length===0)return;let r=this._signalChannel.rtt,o=Math.max(e,t),{rttRatioThreshold:n,rttThreshold:a}=((h=this._room.scheduleResult.config)==null?void 0:h.useTurnTcpInfo)||{};if(!n||!a||!r||!o)return;let c=Math.floor(o/r),l=(this._isRelayTried||c>n)&&o>a;if(!l){this._rttOverCount=0;return}++this._rttOverCount<5||(this._log.warn(`detectTCPAndUDP ws-rtt: ${r} upRTT: ${e} downRTT: ${t} ratio: ${c} over-count: ${this._rttOverCount} isOver: ${l} isRelayTried: ${this._isRelayTried} force-relay: ${this._room.forceRelay}`),!this.isUsingRelay&&!this._isRelayTried?(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0)):this._room.forceRelay&&this.switchRelay(!1))}switchRelay(e,t=!1){return f(this,null,function*(){if(this.isUsingRelay===e)return;let r=e?"relay":"udp",o=e?521709:521710;try{this._room.forceRelay=e,this._log.warn(`switchRelay ${r}`);let n=Date.now();yield this.doSwitchRelay(r),this._log.warn(`switchRelay ${r} success`),N.addSuccessEvent({key:o,cost:Date.now()-n})}catch(n){this._log.warn(`switchRelay ${r} failed`,n),N.addFailedEvent({key:o,error:n}),t?this._room.reJoin():yield this.switchRelay(!e,!0)}})}doSwitchRelay(e){return new Promise((t,r)=>{let o=setTimeout(()=>{this.stopReconnection(),r(new Error(`switch ${e} timeout`))},1e4);this.startReconnection().then(t,r).finally(()=>clearTimeout(o))})}removeRTCListener(){this._peerConnection&&(this._peerConnection.oniceconnectionstatechange=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.onsignalingstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}};y([fa("reconnect")],Vt.prototype,"startReconnection",1),y([vi(e=>e.userId)],Vt.prototype,"addDownlink",1),y([vi(e=>e)],Vt.prototype,"removeDownlink",1),y([ii(!0)],Vt.prototype,"updateSDP",1),y([rt(521712,!1)],Vt.prototype,"setOffer",1),y([rt(521713,!1)],Vt.prototype,"setAnswer",1);var gu=class{constructor(i){d(this,"tag");d(this,"len");d(this,"data");let e=new DataView(i);this.tag=e.getUint16(),this.len=e.getUint16(2),this.data=new Uint8Array(i).slice(4,4+this.len).buffer}},Tu=class{constructor(i){d(this,"tinyId");d(this,"data");let e=new DataView(i),t=0,r=[];for(;t<e.byteLength;){let o=e.getUint16(t+2),n=new gu(new Uint8Array(i).slice(t,t+2+2+o).buffer);r.push(n),t+=4+o}r.forEach(o=>{o.tag===1?this.tinyId=new TextDecoder().decode(o.data):o.tag===2&&(this.data=o.data)})}},Tp=new Set;function Fr(){let s=Math.floor(Math.random()*4294967296);return Tp.has(s)?Fr():(Tp.add(s),s)}var Ap=Pe(je());var Hr=class extends Ap.default{constructor(e){super();d(this,"userId");d(this,"tinyId");d(this,"_sdpSemantics");d(this,"_isUplink");d(this,"_room");d(this,"_log");d(this,"_currentState","DISCONNECTED");d(this,"_prevTime",-1);this.userId=e.userId,this.tinyId=e.tinyId,this._room=e.room,this._sdpSemantics=e.room.sdpSemantics,this._isUplink=e.isUplink,this._log=C.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:(E.emit(T.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 tn=class extends Hr{constructor(e){super(k(v({},e),{isUplink:!0}));d(this,"localMainAudioTrack",null);d(this,"localMainVideoTrack",null);d(this,"localAuxAudioTrack",null);d(this,"localAuxVideoTrack",null);d(this,"_isPublishingAux",!1);d(this,"_publishingLocalAudioTrack");d(this,"_publishingLocalVideoTrack");d(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0});d(this,"_flag",0);d(this,"_checkPublishStateTimeoutId",-1);this.initialize()}get videoCodec(){var e;return((e=this.singlePC)==null?void 0:e.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:e,bigVideoSsrc:t,bigVideoRtxSsrc:r,smallVideoSsrc:o,smallVideoRtxSsrc:n,auxVideoSsrc:a,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:r||0,small:o||0,smallRtx:n||0,auxiliary:a||0,auxiliaryRtx:c||0}}get flag(){return this._flag}set flag(e){this._flag!==e&&(this._flag=e,this.checkPublishState())}checkPublishState(e=!1){if(!e&&this._checkPublishStateTimeoutId>0)return;let{publishState:t,serverPublishState:r}=this,o=Object.keys(t).find(n=>t[n]!==r[n]);if(o)if(e)this._log.warn(`publish state not matched, ${o} local:${t[o]} server:${r[o]} ${Ei()} ${_r()}`),N.addCount({key:521e3});else{this._checkPublishStateTimeoutId=re.run("timeout",()=>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,r,o,n;let e={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};if(this._peerConnection){let a=this._peerConnection.getSenders();a&&(Qt()?(e.audio=!!((t=a[0])!=null&&t.track),e.bigVideo=!!((r=a[1])!=null&&r.track),e.smallVideo=!!((o=a[2])!=null&&o.track),e.auxVideo=!!((n=a[3])!=null&&n.track)):a.forEach(c=>{c.track&&(c.track.kind===m.AUDIO?e.audio=!0:(e.bigVideo=!0,this._room.videoManager.hasSmall&&(e.smallVideo=!0)))}))}return e}get publishingState(){let{publishState:e}=this,t=v({},e);return this._publishingLocalAudioTrack&&(t.audio=!0),this._publishingLocalVideoTrack&&(this._isPublishingAux?t.auxVideo=!0:(t.bigVideo=!0,this._publishingLocalVideoTrack.small&&(t.smallVideo=!0))),t}get serverPublishState(){return{audio:!!(this.flag&$i),bigVideo:!!(this.flag&Hi),smallVideo:!!(this.flag&Ws),auxVideo:!!(this.flag&ar)}}get muteState(){var e,t,r;return{audio:!!((e=this.localMainAudioTrack)!=null&&e.muted),bigVideo:!!((t=this.localMainVideoTrack)!=null&&t.muted),auxVideo:!!((r=this.localAuxVideoTrack)!=null&&r.muted)}}initialize(){this.installEvents()}close(e){var r;let t=((r=this._peerConnection)==null?void 0:r.getSenders())||[];for(let o of t)o.replaceTrack(null);super.close(e),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}installSPCEvents(){var e,t;(e=this.singlePC)!=null&&e.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(t=this.singlePC)==null||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallSPCEvents(){var e;(e=this.singlePC)==null||e.off("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}emitConnectionStateChangedEvent(e,t){var n,a,c;let r=this._currentState,o=super.emitConnectionStateChangedEvent(e);return o&&r!==e&&(t?t.emit("connection-state-changed",{prevState:r,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:r,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:r,state:e}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:r,state:e}))),o}onVideoEncodeFailed(e){var t,r;e&&e.isMediaTrackActive&&this.videoCodec==="h264"&&(this._log.warn("h264 encoder not working"),(t=this.singlePC)!=null&&t.isVP8EncodeSupported&&(this._log.warn("switch to vp8"),(r=this.singlePC)==null||r.switchVideoEncoder("vp8")))}publish(o){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){var l,h,u,p,_,I,R;if(!this.singlePC)return;this.installEvents(),yield this.singlePC.waitForPeerConnectionConnected();let{publishState:n,muteState:a}=this;if(e&&(this._publishingLocalAudioTrack=e,n.audio=!0,a.audio=e.muted),t){if(!this.singlePC.isH264EncodeSupported&&!this.singlePC.isVP8EncodeSupported)throw new b({code:S.NOT_SUPPORTED_H264,message:V({key:w.NOT_SUPPORTED_H264ENCODE})});pe&&fr()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn("fallback video to 480p"),t.setProfile(pt["480p_2"]),yield t.applyProfile()),this._publishingLocalVideoTrack=t,r?(n.auxVideo=!0,a.auxVideo=t.muted):(n.bigVideo=!0,a.bigVideo=t.muted)}this._isPublishingAux=r;let c;if(t&&!r&&t.small&&(c=this._room.videoManager.smallTrack,n.smallVideo=!0),yield this._signalChannel.sendWaitForResponseWithRetry({command:q.SPC_PUBLISH,responseCommand:B.SPC_PUBLISH_RESULT,data:k(v({},this.singlePC.uplinkSSRC),{state:n,muteState:a}),retries:3}),yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:c,isAuxiliary:r}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,t){this[r?"localAuxVideoTrack":"localMainVideoTrack"]=t;let{scaleResolutionDownBy:D}=t;yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[r?3:1],D,t.streamType)}e&&(this[r?"localAuxAudioTrack":"localMainAudioTrack"]=e),yield this.singlePC.setBandwidth({audio:((l=this.localMainAudioTrack)==null?void 0:l.profile.bitrate)||((h=this.localAuxAudioTrack)==null?void 0:h.profile.bitrate),bigVideo:(u=this.localMainVideoTrack)==null?void 0:u.profile.bitrate,smallVideo:(_=(p=this.localMainVideoTrack)==null?void 0:p.small)==null?void 0:_.bitrate,auxVideo:(I=this.localAuxVideoTrack)==null?void 0:I.profile.bitrate}),this.sendMediaSettings(),this.installTrackMuteEvents(e,t),(this._room.preferHW||(R=this._room.scheduleResult.config)!=null&&R.preferHW)&&t&&t.profile.width*t.profile.height>=1280*720&&this.singlePC.useHWEncoder(!0,r?7:2)})}publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:o}){if(!gt())return;this._log.info("publish by transceiver");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack,c=this._peerConnection.getTransceivers(),l=[],h=[],u=(_,I,R)=>{var G,te;let D=c[I].sender.replaceTrack(R);h.push(I),(G=this.singlePC)!=null&&G.enableInsertableStreams&&D.then(()=>this.createEncodedStreams(c[I].sender,_)),(te=this.singlePC)!=null&&te.scriptTransformWorker&&this.initSenderTransfrom(c[I].sender,_),l.push(D)};a&&u(e.mediaType,0,a),n&&u(t.mediaType,o?3:1,n),r&&u(8,2,r);let p=this.singlePC.setTransceiverDirection(z.SENDONLY,h);return l.push(p),Promise.all(l)}getTrackByMediaType(e){switch(e){case 1:return this.localMainAudioTrack||this._publishingLocalAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._publishingLocalVideoTrack;case 2:return this.localAuxVideoTrack||this._publishingLocalVideoTrack;default:return null}}createEncodedStreams(e,t){var a,c;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let r=e.createEncodedStreams(),o=new AbortController;(a=this.singlePC)==null||a.addAbortController(e,o),((c=this.getTrackByMediaType(t))!=null&&c.enableEncodeFrame?r.readable.pipeThrough(new TransformStream({transform:(l,h)=>{var p;let u=this.getTrackByMediaType(t);h.enqueue((p=this.singlePC)!=null&&p.isUsingH264&&u?u.encodeFrame(l,t===8):l)}}),o):r.readable).pipeTo(r.writable,o).catch(l=>{this._log.debug("encoded stream error",l),l!=="destory"&&this._log.warn(l)})}initSenderTransfrom(e,t){if(!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker)return;let r=t!==2,o=t===8;e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:t===1,isMain:r,isSmall:o}))}enableSmall(e){return f(this,null,function*(){var r;if(!this.singlePC)return;let t=this._peerConnection.getTransceivers();if(e){if(this._room.videoManager.smallTrack){let{sender:o}=t[2];(r=this.singlePC)!=null&&r.enableInsertableStreams&&this.createEncodedStreams(o,8),yield o.replaceTrack(this._room.videoManager.smallTrack),yield this.singlePC.setTransceiverDirection(z.SENDONLY,[2])}}else yield t[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(z.INACTIVE,[2]);this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return f(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){let o=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),c=[];e&&(o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localMainAudioTrack&&!this.localAuxAudioTrack&&(yield a[0].replaceTrack(null),c.push(0))),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=k(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=k(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.singlePC.setTransceiverDirection(z.INACTIVE,c),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return f(this,null,function*(){let t={state:this.publishingState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponseWithRetry({command:q.PUBLISH_STATE_CHANGE,data:t,responseCommand:B.PUBLISH_STATE_CHANGE_RESULT,enableLog:e,retries:3});this.checkPublishResultCode(r.data.code,r.data.message)})}doUnpublish(e=!1){return this._signalChannel.sendWaitForResponse({command:q.UNPUBLISH,commandDesc:"unpublish",responseCommand:B.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===S.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let r=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:o,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:o=this._publishingLocalVideoTrack),zt){if(r&&r.outMediaTrack){let a=r.outMediaTrack.getSettings();this._mediaSettings.audioChannel=a.channelCount||1,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=a.sampleRate||0}if(o&&o.outMediaTrack){let a=o.outMediaTrack.getSettings();this._mediaSettings.videoWidth=a.width||0,this._mediaSettings.videoHeight=a.height||0,this._mediaSettings.videoFps=a.frameRate||0,this._mediaSettings.videoBps=o.profile.bitrate*1e3,o.small&&(this._mediaSettings.smallVideoWidth=o.small.width,this._mediaSettings.smallVideoHeight=o.small.height,this._mediaSettings.smallVideoFps=o.small.frameRate,this._mediaSettings.smallVideoBps=o.small.bitrate*1e3)}if(n&&n.outMediaTrack){let a=n.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=a.width||0,this._mediaSettings.auxVideoHeight=a.height||0,this._mediaSettings.auxVideoFps=a.frameRate||0,this._mediaSettings.auxVideoBps=n.profile.bitrate*1e3}}else r&&r.outMediaTrack&&(this._mediaSettings.audioChannel=r.profile.channelCount,this._mediaSettings.audioBps=r.profile.bitrate*1e3,this._mediaSettings.audioFs=r.profile.sampleRate),o&&o.outMediaTrack&&(this._mediaSettings.videoWidth=o.profile.width,this._mediaSettings.videoHeight=o.profile.height,this._mediaSettings.videoFps=o.profile.frameRate,this._mediaSettings.videoBps=o.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:q.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:B.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?m.AUXILIARY:m.MAIN} stream`),Qt()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return f(this,null,function*(){var o;if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===m.AUDIO)yield r[0].sender.replaceTrack(e.outMediaTrack);else{let n=t?3:1;yield r[n].sender.replaceTrack(e.outMediaTrack),n===1&&((o=this.localMainVideoTrack)!=null&&o.small)&&(yield r[2].sender.replaceTrack(this._room.videoManager.smallTrack)),r[n].direction===z.INACTIVE&&(yield this.singlePC.setTransceiverDirection(z.SENDONLY,[n]))}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?m.AUXILIARY:m.MAIN} stream`),Qt()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return f(this,null,function*(){if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===m.AUDIO)yield r[0].sender.replaceTrack(null);else{let o=t?3:1;yield r[o].sender.replaceTrack(null),o===1&&this._room.videoManager.hasSmall&&(yield r[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(z.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(e){return f(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders(),r=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!r||t.find(a=>a.track===r))return!1;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${r.kind} track ${r.id} ${r.label} on ${o?m.AUXILIARY:m.MAIN} stream`),r.kind===m.AUDIO&&t[0]&&(yield t[0].replaceTrack(r)),r.kind===m.VIDEO&&(!o&&t[1]&&(yield t[1].replaceTrack(r)),o&&t[3]&&(yield t[3].replaceTrack(r))),!0})}setBandwidth(o){return f(this,arguments,function*({bandwidth:e,type:t,videoType:r}){if(this.singlePC){let n={};t===m.AUDIO?n.audio=e:r==="big"?n.bigVideo=e:r==="small"?n.smallVideo=e:n.auxVideo=e,yield this.singlePC.setBandwidth(n)}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info(`send muted state: ${JSON.stringify(this.muteState)}`),this._signalChannel.sendWaitForResponseWithRetry({command:q.UPDATE_MUTE_STAT,responseCommand:B.MUTE_RESULT,data:this.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&E.emit(T.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(e=m.VIDEO){if(this._peerConnection){let t=this._peerConnection.getSenders();if(e===m.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(e===m.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&e===m.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&e===m.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,t){if(e!==0)throw e===dr?(this._log.error(Oe.NOT_SUPPORTED_H264ENCODE),new b({code:S.NOT_SUPPORTED_H264,message:V({key:w.NOT_SUPPORTED_H264ENCODE})})):new b({code:S.UNKNOWN,message:V({key:w.SIGNAL_RESPONSE_FAILED,data:{signalResponse:B.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}))})}};y([Qe(function({localVideoTrack:e}){e==null||e.once("6",this.onVideoEncodeFailed,this)})],tn.prototype,"publish",1),y([Qe(function({localVideoTrack:e}){e==null||e.off("6",this.onVideoEncodeFailed,this)})],tn.prototype,"unpublish",1);var Eu=tn;function Cp(s){return Object.keys(s).filter(i=>s[i])}var xs=class extends Hr{constructor(e){super(k(v({},e),{isUplink:!1}));d(this,"_flag",0);d(this,"isRobot",!1);d(this,"role","anchor");d(this,"remoteAudioTrack");d(this,"remoteVideoTrack");d(this,"remoteAuxiliaryTrack");d(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});d(this,"jitterBufferTimeoutId",-1);this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new Oi(this._room,this),this.remoteVideoTrack=new oi(this._room,this),this.remoteAuxiliaryTrack=new Cs(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 pi(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var t,r,o;e!==this._flag&&(this._flag=e,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(r=this.remoteVideoTrack)==null||r.onFlagChanged(),(o=this.remoteAuxiliaryTrack)==null||o.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===m.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(e){clearTimeout(this.jitterBufferTimeoutId),super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.uninstallEvents(),this.removeDownlink()}installEvents(){this.singlePC&&(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this))}uninstallEvents(){this.singlePC&&(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this))}emitConnectionStateChangedEvent(e){var o,n;let t=this._currentState,r=super.emitConnectionStateChangedEvent(e);return r&&t!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:t,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:t,state:e})),r}onTrack(e){var h,u;let t=e.streams[0],{track:r,receiver:o}=e;if(!t.id.includes(this.tinyId))return;let a=t.id.includes("aux")?"auxiliary":"main";this._log.debug(`ontrack ${a} ${r.kind}`);let c=m.AUDIO;r.kind===m.VIDEO&&(c=a===m.MAIN?m.VIDEO:m.AUXILIARY);let l=this.remoteAudioTrack;c===m.VIDEO?l=this.remoteVideoTrack:c===m.AUXILIARY&&(l=this.remoteAuxiliaryTrack),(h=this.singlePC)==null||h.receiverRemoteTrackMap.set(o,l),(u=this.singlePC)!=null&&u.scriptTransformWorker&&this.initReceiverTransform(o,a,r.kind===m.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(o),l.setInputMediaStreamTrack(r)}createEncodedStreams(e){if(!this.singlePC.insertableStreamsAbortMap.has(e)){let t=e.createEncodedStreams(),r=new AbortController,o={abortController:r,enqueue:n=>{var c,l;let a=(c=this.singlePC)==null?void 0:c.receiverRemoteTrackMap.get(e);return!a||a.kind==="video"&&!((l=this.singlePC)!=null&&l.isUsingH264)?n:a.decodeFrame(n)}};t.readable.pipeThrough(new TransformStream({transform:(n,a)=>{let c=o.enqueue(n);c&&a.enqueue(c)}})).pipeTo(t.writable,r).catch(n=>{n!=="destory"&&this._log.warn(n)}),this.singlePC.addAbortController(e,r)}}initReceiverTransform(e,t,r){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||e.transform||(e.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:r,userId:this.userId,streamType:t}))}subscribe(e,t){return f(this,null,function*(){try{if(this._log.info(`subscribe ${t} ${Cp(e)}`),this.hasSSRC){let r="subscribe_change";Object.values(e).find(o=>o===!0)||(r="unsubscribe"),yield this.sendSubscription(r,e)}else yield this.doSubscribe(e),this.checkTrackEnded(e)}catch(r){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn(`${r.message} ${JSON.stringify(this.muteState)}`),new b({code:S.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):r}})}checkTrackEnded(e){var t,r,o;if((e.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||e.video&&((r=this.remoteVideoTrack.mediaTrack)==null?void 0:r.readyState)==="ended"||e.auxiliary&&((o=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:o.readState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),Ot&&kt<92)return;this.singlePC.startReconnection()}}unsubscribe(r){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 o=v({},this.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:o.audio=!1;break;case 4:o.video=!1;break;case 8:o.smallVideo=!1;break;case 2:o.auxiliary=!1;break;default:break}});let n="subscribe_change";Object.values(o).find(c=>c===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${Cp(o)}]`),n==="unsubscribe"&&((a=this.singlePC)==null||a.removeDownlinkQueue.add(this.tinyId)),yield this.sendSubscription(n,o),n==="unsubscribe"&&(yield this.removeDownlink())})}sendSubscription(e,t=this.subscribeState){let r={srcTinyId:this.tinyId,srcUserId:this.userId},o=q.UNSUBSCRIBE,n=B.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(r={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,srcTinyId:this.tinyId},o=q.SUBSCRIBE_CHANGE,n=B.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:o,data:r,responseCommand:n,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let c=new b({code:a.code,message:V({key:w.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 r={audioSsrc:Fr(),bigVideoSsrc:Fr(),bigVideoRtxSsrc:Fr(),auxVideoSsrc:Fr(),auxVideoRtxSsrc:Fr()},{audioSsrc:o,bigVideoSsrc:n,bigVideoRtxSsrc:a,auxVideoSsrc:c,auxVideoRtxSsrc:l}=r;this.ssrc={audio:o,video:n,videoRtx:a,auxiliary:c,auxiliaryRtx:l},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});try{let h=yield this._signalChannel.sendWaitForResponseWithRetry({command:q.SPC_SUBSCRIBE,responseCommand:B.SPC_SUBSCRIBE_RESULT,data:{srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:!1,ssrc:r},retries:3,retryTimeout:0});if(h.data.code!==0)throw new b({code:h.data.code,message:h.data.message})}catch(h){throw yield this.removeDownlink(),h}return}this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc})}finally{let r=this._room.scheduleResult.config;Kn&&(r!=null&&r.jitterDelay||r!=null&&r.jitterDelayAux)&&this.setJitterBufferDelay({mainDelay:r.jitterDelay,auxDelay:r.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&&e.jitterDelay||e!=null&&e.jitterDelayAux)&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)})}setJitterBufferDelay({mainDelay:e,auxDelay:t}){if(!Kn||!this.singlePC||!this._peerConnection||gi(e)&&gi(t))return Promise.resolve();this._log.info(`set jitterBuffer main: ${e} aux: ${t}`);let r=this.singlePC.getReceiversByUserId(this.userId);return Y(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),Y(t)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=t,gi(e)&&(this.remoteAudioTrack.jitterBufferDelay=t)),new Promise(o=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:o})})}doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:o}){try{if(e===0&&t===0)return r.forEach(a=>a.jitterBufferTarget=0),o();if(r.forEach(a=>{var u;let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack||gi(e)&&a.track===this.remoteAudioTrack.outMediaTrack;if(c&&gi(t)||!c&&gi(e))return;let l=c?t||0:e,h=(a.jitterBufferTarget||0)+100;h>l||(a.jitterBufferTarget=h,this._log.debug(`set ${c?"aux ":""}${(u=a==null?void 0:a.track)==null?void 0:u.kind} jitterBuffer delay ${h} -> ${l}`))}),!r.find(a=>{let c=a.track===this.remoteAuxiliaryTrack.outMediaTrack?t||0:e;return a.jitterBufferTarget<c}))return this._log.info(`set jitterBuffer main: ${e} aux: ${t} done`),o();this.jitterBufferTimeoutId=setTimeout(()=>{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:t,receivers:r,resolve:o})},1e3)}catch(n){this._log.warn(`set jitterBuffer delay error: ${n}`),clearTimeout(this.jitterBufferTimeoutId),o()}}get audioReceiver(){var e;return((e=this.singlePC)==null?void 0:e.getReceiversByUserId(this.userId)[0])||null}};y([ii(),J(e=>function(...t){return new Promise((r,o)=>{let n=a=>{this.off("closed",n),o(new b({code:S.API_CALL_ABORTED,message:V({key:w.CONNECTION_ABORTED,data:a})}))};this.on("closed",n),e.apply(this,t).then(r,o).finally(()=>{this.off("closed",n)})})})],xs.prototype,"subscribe",1),y([ii()],xs.prototype,"unsubscribe",1),y([vi(()=>"jitter")],xs.prototype,"setJitterBufferDelay",1);var Rp=xs;function yp(){return J(s=>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;E.emit("61",{room:this});let e=s.apply(this,i);return i.forEach(t=>t.publish(this,e)),e})})}function bp(){return J(s=>function(...i){let e=s.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var Np=Pe(je());function HT(){return Math.floor(Math.random()*16383)}var md=class md extends Np.EventEmitter{constructor(e,t){super();this.room=e;this.signalChannel=t;d(this,"log");d(this,"cmdIdSeqMap",new Map);d(this,"messageMap",new Map);this.log=C.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(B.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",r=>{[...this.messageMap.keys()].forEach(o=>{o.split("_").slice(0,-1).join("_")===r&&this.messageMap.delete(o)})})}send({cmdId:e,data:t}){let r=this.cmdIdSeqMap.get(e)||HT(),o={cmdId:e,msg:btoa(String.fromCharCode(...new Uint8Array(t))),ordered:!0,reliable:!0,streamSeq:r};this.cmdIdSeqMap.set(e,r+1),this.signalChannel.send(q.SEND_CUSTOM_MSG,o),this.log.debug(`send custom msg: ${JSON.stringify(o)}`)}onReceiveMsg(e){let{data:t}=e.data,r=this.room.tinyIdToUserIdMap.get(t.srcTinyId);if(r){let o={userId:r,cmdId:t.cmdId,seq:t.streamSeq,data:Uint8Array.from(atob(t.msg),n=>n.charCodeAt(0)).buffer};if(t.ordered){let n=`${r}_${o.cmdId}`,a=this.messageMap.get(n);if(!a||a.lastSeq===0)a||(a={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(n,a),setTimeout(()=>this.emitMessage(o,!0),100)),a.cachedMessageMap.set(o.seq,{message:o});else if(Math.abs(a.lastSeq-o.seq)>md.SEQ_INTERVAL)this.messageMap.set(n,{lastSeq:o.seq,cachedMessageMap:new Map}),this.emitMessage(o);else if(o.seq>a.lastSeq){if(o.seq===a.lastSeq+1)this.emitMessage(o);else if(!a.cachedMessageMap.has(o.seq)){let c=setTimeout(()=>this.emitMessage(o,!0),5e3);a.cachedMessageMap.set(o.seq,{message:o,timeoutId:c})}}else this.log.debug(`drop message ${o.userId}-${o.cmdId}-${o.seq}`)}else this.emit("message",o)}else{this.log.warn(`receive msg from unknown user, wait peer-join tinyId: ${t.srcTinyId}`);let o=n=>{n.tinyId===t.srcTinyId&&(this.room.off("peer-join",o),this.onReceiveMsg(e))};this.room.on("peer-join",o),fi(2e3).then(()=>this.room.off("peer-join",o))}}emitMessage(e,t=!1){var a;let r=this.messageMap.get(`${e.userId}_${e.cmdId}`),o=e;if(r){if(t){let c=[...r.cachedMessageMap.values()].sort((l,h)=>l.message.seq-h.message.seq);c[0]&&(o=c[0].message)}r.lastSeq!==0&&o.seq-r.lastSeq>1&&this.log.debug(`msg lost userId: ${o.userId} seq: ${r.lastSeq} -> ${o.seq}`),r.lastSeq=o.seq,clearTimeout((a=r.cachedMessageMap.get(o.seq))==null?void 0:a.timeoutId),r.cachedMessageMap.delete(o.seq)}this.log.debug(`receive custom msg: ${JSON.stringify(o)}`),this.emit("message",o);let n=r==null?void 0:r.cachedMessageMap.get(o.seq+1);n&&this.emitMessage(n.message)}};d(md,"SEQ_INTERVAL",300);var hd=md;var{isString:vp,isUndefined:ws,getNetworkType:$T,isEmpty:rn}=nt,Bt=class extends ld{constructor(e){super(e);d(this,"_businessInfo");d(this,"userManager");d(this,"_version");d(this,"_heartbeat",-1);d(this,"_lastHeartBeatTime",-1);d(this,"_stats");d(this,"_joinTimeout",-1);d(this,"_firstPublishedList",null);d(this,"_joinReject",null);d(this,"_isRelayChanged",!1);d(this,"sdpSemantics");d(this,"signalChannel",null);d(this,"uplinkConnection",null);d(this,"singlePC",null);d(this,"enableSPC",hs);d(this,"_changeBigSmallRecords",new Map);d(this,"networkQuality");d(this,"_iceTransportPolicy");d(this,"forceRelay",!1);d(this,"_turnServers",[]);d(this,"_syncUserListInterval",-1);d(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160});d(this,"enableSEI",!1);d(this,"_enableAudioVolumeEvaluation",!1);d(this,"_audioVolumeIntervalId",0);d(this,"_enableMultiAuxStream",!1);d(this,"_pureAudioPushMode",!1);d(this,"_customMessageManager");d(this,"preferHW",!1);d(this,"healthDetector");d(this,"_updateAudioLevelTaskId",-1);this._stats=new Ko(this,this._log),this.userManager=new xa(this.userId,this._log),this._version=Re,this.sdpSemantics=Gr,ws(e.sdpSemantics)?Yt.isUnifiedPlanDefault()&&(this.sdpSemantics=Gi):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${$T()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=ws(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&hs,!ws(e.enableSPC)&&hs&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new pp(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,r){return f(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",o=>{this.emit("peer-join",o)}),this.userManager.on("2",o=>{this.closeDownLinkConnection(o,"remote user exitRoom"),this.emit("peer-leave",o)}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",n=>{var o=Cu(n,[]);E.emit(T.REMOTE_PUBLISH_STATE_CHANGED,v({room:this},o)),this.emit("remote-publish-state-changed",v({},o))}),this.joinParams=e,new Promise((o,n)=>f(this,null,function*(){var a,c;this._joinReject=n;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(h){if(h instanceof b&&h.code===S.SPC_INITIALIZED_FAILED)(a=this.signalChannel)==null||a.destroy(),yield this.initialize();else return n(h)}let l=L();yield this.doJoin(e,(c=this.singlePC)==null?void 0:c.clientAbility),N.addSuccessEvent({key:521708,cost:L()-l}),o(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(l){N.addFailedEvent({key:521708,error:l}),n(l)}this._joinReject=null}))})}initSinglePC(){return f(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new Vt({signalChannel:this.signalChannel,room:this,enableCustomMessage:!1}),this.singlePC.on("sei-message",e=>this.emit("sei-message",e)),this.singlePC.on("dump",e=>this.emit("dump",e)),this.singlePC.once("error",()=>this.fallbackToMPC());try{return yield this.singlePC.initialize()}catch(e){throw this.fallbackToMPC(),new b({code:S.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((r,o)=>f(this,null,function*(){var c,l,h;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(Ee.SETUP_FAILED,u=>{this.clearJoinTimeout(),E.emit(T.JOIN_SIGNAL_CONNECTION_END,{room:this,error:u}),o(u)}),me((l=(c=this.scheduleResult)==null?void 0:c.config)==null?void 0:l.singlePC)&&hs&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2);let n={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:e.role,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:Kd(),netType:ur(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0};this._log.debug(`join room signal data: ${JSON.stringify(n)}`);let a=5e3;(h=this.scheduleResult.config)!=null&&h.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(a=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{o(new b({code:S.JOIN_ROOM_FAILED,message:V({key:w.JOIN_ROOM_TIMEOUT})}))},a),E.emit(T.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?q.SPC_JOIN_ROOM:q.JOIN_ROOM,n),this.signalChannel.once(B.JOIN_ROOM_RESULT,u=>{this.clearJoinTimeout();let{code:p,message:_,data:I,tinyId:R}=u.data;E.emit(T.JOIN_RECEIVED_CMD_RES,{room:this,code:p}),p===0?(this._log.info("Join room success, start heartbeat"),R&&(this.tinyId=R),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=I.publishers,this.singlePC&&this.singlePC.connect(k(v({},I.ability),{useVp8:I.ability.useVp8||!!e.useVp8})).catch(()=>{}),r()):(this._log.error(`Join room failed result: ${p} error: ${_}`),o(new b({code:S.JOIN_ROOM_FAILED,extraCode:p,message:V({key:w.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,r=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,r.push(this.initSinglePC().then(o=>(t=o,o)))),this.signalChannel&&(this.signalChannel.race=e,this.signalChannel.close(),r.push(this.signalChannel.connect())),yield Promise.all(r),yield this.doJoin(k(v({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),t),this._log.warn("reJoin success"),ee.logSuccessEvent({userId:this.userId,eventType:Ke.REJOIN}),this.singlePC){let o=n=>{var a;n.state==="CONNECTED"&&((a=this.singlePC)==null||a.off(ai.CONNECTION_STATE_CHANGED,o),this.uplinkConnection instanceof Eu&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(c=>{c.installEvents(),c.onSinglePCReconnected()}))};this.singlePC.on(ai.CONNECTION_STATE_CHANGED,o),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof Yo&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(t){this._log.warn(`reJoin fail ${t}`),this.reset(),ee.logFailedEvent({userId:this.userId,eventType:Ke.REJOIN,error:t}),this.emit("error",new b({code:S.JOIN_ROOM_FAILED,message:V({key:w.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}})}initialize(){return f(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),r=this.signalChannel||Hm(this.userId),o=!!(r&&r.isConnected&&r.keepAlive),n;return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(n=this.scheduleResult.domains[0]),this._log.info(`${o?"reuse":"setup"} signal channel`),o?(r.url=e,r.backupUrl=t,r.room=this,this.signalChannel=r):(this.signalChannel=new Os({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,race:this.enableSPC&&!this.proxy_ws,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?n:void 0}),this._customMessageManager=new hd(this,this.signalChannel),this._customMessageManager.on("message",a=>{this.emit("custom-message",a)})),this.networkQuality||(this.networkQuality=new Ps({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(Ps.EVENT_NETWORK_QUALITY,a=>{var c;this.emit("network-quality",a),(c=this.singlePC)==null||c.detectTCPAndUDP(a)})),Fe(this,this.signalChannel).add(Ee.CONNECTION_STATE_CHANGED,a=>{E.emit(T.SIGNAL_CONNECTION_STATE_CHANGED,v({room:this},a)),this.emit("signal-connection-state-changed",a)}).add(Ee.RECONNECT_FAILED,a=>{this.reset(),this.emit("error",a)}).add(B.PEER_JOIN,a=>{let{srcTinyId:c,userId:l,role:h}=a.data.data;this.userManager.addUser({userId:l,tinyId:c,role:h})}).add(B.PEER_LEAVE,a=>{let{userId:c,reason:l=0}=a.data.data;this.userManager.deleteUser(c,l)}).add(B.UPDATE_REMOTE_MUTE_STAT,a=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(a.data)}).add(B.CLIENT_BANNED,a=>{let c=a.data.data,{reason:l}=c;if(ee.uploadEvent({log:`stat-banned:${l}`,userId:this.userId}),l==="user_time_out"){this._log.warn(`${l} last heart beat time: ${this._lastHeartBeatTime} interval: ${Date.now()-this._lastHeartBeatTime}, visibility: ${document.visibilityState}`),this.reJoin();return}this._log[l==="kick"?"error":"info"](`user was banned because of [${l}]`),this.reset(),this.emit("banned",{reason:l})}),this.signalChannel.once(Ee.SETUP_SUCCESS,a=>{this.tinyId=a.signalInfo.tinyId,E.emit(T.JOIN_SIGNAL_CONNECTION_END,{room:this})}),E.emit(T.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),o&&E.emit(T.JOIN_SIGNAL_CONNECTION_END,{room:this}),o})}setSignalChannel(e){this.signalChannel=e,e||Se(this)}leave(){return f(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),E.emit(T.LEAVE_SEND_CMD,{room:this}),(e=this.signalChannel)==null||e.send(q.LEAVE_ROOM)})}clearNetworkQuality(){this.networkQuality&&(this.networkQuality.stop(),delete this.networkQuality)}closeConnections(){this.remotePublishedUserMap.forEach(e=>{this.closeDownLinkConnection(e.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=re.run("ric",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 n;let e=this.badCaseDetector.getMonitorFreeze(),t=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});this.badCaseDetector.resetMonitor();let r=(n=this.signalChannel)!=null&&n.isConnected?hm(this.userId):[],o=k(v({str_sdk_version:Hs,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:r,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},t),{msg_device_info:v({uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:ur()},t.msg_device_info)});if(this.heartbeatReport=o,E.emit(T.HEARTBEAT_REPORT,{room:this,report:o}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(q.ON_QUALITY_REPORT,o);let a=Date.now();this._lastHeartBeatTime>0&&a-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${a-this._lastHeartBeatTime}`),this._lastHeartBeatTime=a,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",k(v({},o),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(e){if(!this.isJoined)return;let t=e.data.userList.filter(r=>r.flag!==Cd).map(({userId:r,srcTinyId:o,flag:n})=>{r===this.userId&&this.uplinkConnection&&(this.uplinkConnection.flag=n);let a=this.remotePublishedUserMap.get(r);return a&&this.checkSubscribeBigSmallVideo(a),{userId:r,tinyId:o,flag:n}});e.data.mixRobotList.forEach(({userId:r,srcTinyId:o,flag:n,mixUserList:a})=>{t.unshift({userId:r,tinyId:o,flag:n,isRobot:!0,mixUserList:a})}),E.emit(T.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 Yo&&(this.uplinkConnection=null)),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection({userId:e,tinyId:t,flag:r,isRobot:o}){let n=new(this.singlePC?Rp:du)({userId:e,tinyId:t,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:r,isRobot:o});this.userManager.addRemotePublishedUser(n),this.installDownlinkEvents(n,e),this.emit("remote-published",n)}closeDownLinkConnection(e,t="remote user unpublished"){let r=this.remotePublishedUserMap.get(e);r&&(r.close(t),this.emit("remote-unpublished",r))}installDownlinkEvents(e,t){e.on("error",r=>{let o=r.getCode();o!==S.ICE_TRANSPORT_ERROR&&(o===S.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",r))}),e.on("connection-state-changed",r=>{this.emit("media-connection-state-changed",k(v({},r),{userId:e.userId}))}),e.on("firewall-restriction",()=>{this.emit("firewall-restriction")})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=re.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){re.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then(e=>{this.userManager.setUserList(e)}).catch(e=>{this._log.debug(`sync user list failed: ${e}`)})}getUserList(){var e;return(e=this.signalChannel)!=null&&e.isConnected?this.signalChannel.sendWaitForResponse({command:q.GET_USER_LIST,responseCommand:B.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(({data:t})=>{let{code:r,message:o}=t;if(r===0)return(t.data&&t.data.userList||[]).map(({userId:a,srcTinyId:c,role:l})=>({userId:a,tinyId:c,role:l}));throw V({key:w.SIGNAL_RESPONSE_FAILED,data:{signalResponse:B.USER_LIST_RES,code:r,message:o}})}):Promise.reject("not connected")}getAllConnections(){let e=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&e.push(this.uplinkConnection),e}isRelayMaybeFailed(){if(this.signalChannel&&!this.signalChannel.isOnline||!iu)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let e=this.getAllConnections();if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(e[t].getReconnectionCount()<6)return!1;return!0}checkConnectionsToReconnect(){var e;this.singlePC?((e=this.singlePC.getPeerConnection())==null?void 0:e.connectionState)===ce.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(r=>{if(r instanceof Ye&&!r.getIsReconnecting()){let o=r.getPeerConnection();o&&o.connectionState===ce.CLOSED&&(this._log.warn(`[${r.getUserId()}] pc is closed but not reconnect`),r.startReconnection())}})}fallbackToMPC(){return f(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),ee.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 Yo({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),t.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localMainAudioTrack,localVideoTrack:t.localMainVideoTrack,isAuxiliary:!1})),t.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localAuxAudioTrack,localVideoTrack:t.localAuxVideoTrack,isAuxiliary:!0})),t.close()}for(let t of[...this.remotePublishedUserMap.values()]){let r=new du({userId:t.userId,tinyId:t.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:t.flag,remoteAudioTrack:t.remoteAudioTrack,remoteVideoTrack:t.remoteVideoTrack,remoteAuxiliaryTrack:t.remoteAuxiliaryTrack});this.installDownlinkEvents(r,t.userId),this.remotePublishedUserMap.set(t.userId,r),t.isMainStreamSubscribed&&(yield r.subscribe(t.subscribeState,"main")),t.isAuxStreamSubscribed&&(yield r.subscribe(t.subscribeState,"auxiliary"))}})}destroy(){this.isDestroyed||(this.signalChannel&&(this._log.info("destroying SignalChannel"),this.signalChannel.close(),this.signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new b({code:S.INVALID_OPERATION,message:V({key:w.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),re.clearTask(this._audioVolumeIntervalId))}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:q.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:B.SWITCH_ROLE_RES,retries:1};return this._log.info(`switchRole signal data: ${JSON.stringify(t.data)}`),this.signalChannel.sendWaitForResponseWithRetry(t).then(r=>{let{code:o,message:n}=r.data;if(o!==0)throw new b({code:S.SWITCH_ROLE_FAILED,message:V({key:w.SWITCH_ROLE_FAILED,data:{message:n,code:o}})});this.role=e}).catch(r=>{throw r instanceof b&&r.getCode()===S.API_CALL_TIMEOUT&&(r=new b({code:S.SWITCH_ROLE_FAILED,message:V({key:w.SWITCH_ROLE_TIMEOUT})})),this._log.error(r),r})}publish(...e){return f(this,null,function*(){let t={},r={};e.forEach(c=>{c instanceof ht&&(c instanceof si?r.audio=c:t.audio=c),c instanceof $e&&(c instanceof st&&c.mediaType===2?r.video=c:t.video=c)});let o=rn(t),n=rn(r);(!o||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new Eu({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new Yo({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",c=>{this.emit("media-connection-state-changed",k(v({},c),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",c=>{let l=c.getCode();l!==S.ICE_TRANSPORT_ERROR&&(l===S.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",c))}));let a=e.map(c=>c.kind).join(",");o||(this._log.info(`publish() => main ${a}`),yield this.uplinkConnection.publish({localAudioTrack:t.audio,localVideoTrack:t.video,isAuxiliary:!1}),this._log.info("main is published")),n||(this._log.info(`publish() => aux ${a}`),yield this.uplinkConnection.publish({localAudioTrack:r.audio,localVideoTrack:r.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={},r={};e.forEach(o=>{!o.mediaTrack||!o.isPublished||(o instanceof ht&&(o instanceof si?r.audio=o:t.audio=o),o instanceof $e&&(o instanceof st&&o.mediaType===2?r.video=o:t.video=o))});try{let o=e.map(n=>n.kind).join(",");rn(t)||(this._log.info(`unpublish() => main ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:t.audio,localVideoTrack:t.video})),rn(r)||(this._log.info(`unpublish() => aux ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:r.audio,localVideoTrack:r.video}))}catch(o){}this.localTracks.size===0&&this.closeUplink("you unpublished")})}addTrack(e){if(!this.uplinkConnection||!e.mediaTrack)return Promise.resolve();let t=this.uplinkConnection.addTrack(e);return e.publish(this,t),t}removeTrack(e){return!this.uplinkConnection||!e.mediaTrack?Promise.resolve():this.uplinkConnection.removeTrack(e).then(t=>(e.unpublish(),t))}replaceTrack(e){return!this.uplinkConnection||!e.mediaTrack||!Cc()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{t&&E.emit(T.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:m.VIDEO,videoType:m.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(...e){return f(this,null,function*(){if(e=e.filter(n=>!n.isSubscribed),e.length===0)return;let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";try{let n=v({},r.subscribeState);e.forEach(c=>{switch(c.mediaType){case 1:n.audio=!0;break;case 4:n.video=!0;break;case 8:n.smallVideo=!0;break;case 2:n.auxiliary=!0;break}});let a=this._changeBigSmallRecords.get(t);a&&a.options.smallVideo&&r.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),E.emit(T.SUBSCRIBE_START,{room:this,streamType:o,remotePublishedUser:r,subscribeState:n}),this._log.info(`subscribe() => ${t} ${o} [${id(n)}] prev: [${id(r.subscribeState)}]`),yield r.subscribe(n,o),this._log.info(`subscribe ${t} ${o} done`);for(let c of e)c.mediaTrack||(yield c.waitHasMediaTrack());E.emit(T.SUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:r})}catch(n){let a=n instanceof b?n.getCode():S.UNKNOWN,c=n;throw n instanceof b?a===S.REMOTE_STREAM_NOT_EXIST&&(c=new b({code:S.API_CALL_ABORTED,message:V({key:w.API_CALL_ABORTED,data:{message:n.message,userId:t,streamType:o}})}),this._log.warn(c)):(c=new b({code:a,message:V({key:w.SUBSCRIBE_FAILED,data:{message:n.message,userId:t,streamType:o}})}),this._log.error(c)),c}})}unsubscribe(...e){return f(this,null,function*(){let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";this._log.info(`unsubscribe() => ${t} ${o}`);try{yield r.unsubscribe({remoteTracks:e,streamType:o})}catch(n){this._log.warn(`unsubscribe() => failed ${n}`)}e.forEach(n=>{n.unsubscribe(),n.mediaType===8&&n.setMediaType(4)}),E.emit(T.UNSUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:r})})}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)),E.emit(T.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&re.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=re.run("intervalInWorker",()=>{var o;Ar.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];(o=this.remotePublishedUserMap)==null||o.forEach(n=>{if(n.muteState.hasAudio){!Ar.isRunning&&n.muteState.audioAvailable&&n.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(n):n.remoteAudioTrack.volume=0;let a=Math.floor(n.remoteAudioTrack.getAudioLevel()*100);r.push({userId:n.userId,volume:a})}}),this.emit("audio-volume",r)},{delay:e,backgroundTask:t})}updateAudioLevelFromSenderStat(e,t){return f(this,null,function*(){var n;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||this._updateAudioLevelTaskId!==-1)return;let r=(n=this.uplinkConnection.getPeerConnection())==null?void 0:n.getSenders()[0];if(!r)return;let o=Math.max(e,500);this._log.warn(`updateAudioLevelFromSenderStat ${o}`),this._updateAudioLevelTaskId=re.run("intervalInWorker",()=>f(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack){this.stopUpdateAudioLevelFromSenderStat();return}let a=yield r.getStats();if(this._updateAudioLevelTaskId<0)return;let c=this.uplinkConnection.localMainAudioTrack;a.forEach(l=>{l.type==="media-source"&&l.audioLevel&&(c.volume=l.audioLevel)})}),{delay:o,backgroundTask:t})})}stopUpdateAudioLevelFromSenderStat(){var e;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),re.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,(e=this.uplinkConnection)!=null&&e.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(e){var o;let{audioReceiver:t}=e;if(!Rc||!t)return;let r=(o=t.getSynchronizationSources()[0])==null?void 0:o.audioLevel;Y(r)?e.remoteAudioTrack.volume=Math.min(r*2,1):t.getStats().then(n=>{n.forEach(a=>{a.type==="inbound-rtp"&&Y(a.audioLevel)&&(e.remoteAudioTrack.volume=a.audioLevel)})})}getLocalAudioStats(){return f(this,null,function*(){var t;let e={};return e[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},(t=this.uplinkConnection)!=null&&t.localMainAudioTrack&&(e[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),e})}getLocalVideoStats(){return f(this,null,function*(){var t,r;let e={};return e[this.userId]=((r=(t=this.uplinkConnection)==null?void 0:t.localMainVideoTrack)==null?void 0:r.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},e})}getTransportStats(){return 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 r=yield this._stats.getReceiverStats(t);e.downlinksRTT[r.userId]=r.rtt}return e})}getRemoteVideoStats(e){return f(this,null,function*(){let t={};for(let[r,o]of this.remotePublishedUserMap)e==="main"&&o.muteState.hasVideo&&(t[r]=o.remoteVideoTrack.stat),e==="auxiliary"&&o.muteState.hasAuxiliary&&(t[r]=o.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return f(this,null,function*(){let e={};for(let[t,r]of this.remotePublishedUserMap)r.muteState.hasAudio&&(e[t]=r.remoteAudioTrack.stat);return e})}setTurnServer(e,t){this._log.info(`set turn server: ${JSON.stringify(e)} ${t||""}`);let r=[];Array.isArray(e)?e.forEach(o=>r.push(nt.getTurnServer(o))):nt.isPlainObject(e)&&r.push(nt.getTurnServer(e)),this._turnServers=r,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:q.START_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:B.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:q.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:B.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"})}sendStartPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?q.START_PUBLISH_TENCENT_CDN:q.START_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?B.START_PUBLISH_TENCENT_CDN_RES:B.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"})}sendStopPublishCDN(e,t=!0){return this.signalChannel.sendWaitForResponse({command:t?q.STOP_PUBLISH_TENCENT_CDN:q.STOP_PUBLISH_GIVEN_CDN,data:e,timeout:5e3,responseCommand:t?B.STOP_PUBLISH_TENCENT_CDN_RES:B.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:q.START_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:B.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:q.UPDATE_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:B.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:q.STOP_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:B.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"})}sendAbilityStatus(e){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:q.ABILITY_STATUS_REPORT,data:e,timeout:5e3,responseCommand:B.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(r=>{})}getIceServers(){return this._turnServers.length===0&&this.scheduleResult.iceServers?this.scheduleResult.iceServers:this._turnServers}getIceTransportPolicy(){return this.forceRelay?"relay":this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=nt.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:r,muteState:{hasSmall:o,hasVideo:n}}=e;if(!o&&!n||!t.video&&!t.smallVideo)return;let a=this._changeBigSmallRecords.get(r);if(!a||a.isSubscribing||a.reSubscribeCount<=0)return;let{options:c,reSubscribeCount:l}=a;if(c.video&&t.video||c.smallVideo&&t.smallVideo&&o)return;let h={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:c.video,smallVideo:c.smallVideo};try{if(!o&&h.smallVideo&&(h.video=!0,h.smallVideo=!1),h.smallVideo===t.smallVideo&&h.video===t.video)return;a.isSubscribing=!0,a.reSubscribeCount=l-1,yield e.subscribe(h,"main"),e.remoteVideoTrack.setMediaType(h.smallVideo?8:4),this._log.info(`change [${r}] to ${h.smallVideo?"small":"big"} video successfully. count ${Wr-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=Wr}catch(u){this._log.info(`change [${r}] to ${h.smallVideo?"small":"big"} video failed. count ${Wr-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount===0&&this._changeBigSmallRecords.delete(r)}})}changeType(e,t){let o={options:{video:!e,smallVideo:e},isSubscribing:!1,reSubscribeCount:Wr};this._changeBigSmallRecords.set(t.userId,o),this._log.info(`set [${t.userId}] video prefer type: ${e?"small":"big"}`);let n=this.remotePublishedUserMap.get(t.userId);n&&this.checkSubscribeBigSmallVideo(n)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(e){this._businessInfo=e.businessInfo;let t={};if(vp(e.businessInfo)&&(t=JSON.parse(e.businessInfo)),!ws(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new b({code:S.INVALID_PARAMETER,message:V({key:w.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(!ws(e.userDefineRecordId)){let r=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(r)===null)throw new b({code:S.INVALID_PARAMETER,message:V({key:w.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!ws(e.userDefinePushArgs))if(vp(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:S.INVALID_PARAMETER,message:V({key:w.INVALID_USER_DEFINE_PUSH_ARGS})});rn(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){return f(this,null,function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&Ri)return this.singlePC.enableInsertableStreams=!0,yield this.singlePC.waitForPeerConnectionConnected(),yield this.singlePC.startReconnection()})}sendSignalMessage(e){var t;return this.signalChannel?(t=this.signalChannel)==null?void 0:t.sendWaitForResponseWithRetry(e):Promise.reject(new b({code:S.INVALID_OPERATION,message:"not join"}))}get enableCodecPipeline(){return this.videoManager.encodePipeline.length>0||this.videoManager.decodePipeline.length>0||this.audioManager.encodePipeline.length>0||this.audioManager.decodePipeline.length>0}get scriptTransformWorker(){var e;return(e=this.singlePC)==null?void 0:e.scriptTransformWorker}};y([le(["left",Q.INIT],"joined"),tt({settings:{retries:1,timeout:0},onRetrying(e){this._log.warn(`join retry ${e}`)},onRetryFailed(e){this._log.error("join failed",e)},onError(e,t){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),wt(!0),this.reset(),t()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),t()):(this.reset(),t())}}),wm()],Bt.prototype,"join",1),y([le("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),Um(),fa("leave room"),Oo({fnName:"publish",validateArgs:!1}),Oo({fnName:"unsubscribe",validateArgs:!1})],Bt.prototype,"leave",1),y([ii(),yp(),tt({settings:{retries:ui,timeout:e=>yt(e)},onError(e,t,r){var o;(o=e.message)!=null&&o.includes("timeout")?(this._log.warn("publish timeout"),t()):(this._log.error(`publish failed: ${e}`),r(e),E.emit(T.PUBLISH_FAILED,{room:this}))}})],Bt.prototype,"publish",1),y([Oo({fnName:"publish"}),Kh("api-call"),ii(),bp(),Qe(function(){var e,t;this.localTracks.size===0&&Ki()&&((t=(e=this.singlePC)==null?void 0:e.getPeerConnection())==null||t.getSenders().forEach(r=>r.track&&r.replaceTrack(null)))})],Bt.prototype,"unpublish",1),y([ha(e=>{if(e.code!==S.API_CALL_ABORTED)throw e}),vi(e=>e.userId)],Bt.prototype,"replaceTrack",1),y([vi((...e)=>e[0].userId),Ta(),Vm(),tt({settings:{retries:ui,timeout:e=>yt(e)},onError(e,t,r,o){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error(`subscribe failed: ${e}`),r(e),E.emit(T.SUBSCRIBE_FAILED,{room:this,remoteTracks:o}))}})],Bt.prototype,"subscribe",1),y([Oo({fnName:"subscribe",callback(...e){this.singlePC||e.forEach(t=>{let r=this.remotePublishedUserMap.get(t.userId);r&&!r.isMainStreamSubscribed&&!r.isAuxStreamSubscribed&&r.close("you unsubscribed")})}}),vi((...e)=>e[0].userId)],Bt.prototype,"unsubscribe",1);Qo.create=Qo._create.bind(Qo,Bt);var r1=Qo;export{r1 as default};
|