trtc-sdk-v5 5.10.2-beta.2 → 5.10.2-wasm.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/av_processing.wasm +0 -0
- package/assets/debug-dialog.js +2 -2
- package/assets/worker.js +17 -0
- package/index.d.ts +23 -6
- package/package.json +4 -6
- package/plugins/cdn-streaming/package.json +1 -1
- package/plugins/cross-room/package.json +1 -1
- package/plugins/custom-encryption/package.json +1 -1
- package/plugins/device-detector/package.json +1 -1
- package/plugins/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/plugins/voice-changer/package.json +1 -1
- package/trtc.esm.js +64 -41
- package/trtc.js +1 -1
package/trtc.esm.js
CHANGED
|
@@ -1,16 +1,14 @@
|
|
|
1
|
-
var qp=Object.create;var Vs=Object.defineProperty,Xp=Object.defineProperties,bu=Object.getOwnPropertyDescriptor,zp=Object.getOwnPropertyDescriptors,Qp=Object.getOwnPropertyNames,nn=Object.getOwnPropertySymbols,Nu=Object.getPrototypeOf,Ec=Object.prototype.hasOwnProperty,vu=Object.prototype.propertyIsEnumerable,Yp=Reflect.get;var Bs=Math.pow,Tc=(s,i,e)=>i in s?Vs(s,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[i]=e,v=(s,i)=>{for(var e in i||(i={}))Ec.call(i,e)&&Tc(s,e,i[e]);if(nn)for(var e of nn(i))vu.call(i,e)&&Tc(s,e,i[e]);return s},L=(s,i)=>Xp(s,zp(i));var Du=(s,i)=>{var e={};for(var t in s)Ec.call(s,t)&&i.indexOf(t)<0&&(e[t]=s[t]);if(s!=null&&nn)for(var t of nn(s))i.indexOf(t)<0&&vu.call(s,t)&&(e[t]=s[t]);return e};var hi=(s,i)=>()=>(i||s((i={exports:{}}).exports,i),i.exports),mi=(s,i)=>{for(var e in i)Vs(s,e,{get:i[e],enumerable:!0})},Kp=(s,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of Qp(i))!Ec.call(s,r)&&r!==e&&Vs(s,r,{get:()=>i[r],enumerable:!(t=bu(i,r))||t.enumerable});return s};var Be=(s,i,e)=>(e=s!=null?qp(Nu(s)):{},Kp(i||!s||!s.__esModule?Vs(e,"default",{value:s,enumerable:!0}):e,s));var y=(s,i,e,t)=>{for(var r=t>1?void 0:t?bu(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&&Vs(i,e,r),r};var c=(s,i,e)=>Tc(s,typeof i!="symbol"?i+"":i,e);var Fe=(s,i,e)=>Yp(Nu(s),e,i);var p=(s,i,e)=>new Promise((t,r)=>{var o=d=>{try{a(e.next(d))}catch(l){r(l)}},n=d=>{try{a(e.throw(d))}catch(l){r(l)}},a=d=>d.done?t(d.value):Promise.resolve(d.value).then(o,n);a((e=e.apply(s,i)).next())});var ze=hi((tE,Sc)=>{"use strict";var Zp=Object.prototype.hasOwnProperty,Xe="~";function Fs(){}Object.create&&(Fs.prototype=Object.create(null),new Fs().__proto__||(Xe=!1));function ef(s,i,e){this.fn=s,this.context=i,this.once=e||!1}function Ou(s,i,e,t,r){if(typeof e!="function")throw new TypeError("The listener must be a function");var o=new ef(e,t||s,r),n=Xe?Xe+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 an(s,i){--s._eventsCount===0?s._events=new Fs:delete s._events[i]}function He(){this._events=new Fs,this._eventsCount=0}He.prototype.eventNames=function(){var i=[],e,t;if(this._eventsCount===0)return i;for(t in e=this._events)Zp.call(e,t)&&i.push(Xe?t.slice(1):t);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i};He.prototype.listeners=function(i){var e=Xe?Xe+i:i,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var r=0,o=t.length,n=new Array(o);r<o;r++)n[r]=t[r].fn;return n};He.prototype.listenerCount=function(i){var e=Xe?Xe+i:i,t=this._events[e];return t?t.fn?1:t.length:0};He.prototype.emit=function(i,e,t,r,o,n){var a=Xe?Xe+i:i;if(!this._events[a])return!1;var d=this._events[a],l=arguments.length,u,h;if(d.fn){switch(d.once&&this.removeListener(i,d.fn,void 0,!0),l){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,e),!0;case 3:return d.fn.call(d.context,e,t),!0;case 4:return d.fn.call(d.context,e,t,r),!0;case 5:return d.fn.call(d.context,e,t,r,o),!0;case 6:return d.fn.call(d.context,e,t,r,o,n),!0}for(h=1,u=new Array(l-1);h<l;h++)u[h-1]=arguments[h];d.fn.apply(d.context,u)}else{var f=d.length,g;for(h=0;h<f;h++)switch(d[h].once&&this.removeListener(i,d[h].fn,void 0,!0),l){case 1:d[h].fn.call(d[h].context);break;case 2:d[h].fn.call(d[h].context,e);break;case 3:d[h].fn.call(d[h].context,e,t);break;case 4:d[h].fn.call(d[h].context,e,t,r);break;default:if(!u)for(g=1,u=new Array(l-1);g<l;g++)u[g-1]=arguments[g];d[h].fn.apply(d[h].context,u)}}return!0};He.prototype.on=function(i,e,t){return Ou(this,i,e,t,!1)};He.prototype.once=function(i,e,t){return Ou(this,i,e,t,!0)};He.prototype.removeListener=function(i,e,t,r){var o=Xe?Xe+i:i;if(!this._events[o])return this;if(!e)return an(this,o),this;var n=this._events[o];if(n.fn)n.fn===e&&(!r||n.once)&&(!t||n.context===t)&&an(this,o);else{for(var a=0,d=[],l=n.length;a<l;a++)(n[a].fn!==e||r&&!n[a].once||t&&n[a].context!==t)&&d.push(n[a]);d.length?this._events[o]=d.length===1?d[0]:d:an(this,o)}return this};He.prototype.removeAllListeners=function(i){var e;return i?(e=Xe?Xe+i:i,this._events[e]&&an(this,e)):(this._events=new Fs,this._eventsCount=0),this};He.prototype.off=He.prototype.removeListener;He.prototype.addListener=He.prototype.on;He.prefixed=Xe;He.EventEmitter=He;typeof Sc!="undefined"&&(Sc.exports=He)});var Yn=hi((sS,_h)=>{"use strict";var fh=_h.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(fh).forEach(function(s){var i=fh[s];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var Eh=hi(Ni=>{"use strict";var hs=function(s){return String(Number(s))===s?Number(s):s},Kf=function(s,i,e,t){if(t&&!e)i[t]=hs(s[1]);else for(var r=0;r<e.length;r+=1)s[r+1]!=null&&(i[e[r]]=hs(s[r+1]))},Zf=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;Kf(e.match(s.reg),r,s.names,s.name),s.push&&i[s.push].push(r)},gh=Yn(),e_=RegExp.prototype.test.bind(/^([a-z])=(.*)/);Ni.parse=function(s){var i={},e=[],t=i;return s.split(/(\r\n|\r|\n)/).filter(e_).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<(gh[o]||[]).length;a+=1){var d=gh[o][a];if(d.reg.test(n))return Zf(d,t,n)}}),i.media=e,i};var Th=function(s,i){var e=i.split(/=(.+)/,2);return e.length===2?s[e[0]]=hs(e[1]):e.length===1&&i.length>1&&(s[e[0]]=void 0),s};Ni.parseParams=function(s){return s.split(/;\s?/).reduce(Th,{})};Ni.parseFmtpConfig=Ni.parseParams;Ni.parsePayloads=function(s){return s.toString().split(" ").map(Number)};Ni.parseRemoteCandidates=function(s){for(var i=[],e=s.split(" ").map(hs),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};Ni.parseImageAttributes=function(s){return s.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(Th,{})})};Ni.parseSimulcastStreamList=function(s){return s.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=hs(e):(t=hs(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var Ih=hi((nS,Sh)=>{"use strict";var Sd=Yn(),t_=/%[sdv%]/g,i_=function(s){var i=1,e=arguments,t=e.length;return s.replace(t_,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""}})},So=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 i_.apply(null,r)},r_=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s_=["i","c","b","a"];Sh.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||r_,t=i.innerOrder||s_,r=[];return e.forEach(function(o){Sd[o].forEach(function(n){n.name in s&&s[n.name]!=null?r.push(So(o,n,s)):n.push in s&&s[n.push]!=null&&s[n.push].forEach(function(a){r.push(So(o,n,a))})})}),s.media.forEach(function(o){r.push(So("m",Sd.m[0],o)),t.forEach(function(n){Sd[n].forEach(function(a){a.name in o&&o[a.name]!=null?r.push(So(n,a,o)):a.push in o&&o[a.push]!=null&&o[a.push].forEach(function(d){r.push(So(n,a,d))})})})}),r.join(`\r
|
|
1
|
+
var Vg=Object.create;var fn=Object.defineProperty,Fg=Object.defineProperties,Dp=Object.getOwnPropertyDescriptor,$g=Object.getOwnPropertyDescriptors,Bg=Object.getOwnPropertyNames,Cp=Object.getOwnPropertySymbols,Np=Object.getPrototypeOf,wp=Object.prototype.hasOwnProperty,Hg=Object.prototype.propertyIsEnumerable,Wg=Reflect.get;var gn=Math.pow,Ou=(i,t,e)=>t in i?fn(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,Z=(i,t)=>{for(var e in t||(t={}))wp.call(t,e)&&Ou(i,e,t[e]);if(Cp)for(var e of Cp(t))Hg.call(t,e)&&Ou(i,e,t[e]);return i},Ee=(i,t)=>Fg(i,$g(t));var En=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports),Yr=(i,t)=>{for(var e in t)fn(i,e,{get:t[e],enumerable:!0})},Gg=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Bg(t))!wp.call(i,o)&&o!==e&&fn(i,o,{get:()=>t[o],enumerable:!(r=Dp(t,o))||r.enumerable});return i};var ki=(i,t,e)=>(e=i!=null?Vg(Np(i)):{},Gg(t||!i||!i.__esModule?fn(e,"default",{value:i,enumerable:!0}):e,i));var J=(i,t,e,r)=>{for(var o=r>1?void 0:r?Dp(t,e):t,s=i.length-1,n;s>=0;s--)(n=i[s])&&(o=(r?n(t,e,o):n(o))||o);return r&&o&&fn(t,e,o),o};var u=(i,t,e)=>Ou(i,typeof t!="symbol"?t+"":t,e);var Bt=(i,t,e)=>Wg(Np(i),e,t);var A=(i,t,e)=>new Promise((r,o)=>{var s=m=>{try{d(e.next(m))}catch(l){o(l)}},n=m=>{try{d(e.throw(m))}catch(l){o(l)}},d=m=>m.done?r(m.value):Promise.resolve(m.value).then(s,n);d((e=e.apply(i,t)).next())});var Wi=En((ny,ml)=>{"use strict";var QE=Object.prototype.hasOwnProperty,Wt="~";function qn(){}Object.create&&(qn.prototype=Object.create(null),new qn().__proto__||(Wt=!1));function YE(i,t,e){this.fn=i,this.context=t,this.once=e||!1}function ah(i,t,e,r,o){if(typeof e!="function")throw new TypeError("The listener must be a function");var s=new YE(e,r||i,o),n=Wt?Wt+t:t;return i._events[n]?i._events[n].fn?i._events[n]=[i._events[n],s]:i._events[n].push(s):(i._events[n]=s,i._eventsCount++),i}function Fc(i,t){--i._eventsCount===0?i._events=new qn:delete i._events[t]}function kt(){this._events=new qn,this._eventsCount=0}kt.prototype.eventNames=function(){var t=[],e,r;if(this._eventsCount===0)return t;for(r in e=this._events)QE.call(e,r)&&t.push(Wt?r.slice(1):r);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(e)):t};kt.prototype.listeners=function(t){var e=Wt?Wt+t:t,r=this._events[e];if(!r)return[];if(r.fn)return[r.fn];for(var o=0,s=r.length,n=new Array(s);o<s;o++)n[o]=r[o].fn;return n};kt.prototype.listenerCount=function(t){var e=Wt?Wt+t:t,r=this._events[e];return r?r.fn?1:r.length:0};kt.prototype.emit=function(t,e,r,o,s,n){var d=Wt?Wt+t:t;if(!this._events[d])return!1;var m=this._events[d],l=arguments.length,g,_;if(m.fn){switch(m.once&&this.removeListener(t,m.fn,void 0,!0),l){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,e),!0;case 3:return m.fn.call(m.context,e,r),!0;case 4:return m.fn.call(m.context,e,r,o),!0;case 5:return m.fn.call(m.context,e,r,o,s),!0;case 6:return m.fn.call(m.context,e,r,o,s,n),!0}for(_=1,g=new Array(l-1);_<l;_++)g[_-1]=arguments[_];m.fn.apply(m.context,g)}else{var S=m.length,v;for(_=0;_<S;_++)switch(m[_].once&&this.removeListener(t,m[_].fn,void 0,!0),l){case 1:m[_].fn.call(m[_].context);break;case 2:m[_].fn.call(m[_].context,e);break;case 3:m[_].fn.call(m[_].context,e,r);break;case 4:m[_].fn.call(m[_].context,e,r,o);break;default:if(!g)for(v=1,g=new Array(l-1);v<l;v++)g[v-1]=arguments[v];m[_].fn.apply(m[_].context,g)}}return!0};kt.prototype.on=function(t,e,r){return ah(this,t,e,r,!1)};kt.prototype.once=function(t,e,r){return ah(this,t,e,r,!0)};kt.prototype.removeListener=function(t,e,r,o){var s=Wt?Wt+t:t;if(!this._events[s])return this;if(!e)return Fc(this,s),this;var n=this._events[s];if(n.fn)n.fn===e&&(!o||n.once)&&(!r||n.context===r)&&Fc(this,s);else{for(var d=0,m=[],l=n.length;d<l;d++)(n[d].fn!==e||o&&!n[d].once||r&&n[d].context!==r)&&m.push(n[d]);m.length?this._events[s]=m.length===1?m[0]:m:Fc(this,s)}return this};kt.prototype.removeAllListeners=function(t){var e;return t?(e=Wt?Wt+t:t,this._events[e]&&Fc(this,e)):(this._events=new qn,this._eventsCount=0),this};kt.prototype.off=kt.prototype.removeListener;kt.prototype.addListener=kt.prototype.on;kt.prefixed=Wt;kt.EventEmitter=kt;typeof ml!="undefined"&&(ml.exports=kt)});var qc=En((Vy,Ih)=>{"use strict";var Th=Ih.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(i){return i.encoding?"rtpmap:%d %s/%s/%s":i.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(i){return i.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(i){return i.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(i){return"extmap:%d"+(i.direction?"/%s":"%v")+(i["encrypt-uri"]?" %s":"%v")+" %s"+(i.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(i){return i.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(i){var t="candidate:%s %d %s %d %s %d typ %s";return t+=i.raddr!=null?" raddr %s rport %d":"%v%v",t+=i.tcptype!=null?" tcptype %s":"%v",i.generation!=null&&(t+=" generation %d"),t+=i["network-id"]!=null?" network-id %d":"%v",t+=i["network-cost"]!=null?" network-cost %d":"%v",t}},{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(i){var t="ssrc:%d";return i.attribute!=null&&(t+=" %s",i.value!=null&&(t+=":%s")),t}},{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(i){return i.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(i){return i.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(i){return"imageattr:%s %s %s"+(i.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(i){return"simulcast:%s %s"+(i.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(i){return"ts-refclk:%s"+(i.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(i){var t="mediaclk:";return t+=i.id!=null?"id=%s %s":"%v%s",t+=i.mediaClockValue!=null?"=%s":"",t+=i.rateNumerator!=null?" rate=%s":"",t+=i.rateDenominator!=null?"/%s":"",t}},{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(Th).forEach(function(i){var t=Th[i];t.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var Ah=En(di=>{"use strict";var Vs=function(i){return String(Number(i))===i?Number(i):i},s_=function(i,t,e,r){if(r&&!e)t[r]=Vs(i[1]);else for(var o=0;o<e.length;o+=1)i[o+1]!=null&&(t[e[o]]=Vs(i[o+1]))},n_=function(i,t,e){var r=i.name&&i.names;i.push&&!t[i.push]?t[i.push]=[]:r&&!t[i.name]&&(t[i.name]={});var o=i.push?{}:r?t[i.name]:t;s_(e.match(i.reg),o,i.names,i.name),i.push&&t[i.push].push(o)},Sh=qc(),a_=RegExp.prototype.test.bind(/^([a-z])=(.*)/);di.parse=function(i){var t={},e=[],r=t;return i.split(/(\r\n|\r|\n)/).filter(a_).forEach(function(o){var s=o[0],n=o.slice(2);s==="m"&&(e.push({rtp:[],fmtp:[]}),r=e[e.length-1]);for(var d=0;d<(Sh[s]||[]).length;d+=1){var m=Sh[s][d];if(m.reg.test(n))return n_(m,r,n)}}),t.media=e,t};var yh=function(i,t){var e=t.split(/=(.+)/,2);return e.length===2?i[e[0]]=Vs(e[1]):e.length===1&&t.length>1&&(i[e[0]]=void 0),i};di.parseParams=function(i){return i.split(/;\s?/).reduce(yh,{})};di.parseFmtpConfig=di.parseParams;di.parsePayloads=function(i){return i.toString().split(" ").map(Number)};di.parseRemoteCandidates=function(i){for(var t=[],e=i.split(" ").map(Vs),r=0;r<e.length;r+=3)t.push({component:e[r],ip:e[r+1],port:e[r+2]});return t};di.parseImageAttributes=function(i){return i.split(" ").map(function(t){return t.substring(1,t.length-1).split(",").reduce(yh,{})})};di.parseSimulcastStreamList=function(i){return i.split(";").map(function(t){return t.split(",").map(function(e){var r,o=!1;return e[0]!=="~"?r=Vs(e):(r=Vs(e.substring(1,e.length)),o=!0),{scid:r,paused:o}})})}});var Rh=En(($y,bh)=>{"use strict";var Cl=qc(),c_=/%[sdv%]/g,d_=function(i){var t=1,e=arguments,r=e.length;return i.replace(c_,function(o){if(t>=r)return o;var s=e[t];switch(t+=1,o){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},Kn=function(i,t,e){var r=t.format instanceof Function?t.format(t.push?e:e[t.name]):t.format,o=[i+"="+r];if(t.names)for(var s=0;s<t.names.length;s+=1){var n=t.names[s];t.name?o.push(e[t.name][n]):o.push(e[t.names[s]])}else o.push(e[t.name]);return d_.apply(null,o)},u_=["v","o","s","i","u","e","p","c","b","t","r","z","a"],l_=["i","c","b","a"];bh.exports=function(i,t){t=t||{},i.version==null&&(i.version=0),i.name==null&&(i.name=" "),i.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var e=t.outerOrder||u_,r=t.innerOrder||l_,o=[];return e.forEach(function(s){Cl[s].forEach(function(n){n.name in i&&i[n.name]!=null?o.push(Kn(s,n,i)):n.push in i&&i[n.push]!=null&&i[n.push].forEach(function(d){o.push(Kn(s,n,d))})})}),i.media.forEach(function(s){o.push(Kn("m",Cl.m[0],s)),r.forEach(function(n){Cl[n].forEach(function(d){d.name in s&&s[d.name]!=null?o.push(Kn(n,d,s)):d.push in s&&s[d.push]!=null&&s[d.push].forEach(function(m){o.push(Kn(n,d,m))})})})}),o.join(`\r
|
|
2
2
|
`)+`\r
|
|
3
|
-
`}});var Ah=hi(Qt=>{"use strict";var Sr=Eh(),o_=Ih(),n_=Yn();Qt.grammar=n_;Qt.write=o_;Qt.parse=Sr.parse;Qt.parseParams=Sr.parseParams;Qt.parseFmtpConfig=Sr.parseFmtpConfig;Qt.parsePayloads=Sr.parsePayloads;Qt.parseRemoteCandidates=Sr.parseRemoteCandidates;Qt.parseImageAttributes=Sr.parseImageAttributes;Qt.parseSimulcastStreamList=Sr.parseSimulcastStreamList});var du=hi((_w,ep)=>{"use strict";var Zm=ep.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(Zm).forEach(function(s){var i=Zm[s];i.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})})});var rp=hi(Fi=>{"use strict";var Ms=function(s){return String(Number(s))===s?Number(s):s},bT=function(s,i,e,t){if(t&&!e)i[t]=Ms(s[1]);else for(var r=0;r<e.length;r+=1)s[r+1]!=null&&(i[e[r]]=Ms(s[r+1]))},NT=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;bT(e.match(s.reg),r,s.names,s.name),s.push&&i[s.push].push(r)},tp=du(),vT=RegExp.prototype.test.bind(/^([a-z])=(.*)/);Fi.parse=function(s){var i={},e=[],t=i;return s.split(/(\r\n|\r|\n)/).filter(vT).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<(tp[o]||[]).length;a+=1){var d=tp[o][a];if(d.reg.test(n))return NT(d,t,n)}}),i.media=e,i};var ip=function(s,i){var e=i.split(/=(.+)/,2);return e.length===2?s[e[0]]=Ms(e[1]):e.length===1&&i.length>1&&(s[e[0]]=void 0),s};Fi.parseParams=function(s){return s.split(/;\s?/).reduce(ip,{})};Fi.parseFmtpConfig=Fi.parseParams;Fi.parsePayloads=function(s){return s.toString().split(" ").map(Number)};Fi.parseRemoteCandidates=function(s){for(var i=[],e=s.split(" ").map(Ms),t=0;t<e.length;t+=3)i.push({component:e[t],ip:e[t+1],port:e[t+2]});return i};Fi.parseImageAttributes=function(s){return s.split(" ").map(function(i){return i.substring(1,i.length-1).split(",").reduce(ip,{})})};Fi.parseSimulcastStreamList=function(s){return s.split(";").map(function(i){return i.split(",").map(function(e){var t,r=!1;return e[0]!=="~"?t=Ms(e):(t=Ms(e.substring(1,e.length)),r=!0),{scid:t,paused:r}})})}});var op=hi((Tw,sp)=>{"use strict";var lu=du(),DT=/%[sdv%]/g,OT=function(s){var i=1,e=arguments,t=e.length;return s.replace(DT,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""}})},Ko=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 OT.apply(null,r)},kT=["v","o","s","i","u","e","p","c","b","t","r","z","a"],MT=["i","c","b","a"];sp.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||kT,t=i.innerOrder||MT,r=[];return e.forEach(function(o){lu[o].forEach(function(n){n.name in s&&s[n.name]!=null?r.push(Ko(o,n,s)):n.push in s&&s[n.push]!=null&&s[n.push].forEach(function(a){r.push(Ko(o,n,a))})})}),s.media.forEach(function(o){r.push(Ko("m",lu.m[0],o)),t.forEach(function(n){lu[n].forEach(function(a){a.name in o&&o[a.name]!=null?r.push(Ko(n,a,o)):a.push in o&&o[a.push]!=null&&o[a.push].forEach(function(d){r.push(Ko(n,a,d))})})})}),r.join(`\r
|
|
4
|
-
`)+`\r
|
|
5
|
-
`}});var uu=hi(Hi=>{"use strict";var Ur=rp(),LT=op();Hi.write=LT;Hi.parse=Ur.parse;Hi.parseParams=Ur.parseParams;Hi.parseFmtpConfig=Ur.parseFmtpConfig;Hi.parsePayloads=Ur.parsePayloads;Hi.parseRemoteCandidates=Ur.parseRemoteCandidates;Hi.parseImageAttributes=Ur.parseImageAttributes;Hi.parseSimulcastStreamList=Ur.parseSimulcastStreamList});import nH from"webrtc-adapter";var Jm=Be(ze());var ku=(w=>(w[w.INVALID_PARAMETER=4096]="INVALID_PARAMETER",w[w.INVALID_OPERATION=4097]="INVALID_OPERATION",w[w.NOT_SUPPORTED=4098]="NOT_SUPPORTED",w[w.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",w[w.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",w[w.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",w[w.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",w[w.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",w[w.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",w[w.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",w[w.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",w[w.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",w[w.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",w[w.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",w[w.CLIENT_BANNED=16448]="CLIENT_BANNED",w[w.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",w[w.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",w[w.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",w[w.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",w[w.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",w[w.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",w[w.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",w[w.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",w[w.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",w[w.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",w[w.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",w[w.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",w[w.API_CALL_ABORTED=16461]="API_CALL_ABORTED",w[w.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",w[w.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",w[w.UNKNOWN=65535]="UNKNOWN",w))(ku||{}),I=ku;var tf=function(s){for(let i in I)if(I[i]===s)return i;return"UNKNOWN"},Ic=class extends Error{constructor({name:e="RtcError",message:t,code:r=I.UNKNOWN,extraCode:o=0,constraint:n}){let a=`<${tf(r)} 0x${r.toString(16)}>`,d=`${t}${n?` constraint: ${n}`:""}${t!=null&&t.includes(a)?"":` ${a}`}`;super(d);c(this,"code");c(this,"extraCode");c(this,"message");c(this,"originMessage");c(this,"name");c(this,"constraint");this.code=r,this.extraCode=o,this.name=e,this.message=d,this.constraint=n,this.originMessage=t}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},b=Ic;var Mu=new Date().getTime(),Ac=0,Lu=function(s){Mu=s,Ac=Mu-new Date().getTime();let i=new Date;i.setTime(s),C.info(`baseTime from server: ${i} offset: ${Ac}`)},Hs=function(){return new Date().getTime()+Ac},cn=function(){let s=new Date;return s.setTime(Hs()),s.toLocaleString()},dn=function(s){let i=String(s.getMilliseconds());return"padStart"in String.prototype&&(i=i.toString().padStart(3,"0")),`${s.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${i}`};var dt={};mi(dt,{bytes2ms:()=>Hu,convertObjectNumberToInt:()=>eo,copyProperties:()=>Fu,deepClone:()=>ur,deepMerge:()=>Wt,delay:()=>Ei,fibonacci:()=>mr,formatedTime:()=>zu,getConstructorName:()=>Ks,getContainerFromElement:()=>Xu,getEnv:()=>Vu,getInternalVersion:()=>ju,getLoggerUrl:()=>gi,getMediaStreamTrackInfo:()=>bn,getMuteStateFromFlag:()=>Ti,getNetworkType:()=>Uc,getNumNetworkType:()=>hr,getReconnectionTimeout:()=>Nt,getStringByteLength:()=>Zs,getTurnServer:()=>qu,getUint32Version:()=>Cn,getValueType:()=>ye,getViewListFromView:()=>Qr,glog:()=>Fc,ipv4ToUint32:()=>zr,isArray:()=>Ie,isAudioWorkletSupported:()=>Ju,isBoolean:()=>_e,isConstructor:()=>qr,isEmpty:()=>Xr,isFunction:()=>ce,isLangChinese:()=>bt,isMediaStreamTrack:()=>Gu,isNumber:()=>Y,isObject:()=>Gt,isOverseaSdkAppId:()=>Ys,isPlainObject:()=>rt,isPortrait:()=>An,isPromise:()=>ji,isRemoteTrack:()=>Wu,isString:()=>Z,isUndefined:()=>T,loadImage:()=>Yr,ms2bytes:()=>$u,ms2samples:()=>Bc,normalizeUrl:()=>yn,performanceNow:()=>P,promiseAny:()=>pr,samples2ms:()=>Vc,setNetworkType:()=>Sn,stringify:()=>Tt,stringifyIncludeValue:()=>In,throttlePromise:()=>Rn});var xc={};mi(xc,{AUDIO_MUTE_BIT:()=>_n,AUDIO_STAT_BIT:()=>Wi,AUX_STAT_BIT:()=>cr,AUX_STREAM_MSID:()=>vc,BACKEND_ENV:()=>fn,BASE_DOC_URL:()=>Ht,BASE_HOST:()=>Pu,CAPABILITIES_KEYS:()=>En,CLASS_NAME:()=>Rf,CLOUD_CONSOLE_URL:()=>nf,CROSS_ROOM_BIT:()=>Nc,DATA_FREEZE_TIMING:()=>Tn,DEFAULT_ASSETS_URL:()=>ln,DOC_URL:()=>af,DTLS_STATE_UNKNOWN:()=>yt,ENV_NAME:()=>pi,EXCHANGE_SDP_TIMEOUT:()=>Lc,IS_WORKER:()=>Gr,IS_WORKLET:()=>Gs,KIBANA_EVENT:()=>it,LOCAL_STREAM_PUBLISH_STATE:()=>xu,LOGGER_CMD_TYPE:()=>$i,LOGGER_DOMAIN:()=>Rc,LOGGER_DOMAIN_OVERSEA:()=>yc,LOG_LEVEL:()=>Rt,LOG_LEVEL_NAME:()=>bf,MAIN_STREAM_MSID:()=>js,MAX_RTT:()=>zs,MICROPHONE_COMMUNICATIONS:()=>yf,MICROPHONE_DEFAULT:()=>lr,MUTE_ALL_BIT:()=>lf,NAME:()=>m,NETWORK_TYPE:()=>un,NOT_SUPPORTED_H264:()=>dr,PAUSED_RETRY_COUNT:()=>Pc,PEERCONNECTION_CONNECTING_TIMEOUT:()=>qs,PEER_CONNECTION_STATE:()=>me,PEER_LEAVE_REASON:()=>wc,RECOVER_CAPTURE_INTERVAL:()=>jr,REMOTE_STREAM_TYPE_AUX:()=>Oc,REMOTE_STREAM_TYPE_MAIN:()=>Dc,RENDER_FREEZE_TIMING:()=>Sf,SCHEDULE_DOMAIN:()=>_i,SCHEDULE_TIMEOUT:()=>Cf,SDP_SEMANTICS_PLAN_B:()=>Wr,SDP_SEMANTICS_UNIFIED_PLAN:()=>Ji,SECOND_HOST:()=>sf,SIGNAL_PING_PONG_INTERVAL:()=>df,SIGNAL_PING_TIMEOUT:()=>cf,SIGNAL_RECONNECTION_COUNT:()=>Tf,SMALL_STAT_BIT:()=>Js,SPEAKER_DEFAULT:()=>Xs,STORAGE_EXPIRES_TIME:()=>hn,STREAM_TYPE_BIG:()=>If,STREAM_TYPE_SMALL:()=>Af,SUBSCRIBE_SMALL_RETRY_COUNT:()=>Jr,SYNC_USER_LIST_INTERVAL:()=>Ef,Scene:()=>$t,THIRD_HOST:()=>of,TRANSPORT_DIRECTION:()=>K,TRTC_ERROR_ASSISTANCE:()=>bc,TRTC_QUALITY_BAD:()=>ff,TRTC_QUALITY_DISCONNECTED:()=>gf,TRTC_QUALITY_EXCELLENT:()=>hf,TRTC_QUALITY_GOOD:()=>mf,TRTC_QUALITY_POOR:()=>pf,TRTC_QUALITY_UNKNOWN:()=>uf,TRTC_QUALITY_VERY_BAD:()=>_f,UPDATE_OFFER_TIMEOUT:()=>Mc,VIDEO_MUTE_BIT:()=>gn,VIDEO_STAT_BIT:()=>Gi,audioProfileMap:()=>mn,getRetryCount:()=>fi,getScriptDir:()=>rf,innerVersion:()=>$s,loggerProxy:()=>Ws,screenProfileMap:()=>pn,setLoggerProxy:()=>ar,setRetryCount:()=>kc,setVersion:()=>Cc,version:()=>Oe,videoProfileMap:()=>gt});var $s="4.15.00.1600",Oe="5.0.0";function Cc(s){Oe=s;let[i,e,t]=s.split(".").map(r=>parseInt(r,10));$s=`${i}.${Math.min(15,e)}.${Math.min(15,t)}.${e.toString().padStart(2,"0")}${t.toString().padStart(2,"0")}`}var Gr=typeof importScripts!="undefined",Gs=typeof registerProcessor!="undefined",rf=()=>{let s=Gr?self.location.href:document.currentScript.src;return s.substring(0,s.lastIndexOf("/")+1)},Ws="",ar=s=>Ws=s,Pu="web.sdk.qcloud.com",sf="web.sdk.tencent.cn",of="web.sdk.cloud.tencent.cn",nf="https://console.cloud.tencent.com/trtc",Ht=`https://${Pu}/trtc/webrtc/v5/doc`,ln="https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/",af=`${Ht}/zh-cn/`,Rc="https://yun.tim.qq.com",yc="https://apisgp.my-imcloud.com",bc="trtc_error_assistance",$i={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},pi={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},Rt=(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))(Rt||{}),cf=18e3,df=2e3,un={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},hn=7*24*3600*1e3,mn={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}},gt={"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}},pn={"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"},K={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},fn={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},$t=(e=>(e.LIVE="live",e.RTC="rtc",e))($t||{}),Gi=1,Js=2,cr=4,Wi=8,_n=64,gn=16,lf=112,Nc=128,js="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",vc="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",Dc=m.MAIN,Oc=m.AUXILIARY,uf=0,hf=1,mf=2,pf=3,ff=4,_f=5,gf=6,yt="unknown",me={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},wu=1/0;function kc(s){wu=s}function fi(){return wu}var Tf=30,it={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"},Ef=1e4,Mc=1e4,Lc=1e4,Ji="unified-plan",Wr="plan-b",dr=1028,xu=(t=>(t[t.UNPUBLISH=-1]="UNPUBLISH",t[t.PUBLISHING=0]="PUBLISHING",t[t.PUBLISHED=1]="PUBLISHED",t))(xu||{}),Tn=500,Sf=1e3,If=m.BIG,Af=m.SMALL,qs=10*1e3,_i={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_BACKUP:"intl-schedule.cloud-rtc.com"},Cf=2e3,Rf={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},Pc=5,lr="default",Xs=lr,yf="communications",bf=Object.keys(Rt),wc=["normal leave","timeout leave","kick","role change"],Jr=10,jr=2e3,En=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],zs=10*1e3;var Vu=function(){return new URLSearchParams(location.search).get("trtc_env")||""},Ys=s=>Number(s)<14e8,gi=function(s,i){let e;Ws?e=Ws:e=Ys(s)?yc:Rc;let t=Math.floor(Math.random()*Bs(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${t}&sdkappid=${s}&cmdtype=${i}`},Qs="unknown";function Uc(){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=Bu(t,r)),Qs}function Bu(s,i){if(un[s])return s;switch(s){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function Sn(s){Qs=Bu(s)}function hr(){return un[Uc()]}function Fu(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 Hu(s,i=48e3){return Vc(s/4,i)}function Vc(s,i=48e3){return s*1e3/i}function $u(s,i=48e3){return Bc(s,i)*4}function Bc(s,i=48e3){return s*i/1e3}var Fc=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},bt=()=>{let s=navigator.language;return s=s.substring(0,2),s==="zh"},rt=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 mr(s,i=1,e=1){return s<=1?e:mr(s-1,e,i+e)}function Nt(s){return s>8?30*1e3:mr(s)*1e3}function ye(s){return Reflect.apply(Object.prototype.toString,s,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var ce=s=>typeof s=="function",T=s=>typeof s=="undefined",Z=s=>typeof s=="string",Y=s=>typeof s=="number",_e=s=>typeof s=="boolean",Gt=s=>ye(s)==="object",Ie=s=>ye(s)==="array",Gu=s=>ye(s)==="MediaStreamTrack".toLowerCase(),Wu=s=>s.isRemote,ji=s=>ye(s)==="promise",qr=s=>ce(s)&&s.prototype.constructor===s,Ks=s=>qr(s)?s.prototype.constructor.name:"",Ju=typeof AudioWorkletNode!="undefined";function pr(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 P(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var Uu=s=>+s<10?`0${s}`:s,ju=s=>{let i=s.match(/^\d+\.\d+\.\d+/)[0];if(!i)return s;let e=i.split("."),t=Uu(e[1])+Uu(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${t}`},Nf=Object.prototype.hasOwnProperty,{toString:uE}=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(rt(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(Nf.call(s,i))return!1;return!0}}return!1}function Ti(s,i){return{userId:i,hasAudio:!!(s&Wi),hasVideo:!!(s&Gi),hasAuxiliary:!!(s&cr),hasSmall:!!(s&Js),audioMuted:!!(s&_n),videoMuted:!!(s&gn),audioAvailable:!!(s&Wi)&&!(s&_n),videoAvailable:!!(s&Gi)&&!(s&gn)}}function qu(s){let i={urls:s.url.startsWith("turn:")||s.url.startsWith("turns:")?s.url:`turn:${s.url}`};return!T(s.username)&&!T(s.credential)&&(i.username=s.username,i.credential=s.credential,i.credentialType="password",T(s.credentialType)||(i.credentialType=s.credentialType)),i}function zr(s,i=!0){if(!Z(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 Wt=function(s,i,e,t){if(!(Gt(s)&&Gt(i)))return 0;let r=0,o=Object.keys(i),n;for(let a=0,d=o.length;a<d;a++)if(n=o[a],!(T(i[n])||e&&e.includes(n)))if(Gt(s[n])&&Gt(i[n]))r+=Wt(s[n],i[n],e,t);else{if(t&&t.includes(i[n]))continue;s[n]!==i[n]&&(s[n]=ur(i[n]),r+=1)}return r};function ur(s){if(Ie(s)){let i=[];return s.forEach((e,t)=>{i[t]=ur(e)}),i}if(Gt(s)){let i={};return Object.keys(s).forEach(e=>{i[e]=ur(s[e])}),i}return s}var Qr=s=>{let i=[];if(Ie(s))i=[...s];else if(Z(s)){let e=document.getElementById(s);e&&i.push(e)}else s&&i.push(s);return i},Xu=s=>Z(s)?document.getElementById(s):s,vf=s=>{let i=d=>d<10?`0${d}`:`${d}`,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}`},zu=()=>vf(new Date);function Tt(s,{keysToInclude:i,keysToExclude:e}){try{if(Ie(s))return`[${s.map(n=>Tt(n,{keysToInclude:i,keysToExclude:e})).join(",")}]`;if(!rt(s)||!Ie(i)&&!Ie(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]=rt(s[n])||Ie(s[n])?JSON.parse(Tt(s[n],{keysToExclude:e,keysToInclude:i})):s[n])}),JSON.stringify(t)}catch(t){return"{}"}}function In(s,i=!1){let e=[];return Object.keys(s).forEach(t=>{i===s[t]&&e.push(t)}),Tt(s,{keysToInclude:e})}function Zs(s){return s.replace(/[\u4e00-\u9fa5]/g,"aa").length}var An=()=>{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=>p(void 0,null,function*(){return new Promise((i,e)=>{let t;if(Z(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:I.INVALID_PARAMETER,message:`load image failed, url: ${s}`}))}})}),Cn=s=>{let i=s.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]<<0},eo=s=>(Object.keys(s).forEach(i=>{Y(s[i])&&(i.startsWith("uint")||i.startsWith("int"))?s[i]=Math.floor(s[i]):(rt(s[i])||Ie(s[i]))&&eo(s[i])}),s);function Ei(s,i){return new Promise(e=>{let t=setTimeout(e,s);i&&i(t)})}function Rn(s,i){let e=null;return function(...t){return e||(e=s.apply(i||this,t),e.finally(()=>e=null),e)}}function yn(s){return s.replace(/(^|[^:])\/{2,}/g,"$1/")}function bn(s){var i;try{let{width:e,height:t,frameRate:r,sampleRate:o,sampleSize:n,channelCount:a}=(i=s.getSettings)==null?void 0:i.call(s),d=s.kind===m.AUDIO?`${o}x${n}@${a}`:`${e}x${t}@${r}`,l=s.stats?` stats: ${JSON.stringify(s.stats).replaceAll('"',"")}`:"";return`${s.id} ${s.readyState} muted:${s.muted} ${s.kind} ${s.label} ${d}${l}`}catch(e){return""}}function Si({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(d=>d.text()).then(d=>{try{o({data:JSON.parse(d)})}catch(l){o({data:d})}},n);let a=new XMLHttpRequest;a.onreadystatechange=()=>{if(a.readyState===4)if(a.status>=200&&a.status<300)try{let d=JSON.parse(a.response);o({data:d})}catch(d){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 Hc(s){return p(this,null,function*(){let i=P(),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} ${P()-i}ms`),a}catch(t){return e}})}var Df=Object.prototype.hasOwnProperty;var Jt=s=>typeof s=="function",Ii=s=>typeof s=="undefined";var Nn=s=>typeof s=="boolean";var $c=s=>s.isRemote;var Of=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 Qu(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(Of(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(Df.call(s,i))return!1;return!0}}return!1}var kf=0,Mf=1,Yu=2;function Lf({retryFunction:s,settings:i,onError:e,onRetrying:t,onRetryFailed:r,onRetrySuccess:o,context:n}){return function(...a){let{retries:d=5,timeout:l=1e3}=i,u=0,h=-1,f=kf,g=(D,_)=>p(this,null,function*(){let R=n||this;try{let k=yield s.apply(R,a);u>0&&o&&o.call(this,u),u=0,D(k)}catch(k){let j=()=>{clearTimeout(h),u=0,f=Yu,_(k)},oe=()=>{f!==Yu&&u<(Jt(d)?d():d)?(u++,f=Mf,Jt(t)&&t.call(this,u,j),h=window.setTimeout(()=>{h=-1,g(D,_)},Jt(l)?l(u):l)):(j(),Jt(r)&&r.call(this,k))};Jt(e)?e.call(this,{error:k,retry:oe,reject:_,retryFuncArgs:a,retriedCount:u}):oe()}});return new Promise(g)}}var jt=Lf;var Kr=class{constructor(i){c(this,"userId");c(this,"remoteUserId");c(this,"id");c(this,"sdkAppId");c(this,"type");c(this,"isLocal");this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=Nn(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,Ii(this.userId)||Qu(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={};mi(ds,{ANDROID_VERSION:()=>Jc,CHROME_MAJOR_VERSION:()=>lt,CHROME_VERSION:()=>Wn,EDGE_VERSION:()=>Dn,EDG_MAJOR_VERSION:()=>jc,EDG_VERSION:()=>On,FIREFOX_MAJOR_VERSION:()=>to,FIREFOX_VERSION:()=>vn,HUAWEI_VERSION:()=>Fn,IE_VERSION:()=>Vf,IOS_MAIN_VERSION:()=>ut,IOS_VERSION:()=>Xt,IPADQQB_VERSION:()=>Vn,IS_ANDROID:()=>he,IS_ANDROID_WEBVIEW:()=>$f,IS_ANY_SAFARI:()=>Xi,IS_CHROME:()=>cs,IS_CHROME_OS:()=>qc,IS_CHROMIUM_BASE:()=>Qe,IS_DESKTOP_IOS_CHROME:()=>id,IS_EDG:()=>is,IS_EDGE:()=>ts,IS_ELECTRON:()=>Ff,IS_FIREFOX:()=>se,IS_HEADLESS_CHROME:()=>Kc,IS_HONOR:()=>Qc,IS_HUAWEI:()=>zc,IS_HUAWEIBROWSER:()=>lo,IS_IE:()=>th,IS_IE8:()=>Uf,IS_IOS:()=>Te,IS_IOS_13_OR_14:()=>td,IS_IOS_15_1:()=>ed,IS_IOS_CHROME:()=>ih,IS_IPAD:()=>es,IS_IPADQQB:()=>no,IS_IPAD_PRO:()=>Wc,IS_IPHONE:()=>qi,IS_IPOD:()=>eh,IS_LINUX:()=>ao,IS_LOCAL:()=>Mt,IS_MAC:()=>kt,IS_MACQQB:()=>oo,IS_MIBROWSER:()=>co,IS_MQQB:()=>ns,IS_NATIVE_ANDROID:()=>xf,IS_OLD_ANDROID:()=>wf,IS_OPENHARMONY:()=>Yc,IS_OPPOBROWSER:()=>ho,IS_SAFARI:()=>Me,IS_SAFARI_15_1:()=>Gf,IS_SAMSUNGBROWSER:()=>uo,IS_SOGOU:()=>ro,IS_SOGOUM:()=>io,IS_TBS:()=>Ot,IS_UCBROWSER:()=>Xc,IS_VIVOBROWSER:()=>mo,IS_WECHAT:()=>ss,IS_WIN:()=>fr,IS_WQQB:()=>so,IS_WX:()=>Bf,IS_X5MQQB:()=>os,IS_XWEB:()=>rs,MACQQB_VERSION:()=>Un,MI_VERSION:()=>Bn,MQQB_VERSION:()=>Zr,OPENHARMONY_VERSION:()=>Hf,OPPO_VERSION:()=>$n,SAFARI_VERSION:()=>Ai,SAMSUNG_VERSION:()=>Hn,SOGOUM_VERSION:()=>kn,SOGOU_VERSION:()=>Mn,TBS_VERSION:()=>Ln,UA_DATA_STRING:()=>vt,USER_AGENT:()=>Dt,VIVO_VERSION:()=>Gn,WECHAT_VERSION:()=>wn,WQQB_VERSION:()=>xn,XWEB_VERSION:()=>Pn,browserInfo:()=>qt,getBrowserInfo:()=>rh,getChromeMajorVersion:()=>as,getDeviceModel:()=>_r,getGPUInfo:()=>sd,getOSName:()=>Jn,getOSNumber:()=>fo,getOSString:()=>Ri,getOSType:()=>Wf,getTerminalType:()=>od,getUserAgentData:()=>po,isLocalStorageEnabled:()=>Ci,isMobile:()=>rd,isVersionSmallerThan:()=>Zc});var Dt=typeof navigator=="undefined"?"":navigator.userAgent,X=s=>new RegExp(s,"i").test(Dt),be=s=>{if(X(s)){let i=new RegExp(`${s}\\/([\\d.]+)`),e=Dt.match(i);if(e&&e[1])return e[1]}return""},Gc=s=>{if(X(s)){let i=new RegExp(`${s}\\/(\\d+)`),e=Dt.match(i);if(e&&e[1])return parseFloat(e[1])}return NaN},Ku=/AppleWebKit\/([\d.]+)/i.exec(Dt),Pf=Ku?parseFloat(Ku[1]):NaN,es=X("iPad"),Wc=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&X("Macintosh"),qi=X("iPhone")&&!es,eh=X("iPod"),Te=qi||es||eh||Wc,he=X("Android"),Jc=function(){if(he){let s=Dt.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}(),wf=he&&X("webkit")&&Jc<2.3,xf=he&&Jc<5&&Pf<537,se=X("Firefox"),vn=be("Firefox"),to=Gc("Firefox"),ts=X("Edge"),Dn=be("Edge"),is=X("Edg"),On=be("Edg"),jc=Gc("Edg"),io=X("SogouMobileBrowser"),kn=be("SogouMobileBrowser"),ro=X("MetaSr\\s"),Mn=be("MetaSr\\s"),Ot=X("TBS"),Ln=be("TBS"),rs=X("XWEB"),Pn=be("XWEB"),Uf=X("MSIE\\s8\\.0"),th=X("MSIE\\/\\d+"),Vf=function(){if(th){let s=/MSIE\s(\d+)\.\d/.exec(Dt),i=s&&parseFloat(s[1]);return!i&&/Trident\/7.0/i.test(Dt)&&/rv:11.0/.test(Dt)&&(i=11),i}return NaN}(),ss=X("(micromessenger|webbrowser)"),wn=be("MicroMessenger"),os=!Ot&&X("MQQBrowser")&&X("COVC"),ns=!Ot&&X("MQQBrowser")&&!X("COVC"),Zr=ns||os?be("MQQBrowser"):"",so=!Ot&&X(" QQBrowser"),xn=be(" QQBrowser"),oo=!Ot&&X("QQBrowserLite"),Un=be("QQBrowserLite"),no=!Ot&&X("MQBHD"),Vn=be("MQBHD"),fr=X("Windows"),kt=!Te&&X("MAC OS X"),ao=!he&&X("Linux"),qc=X("CrOS"),Bf=X("MicroMessenger"),Xc=X("UCBrowser"),Ff=X("Electron"),co=X("MiuiBrowser"),Bn=be("MiuiBrowser"),lo=X("HuaweiBrowser"),zc=X("Huawei")||X("HUAWEI"),Qc=X("Honor")||X("HONOR"),Fn=be("HuaweiBrowser"),uo=X("SamsungBrowser"),Hn=be("SamsungBrowser"),ho=X("HeyTapBrowser"),$n=be("HeyTapBrowser"),mo=X("VivoBrowser"),Gn=be("VivoBrowser"),Yc=X("OpenHarmony"),Hf=be("OpenHarmony"),as=()=>Gc("Chrome"),Qe=X("Chrome"),cs=!ts&&!ro&&!io&&!Ot&&!rs&&!is&&!so&&!co&&!lo&&!uo&&!ho&&!mo&&Qe,Kc=X("HeadlessChrome"),lt=as(),Wn=be("Chrome"),Me=!Qe&&!ns&&!os&&!oo&&!no&&X("Safari"),Xi=Me||Te,Ai=be("Version"),$f=/Android.*(wv|.0.0.0)/.test(Dt),Xt=(()=>{if(Wc)return Ai;if(Te){let s=Dt.match(/OS (\d+)_(\d+)/i);if(s&&s[1]){let i=s[1];return s[2]&&(i+=`.${s[2]}`),i}}return""})();function Zc(s,i){let e=s.split(".").map(r=>Number(r)),t=i.split(".").map(r=>Number(r));for(let r=0;r<Math.max(e.length,t.length);r++){let o=e[r]||0,n=t[r]||0;if(o<n)return!0;if(o>n)return!1}return!1}var ut=Number(Xt.split(".")[0]),Gf=Ai==="15.1",ed=Xt==="15.1",td=(()=>{let s=Number(Xt.split(".")[0]);return s===14||s===13})(),ih=X("CriOS"),id=ih&&Ai==="11.1.1",Mt=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",Ci=(()=>{let s;return()=>{if(typeof s=="undefined")try{s=!!window.localStorage}catch(i){s=!1}return s}})(),qt=rh();function rh(){let s=new Map([[se,["Firefox",vn]],[is,["Edg",On]],[cs,["Chrome",Wn]],[Me,["Safari",Ai]],[Ot,["TBS",Ln]],[rs,["XWEB",Pn]],[ss&&qi,["WeChat",wn]],[so,["QQ(Win)",xn]],[ns,["QQ(Mobile)",Zr]],[os,["QQ(Mobile X5)",Zr]],[oo,["QQ(Mac)",Un]],[no,["QQ(iPad)",Vn]],[co,["MI",Bn]],[lo,["HW",Fn]],[uo,["Samsung",Hn]],[ho,["OPPO",$n]],[mo,["VIVO",Gn]],[ts,["EDGE",Dn]],[io,["SogouMobile",kn]],[ro,["Sogou",Mn]]]),i="unknown",e="unknown";return s.has(!0)&&([i,e]=s.get(!0)),{name:i,version:e}}var ne=null;function rd(){return ne&&typeof ne.mobile=="boolean"?ne.mobile:he||Te||qi||es||Yc}var vt="";function po(){return p(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&&!vt&&(vt=`UAData: ${ne.platform}/${ne.platformVersion}`,ne.architecture&&ne.bitness&&(vt+=` ${ne.architecture}/${ne.bitness}`),ne.mobile&&(vt+=" mobile"),ne.model&&(vt+=` model: ${ne.model.replace(/\s+/g,"/")}`),ne.fullVersionList&&(vt+=` ${ne.fullVersionList.filter(s=>s.brand!=="Not/A)Brand").map(s=>`${s.brand}/${s.version}`).join(",")}`)),ne}catch(s){return null}})}function sd(){try{let s=document.createElement("canvas"),i=s.getContext("webgl")||s.getContext("experimental-webgl");if(!i)return"";let e=i.getExtension("WEBGL_debug_renderer_info");if(e){let t=i.getParameter(e.UNMASKED_VENDOR_WEBGL),r=i.getParameter(e.UNMASKED_RENDERER_WEBGL);return`${t} ${r}`}return""}catch(s){return""}}function _r(){return(ne==null?void 0:ne.model)||""}var Zu=new Map([[he,"Android"],[Te,"iOS"],[fr,"Windows"],[kt,"MacOS"],[ao,"Linux"],[qc,"ChromeOS"]]),Jn=function(){return Zu.get(!0)?Zu.get(!0):ne?ne.platform:"unknown"};function fo(){return fr?1:he?2:kt?3:Te?4:ao?5:qc?6:0}var Ri=()=>{let s=Jn();return s+=`/${qt.name}/${Me?qt.version:qt.version.split(".")[0]}`,ne!=null&&ne.platformVersion&&(s+=`/${ne.platformVersion}`),ne!=null&&ne.architecture&&(s+=`/${ne.architecture}`),s};function od(){return he?4:qi?2:es?3:kt?12:fr?5:ao?13:Yc?22:1}function Wf(){return he?"Android":qi?"iPhone":es?"iPad":kt?"Mac":fr?"Windows":ao?"Linux":"unknown"}var sh=Be(ze(),1),Jf=new sh.default,S=Jf;var yi=(q=>(q.ROOM_DESTROY="1",q.JOIN_START="21",q.JOIN_SCHEDULE_SUCCESS="22",q.JOIN_SIGNAL_CONNECTION_START="23",q.JOIN_SIGNAL_CONNECTION_END="24",q.JOIN_SEND_CMD="25",q.JOIN_RECEIVED_CMD_RES="26",q.JOIN_SUCCESS="27",q.JOIN_FAILED="28",q.LEAVE_START="51",q.LEAVE_SEND_CMD="52",q.LEAVE_SUCCESS="53",q.PUBLISH_START="61",q.SEND_FIRST_VIDEO_FRAME="62",q.PUBLISH_FAILED="63",q.SUBSCRIBE_START="81",q.SUBSCRIBE_SUCCESS="82",q.SUBSCRIBE_FAILED="84",q.UNSUBSCRIBE_SUCCESS="83",q.LOCAL_TRACK_CAPTURE_START="101",q.LOCAL_TRACK_CAPTURE_SUCCESS="102",q.LOCAL_TRACK_CAPTURE_FAILED="103",q.LOCAL_TRACK_PUBLISHED="104",q.LOCAL_TRACK_UNPUBLISHED="105",q.LOCAL_TRACK_REPLACED="106",q.SWITCH_DEVICE_SUCCESS="107",q.TRACK_MUTED="108",q.TRACK_UNMUTED="109",q.REMOTE_TRACK_SUBSCRIBED="110",q.REMOTE_TRACK_UNSUBSCRIBED="111",q.LOCAL_TRACK_RECAPTURE="112",q.PLAY_TRACK_START="151",q.PLAYER_STATE_CHANGED="152",q.VIDEO_LOADED_DATA="153",q.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",q.SIGNAL_CONNECTION_STATE_CHANGED="201",q.PEER_CONNECTION_STATE_CHANGED="202",q.SINGLE_CONNECTION_STAT="203",q.SPC_RECONNECTED="204",q.HEARTBEAT_REPORT="251",q.RECEIVED_PUBLISHED_USER_LIST="252",q.REMOTE_PUBLISH_STATE_CHANGED="253",q.AUDIO_LEVEL_INTERVAL="260",q.NETWORK_QUALITY="261",q.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",q.QUALITY_LIMITATION_CHANGED="263",q.LOG="264",q))(yi||{});var E=yi;var jf="%cTRTC%c%s",qf="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",Xf="display: inline",jn=class jn{constructor(){c(this,"_isEnableUploadLog",!0);c(this,"_localJoinedUser",new Map);c(this,"_queue",[]);c(this,"_timeoutId",-1);c(this,"_logLevel",1);c(this,"_logLevelToUpload",2);!Gr&&!Gs&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){S.on(E.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var e;(e=i==null?void 0:i.config)!=null&&e.logLevelToUpload&&Rt[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),S.on(E.JOIN_SUCCESS,({room:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),S.once(E.JOIN_FAILED,()=>{this.startUpload()}),S.on(E.LEAVE_SUCCESS,({room:i})=>{this.deleteJoinedUser(i.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(i){this._localJoinedUser.set(i.userId,i),this.startUpload()}deleteJoinedUser(i){this._localJoinedUser.delete(i)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),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(Z(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 p(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:i,splicedQueue:e}=this.getLogsToUpload();if(i.size===0)return;try{let r=[...i.values()];for(let o=0;o<r.length;o++){let{userId:n,sdkAppId:a,logs:d}=r[o];yield this.uploadLogWithRetry(JSON.stringify({timestamp:cn(),sdkAppId:String(a),userId:n,version:Oe,log:d.map(l=>l.log).join(`
|
|
6
|
-
`)}),a),d.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:()=>Si({url:gi(e,$i.LOG),body:i,timeout:5e3,priority:"low"}),settings:{retries:3,timeout:2e3},onError:({retry:t})=>{t()}})()}getPrefix(i){let e=new Date;return e.setTime(Hs()),`[${dn(e)}] <${Rt[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){T(Rt[i])||(this._logLevel!==i&&this.info("setLogLevel",i),this._logLevel=i)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(i){if(Z(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch(e){return""}}log(i,e,t=!0,r,o){var d;e.unshift(this.getPrefix(i));let n={log:e.reduce((l,u)=>`${l} ${this.logChunkToString(u)}`.trim(),""),level:i,userId:r,sdkAppId:o,forAllJoinedClients:t};if(S.emit(E.LOG,{log:n}),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push(n),i<this._logLevel)return;let a=((d=Rt[i])==null?void 0:d.toLowerCase())||"info";jn.PRINT_LOG_TAG?console[a](jf,qf,Xf,...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;Rt[t]&&(this._logLevelToUpload=t)}getQueue(){return this._queue}};c(jn,"PRINT_LOG_TAG",!(Te||he||Kc));var nd=jn,C=new nd;var zf=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)})},_o=zf;var ad=class{constructor(){c(this,"_prefix","TRTC");c(this,"_queue",new Map)}getRealKey(i){return`${this._prefix}_${i}`}checkStorage(){if(!Ci())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(Ci())try{for(let[i,e]of this._queue)localStorage.setItem(i,JSON.stringify(e))}catch(i){C.warn(i)}}getItem(i){if(!Ci())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(Ci())try{let t={expiresIn:Date.now()+hn,value:e};this._queue.set(this.getRealKey(i),t)}catch(t){C.warn(t)}}deleteItem(i){if(!Ci())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(Ci())try{localStorage.clear()}catch(i){C.warn(i)}}},ls=new ad;var Zt={};mi(Zt,{HTTPS_API:()=>p_,IS_GET_CAPABILITIES_SUPPORTED:()=>Od,IS_GET_SETTINGS_SUPPORTED:()=>Kt,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>Dd,IS_INSERTABLE_STREAM_SUPPORTED:()=>Di,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>oa,IS_RTC_RTP_SENDER_SUPPORTED:()=>Co,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>sa,IS_SEI_SUPPORTED:()=>yo,IS_SPC_SUPPORTED:()=>ms,basis:()=>T_,capabilityCheck:()=>Md,checkSystemRequirementsInternal:()=>ra,decodeSupportStatus:()=>ia,encodeSupportStatus:()=>yd,getBrowserInfo:()=>u_,getDisplayResolution:()=>yh,isAddTransceiverSupported:()=>mt,isBrowserSupported:()=>bd,isGetReceiversSupported:()=>Ar,isGetSendersSupported:()=>Ki,isGetTransceiversSupported:()=>Yt,isGetUserMediaSupported:()=>bh,isMediaDevicesSupported:()=>ta,isMediaSessionSupported:()=>Oh,isMediaStreamTrackProcessorSupported:()=>Nd,isReplaceTrackSupported:()=>vd,isRequestVideoFrameCallbackSupported:()=>Cr,isSIMDSupported:()=>g_,isScreenCaptureApiAvailable:()=>Io,isSelectedCandidatePair:()=>Yi,isSetParametersSupported:()=>Ro,isSmallStreamAPISupported:()=>vh,isSmallStreamSupported:()=>Ao,isStopTransceiverSupported:()=>__,isTRTCSupported:()=>h_,isUnifiedPlanDefault:()=>f_,isUsedInHttpProtocol:()=>vi,isWebAudioSupported:()=>Nh,isWebCodecSupported:()=>Dh,isWebCodecsSupported:()=>Rh,isWebRTCSupported:()=>kd,isWebTransportSupported:()=>kh});var Ed={};mi(Ed,{AUDIO_LEVEL_SCALE:()=>Et,AudioCodecPipelineType:()=>gd,AudioDecoderDowngradeState:()=>ud,AudioPlayerMode:()=>fd,AudioType:()=>ch,BASIC_TYPE:()=>Er,BannedReason:()=>_d,CONNECTION_CLOSED_REASON:()=>dd,ClientEvent:()=>oh,CodecType:()=>mh,ConnectionEvent:()=>Lt,ConnectionState:()=>ht,DECODE_FAILED_ERROR_CODE:()=>Td,FacingMode:()=>Xn,LeaveReason:()=>hh,LocalTrackEvent:()=>go,MULTI_VIDEO_DATA_TYPE:()=>Pt,MediaType:()=>Le,MediaTypeLabel:()=>Qf,MonitorEventId:()=>Eo,MutedFlag:()=>ah,NetworkQualityValue:()=>pd,PlayerState:()=>gr,ReceiveMode:()=>uh,RemoteStreamType:()=>st,RemoteTrackEvent:()=>To,RoomEvent:()=>zi,SceneNumber:()=>ld,StreamEvent:()=>nh,StreamType:()=>lh,SubscribeMediaType:()=>cd,TIMER_TYPE:()=>zt,TRACK_ACTION:()=>md,TRACK_KIND:()=>hd,TrackEvent:()=>bi,UserRole:()=>Ye,UserRoleNumber:()=>Tr,VideoCodec:()=>Qi,VideoCodecPipelineType:()=>Qn,VideoContentHint:()=>us,VideoDecoderDowngradeState:()=>qn,VideoPlayerMode:()=>zn,VideoType:()=>dh});var Lt=(_=>(_.TRACK_ADDED="track-added",_.TRACK_UPDATED="track-updated",_.TRACK_SUBSCRIBED="track-subscribed",_.STREAM_ADDED="stream-added",_.STREAM_REMOVED="stream-removed",_.STREAM_UPDATED="stream-updated",_.STREAM_PUBLISHED="stream-published",_.STREAM_SUBSCRIBED="stream-subscribed",_.STREAM_UNSUBSCRIBED="stream-unsubscribed",_.STATE_CHANGED="state-changed",_.ERROR="error",_.CONNECTION_STATE_CHANGED="connection-state-changed",_.FIREWALL_RESTRICTION="firewall-restriction",_.SEI_MESSAGE="sei-message",_.CLOSED="closed",_))(Lt||{}),dd=(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))(dd||{}),oh=(R=>(R.STREAM_ADDED="stream-added",R.STREAM_REMOVED="stream-removed",R.STREAM_UPDATED="stream-updated",R.STREAM_SUBSCRIBED="stream-subscribed",R.CONNECTION_STATE_CHANGED="connection-state-changed",R.PEER_JOIN="peer-join",R.PEER_LEAVE="peer-leave",R.MUTE_AUDIO="mute-audio",R.MUTE_VIDEO="mute-video",R.UNMUTE_AUDIO="unmute-audio",R.UNMUTE_VIDEO="unmute-video",R.CLIENT_BANNED="client-banned",R.NETWORK_QUALITY="network-quality",R.AUDIO_VOLUME="audio-volume",R.SEI_MESSAGE="sei-message",R.ERROR="error",R))(oh||{}),nh=(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))(nh||{}),go=(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))(go||{}),gr=(t=>(t.PAUSED="PAUSED",t.PLAYING="PLAYING",t.STOPPED="STOPPED",t))(gr||{}),zi=(j=>(j.PEER_JOIN="peer-join",j.PEER_LEAVE="peer-leave",j.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",j.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",j.BANNED="banned",j.NETWORK_QUALITY="network-quality",j.AUDIO_VOLUME="audio-volume",j.SEI_MESSAGE="sei-message",j.ERROR="error",j.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",j.REMOTE_PUBLISHED="remote-published",j.REMOTE_UNPUBLISHED="remote-unpublished",j.FIREWALL_RESTRICTION="firewall-restriction",j.HEARTBEAT_REPORT="heartbeat-report",j.CUSTOM_MESSAGE="custom-message",j.LAYER_DATA="layerData",j.FIRST_VIDEO_FRAME="first-video-frame",j.DUMP="dump",j))(zi||{}),bi=(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))(bi||{}),To=(e=>(e.DECODE_FAILED="decode-failed",e.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",e))(To||{}),ah=(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))(ah||{}),ld=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(ld||{}),Tr=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(Tr||{}),Ye=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(Ye||{}),ht=(o=>(o.CONNECTED="CONNECTED",o.DISCONNECTED="DISCONNECTED",o.CONNECTING="CONNECTING",o.RECONNECTED="RECONNECTED",o.RECONNECTING="RECONNECTING",o))(ht||{}),ud=(r=>(r.INITIALIZED="INITIALIZED",r.STARTING="STARTING",r.STARTED="STARTED",r.FAILED="FAILED",r))(ud||{}),qn=(r=>(r.INITIALIZED="INITIALIZED",r.STARTING="STARTING",r.STARTED="STARTED",r.FAILED="FAILED",r))(qn||{}),hd=(t=>(t.AUDIO="audio",t.VIDEO="video",t.AUXILIARY="auxVideo",t))(hd||{}),md=(e=>(e.ADD="add",e.REMOVE="remove",e))(md||{}),Le=(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))(Le||{}),Qf={1:"audio",2:"auxVideo",4:"video"},ch=(i=>(i[i.opus=111]="opus",i))(ch||{}),dh=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(dh||{}),lh=(e=>(e.Big="big",e.Small="small",e))(lh||{}),st=(e=>(e.Main="main",e.Aux="auxiliary",e))(st||{}),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||{}),Eo=(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))(Eo||{}),pd=(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))(pd||{}),uh=(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))(uh||{}),Xn=(e=>(e.user="user",e.environment="environment",e))(Xn||{}),zn=(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))(zn||{}),fd=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(fd||{}),_d=(r=>(r.BANNED="banned",r.KICK="kick",r.USER_TIME_OUT="user_time_out",r.ROOM_DISBAND="room_disband",r))(_d||{}),hh=(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))(hh||{}),Et=1e8,cd=class{constructor(){c(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)}},Er=(o=>(o.String="string",o.Number="number",o.Boolean="boolean",o.Array="array",o.Object="object",o))(Er||{}),Qi=(t=>(t.H264="h264",t.H265="h265",t.VP8="vp8",t))(Qi||{}),Qn=(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))(Qn||{}),gd=(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))(gd||{}),mh=(t=>(t.WebRTC="webrtc",t.WebCodecs="webcodecs",t.WebAssembly="webassembly",t))(mh||{}),Td=(f=>(f[f.SUCCESS=0]="SUCCESS",f[f.FAILED=1]="FAILED",f[f.WEBCODEC_INIT=2]="WEBCODEC_INIT",f[f.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",f[f.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",f[f.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",f[f.WASM_INIT=6]="WASM_INIT",f[f.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",f[f.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",f[f.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",f[f.TEST=10]="TEST",f[f.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",f))(Td||{}),us=(r=>(r.NONE="",r.DETAIL="detail",r.MOTION="motion",r.TEXT="text",r))(us||{}),zt=(o=>(o.INTERVAL="interval",o.TIMEOUT="timeout",o.RAF="raf",o.RIC="ric",o.INTERVAL_IN_WORKER="intervalInWorker",o))(zt||{});var U={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"},Pe={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: ${ye(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: ${ye(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 ph=(s,i)=>i?`${Ht}/${s}/${i}`:`${Ht}/${s}/index.html`;var Yf=()=>{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(bc);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="";ce(Pe[i])?o=Pe[i](e):Z(Pe[i])&&(o=Pe[i]);let{TRTC_ERROR_INFO:d,TRTC_ERROR_LINK:l}=Yf();t?a=`${t.className}.html#${t.fnName}`:l&&l[i]&&(ce(l[i])?a=l[i](e):Z(l[i])&&(a=l[i]));let u=o;return bt()&&(d&&d[i]&&(ce(d[i])?n=d[i](e):Z(d[i])&&(n=d[i])),n&&(r?u=`${n}
|
|
7
|
-
\u8BF7\u67E5\u770B\u6587\u6863: ${ph("zh-cn",a)}
|
|
3
|
+
`}});var vh=En(Br=>{"use strict";var Uo=Ah(),m_=Rh(),p_=qc();Br.grammar=p_;Br.write=m_;Br.parse=Uo.parse;Br.parseParams=Uo.parseParams;Br.parseFmtpConfig=Uo.parseFmtpConfig;Br.parsePayloads=Uo.parsePayloads;Br.parseRemoteCandidates=Uo.parseRemoteCandidates;Br.parseImageAttributes=Uo.parseImageAttributes;Br.parseSimulcastStreamList=Uo.parseSimulcastStreamList});var Mp=(Y=>(Y[Y.INVALID_PARAMETER=4096]="INVALID_PARAMETER",Y[Y.INVALID_OPERATION=4097]="INVALID_OPERATION",Y[Y.NOT_SUPPORTED=4098]="NOT_SUPPORTED",Y[Y.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",Y[Y.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",Y[Y.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",Y[Y.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",Y[Y.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",Y[Y.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",Y[Y.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",Y[Y.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",Y[Y.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",Y[Y.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",Y[Y.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",Y[Y.CLIENT_BANNED=16448]="CLIENT_BANNED",Y[Y.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",Y[Y.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",Y[Y.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",Y[Y.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",Y[Y.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",Y[Y.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",Y[Y.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",Y[Y.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",Y[Y.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",Y[Y.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",Y[Y.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",Y[Y.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",Y[Y.API_CALL_ABORTED=16461]="API_CALL_ABORTED",Y[Y.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",Y[Y.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",Y[Y.UNKNOWN=65535]="UNKNOWN",Y))(Mp||{}),q=Mp;var jg=function(i){for(let t in q)if(q[t]===i)return t;return"UNKNOWN"},Pu=class extends Error{constructor({name:e="RtcError",message:r,code:o=q.UNKNOWN,extraCode:s=0,constraint:n}){let d=`<${jg(o)} 0x${o.toString(16)}>`,m=`${r}${n?` constraint: ${n}`:""}${r!=null&&r.includes(d)?"":` ${d}`}`;super(m);u(this,"code");u(this,"extraCode");u(this,"message");u(this,"originMessage");u(this,"name");u(this,"constraint");this.code=o,this.extraCode=s,this.name=e,this.message=m,this.constraint=n,this.originMessage=r}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},ae=Pu;var FS=new Date().getTime(),qg=0;var _n=function(){return new Date().getTime()+qg},ic=function(){let i=new Date;return i.setTime(_n()),i.toLocaleString()},oc=function(i){let t=String(i.getMilliseconds());return"padStart"in String.prototype&&(t=t.toString().padStart(3,"0")),`${i.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${t}`};var Ur={};Yr(Ur,{bytes2ms:()=>Bp,convertObjectNumberToInt:()=>wn,copyProperties:()=>$p,deepClone:()=>Do,deepMerge:()=>Lr,delay:()=>Mn,fibonacci:()=>No,formatedTime:()=>fc,getConstructorName:()=>Ts,getContainerFromElement:()=>Xp,getEnv:()=>Up,getInternalVersion:()=>zp,getLoggerUrl:()=>ti,getMediaStreamTrackInfo:()=>Ic,getMuteStateFromFlag:()=>Nn,getNetworkType:()=>vn,getNumNetworkType:()=>hc,getReconnectionTimeout:()=>Wp,getStringByteLength:()=>Qp,getTurnServer:()=>Jp,getUint32Version:()=>_c,getValueType:()=>nt,getViewListFromView:()=>ys,glog:()=>Cn,ipv4ToUint32:()=>Ss,isArray:()=>it,isAudioWorkletSupported:()=>qp,isBoolean:()=>dt,isConstructor:()=>wo,isEmpty:()=>Is,isFunction:()=>He,isLangChinese:()=>_r,isMediaStreamTrack:()=>Gp,isNumber:()=>We,isObject:()=>Er,isOverseaSdkAppId:()=>Rn,isPlainObject:()=>xt,isPortrait:()=>Ec,isPromise:()=>Ui,isRemoteTrack:()=>jp,isString:()=>ve,isUndefined:()=>V,loadImage:()=>As,ms2bytes:()=>Hp,ms2samples:()=>ju,normalizeUrl:()=>Mo,performanceNow:()=>Te,promiseAny:()=>Dn,samples2ms:()=>Gu,setNetworkType:()=>Fp,stringify:()=>ar,stringifyIncludeValue:()=>gc,throttlePromise:()=>Tc});var Wu={};Yr(Wu,{AUDIO_MUTE_BIT:()=>uc,AUDIO_STAT_BIT:()=>Es,AUX_STAT_BIT:()=>Sn,AUX_STREAM_MSID:()=>oE,BACKEND_ENV:()=>dc,BASE_DOC_URL:()=>Pr,BASE_HOST:()=>Op,CAPABILITIES_KEYS:()=>pc,CLASS_NAME:()=>DE,CLOUD_CONSOLE_URL:()=>Qg,CROSS_ROOM_BIT:()=>rE,DATA_FREEZE_TIMING:()=>mc,DEFAULT_ASSETS_URL:()=>sc,DOC_URL:()=>Yg,DTLS_STATE_UNKNOWN:()=>hE,ENV_NAME:()=>Zr,EXCHANGE_SDP_TIMEOUT:()=>IE,IS_WORKER:()=>fs,IS_WORKLET:()=>Tn,KIBANA_EVENT:()=>Kr,LOCAL_STREAM_PUBLISH_STATE:()=>xp,LOGGER_CMD_TYPE:()=>Li,LOGGER_DOMAIN:()=>Lu,LOGGER_DOMAIN_OVERSEA:()=>Uu,LOG_LEVEL:()=>gr,LOG_LEVEL_NAME:()=>wE,MAIN_STREAM_MSID:()=>iE,MAX_RTT:()=>An,MICROPHONE_COMMUNICATIONS:()=>NE,MICROPHONE_DEFAULT:()=>Co,MUTE_ALL_BIT:()=>tE,NAME:()=>N,NETWORK_TYPE:()=>vo,NOT_SUPPORTED_H264:()=>yE,PAUSED_RETRY_COUNT:()=>Hu,PEERCONNECTION_CONNECTING_TIMEOUT:()=>vE,PEER_CONNECTION_STATE:()=>fE,PEER_LEAVE_REASON:()=>kp,RECOVER_CAPTURE_INTERVAL:()=>_s,REMOTE_STREAM_TYPE_AUX:()=>nE,REMOTE_STREAM_TYPE_MAIN:()=>sE,RENDER_FREEZE_TIMING:()=>AE,SCHEDULE_DOMAIN:()=>ei,SCHEDULE_TIMEOUT:()=>CE,SDP_SEMANTICS_PLAN_B:()=>SE,SDP_SEMANTICS_UNIFIED_PLAN:()=>Bu,SECOND_HOST:()=>Jg,SIGNAL_PING_PONG_INTERVAL:()=>Kg,SIGNAL_PING_TIMEOUT:()=>Zg,SIGNAL_RECONNECTION_COUNT:()=>EE,SMALL_STAT_BIT:()=>Fu,SPEAKER_DEFAULT:()=>yn,STORAGE_EXPIRES_TIME:()=>nc,STREAM_TYPE_BIG:()=>bE,STREAM_TYPE_SMALL:()=>RE,SUBSCRIBE_SMALL_RETRY_COUNT:()=>ME,SYNC_USER_LIST_INTERVAL:()=>_E,Scene:()=>kr,THIRD_HOST:()=>Xg,TRANSPORT_DIRECTION:()=>eE,TRTC_ERROR_ASSISTANCE:()=>Vu,TRTC_QUALITY_BAD:()=>lE,TRTC_QUALITY_DISCONNECTED:()=>pE,TRTC_QUALITY_EXCELLENT:()=>cE,TRTC_QUALITY_GOOD:()=>dE,TRTC_QUALITY_POOR:()=>uE,TRTC_QUALITY_UNKNOWN:()=>aE,TRTC_QUALITY_VERY_BAD:()=>mE,UPDATE_OFFER_TIMEOUT:()=>TE,VIDEO_MUTE_BIT:()=>lc,VIDEO_STAT_BIT:()=>gs,audioProfileMap:()=>ac,getRetryCount:()=>gE,getScriptDir:()=>zg,innerVersion:()=>xu,loggerProxy:()=>In,screenProfileMap:()=>cc,setLoggerProxy:()=>Ro,setRetryCount:()=>$u,setVersion:()=>ku,version:()=>st,videoProfileMap:()=>xr});var xu="4.15.00.1600",st="5.0.0";function ku(i){st=i;let[t,e,r]=i.split(".").map(o=>parseInt(o,10));xu=`${t}.${Math.min(15,e)}.${Math.min(15,r)}.${e.toString().padStart(2,"0")}${r.toString().padStart(2,"0")}`}var fs=typeof importScripts!="undefined",Tn=typeof registerProcessor!="undefined",zg=()=>{let i=fs?self.location.href:document.currentScript.src;return i.substring(0,i.lastIndexOf("/")+1)},In="",Ro=i=>In=i,Op="web.sdk.qcloud.com",Jg="web.sdk.tencent.cn",Xg="web.sdk.cloud.tencent.cn",Qg="https://console.cloud.tencent.com/trtc",Pr=`https://${Op}/trtc/webrtc/v5/doc`,sc="https://web.sdk.qcloud.com/trtc/webrtc/v5/assets/",Yg=`${Pr}/zh-cn/`,Lu="https://yun.tim.qq.com",Uu="https://apisgp.my-imcloud.com",Vu="trtc_error_assistance",Li={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},Zr={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},gr=(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))(gr||{}),Zg=18e3,Kg=2e3,vo={unknown:0,wifi:1,"3g":2,"2g":3,"4g":4,wired:5,"5g":6},nc=7*24*3600*1e3,ac={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}},xr={"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}},cc={"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}},N={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"},eE={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},dc={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},kr=(e=>(e.LIVE="live",e.RTC="rtc",e))(kr||{}),gs=1,Fu=2,Sn=4,Es=8,uc=64,lc=16,tE=112,rE=128,iE="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",oE="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",sE=N.MAIN,nE=N.AUXILIARY,aE=0,cE=1,dE=2,uE=3,lE=4,mE=5,pE=6,hE="unknown",fE={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Pp=1/0;function $u(i){Pp=i}function gE(){return Pp}var EE=30,Kr={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"},_E=1e4,TE=1e4,IE=1e4,Bu="unified-plan",SE="plan-b",yE=1028,xp=(r=>(r[r.UNPUBLISH=-1]="UNPUBLISH",r[r.PUBLISHING=0]="PUBLISHING",r[r.PUBLISHED=1]="PUBLISHED",r))(xp||{}),mc=500,AE=1e3,bE=N.BIG,RE=N.SMALL,vE=10*1e3,ei={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"},CE=2e3,DE={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},Hu=5,Co="default",yn=Co,NE="communications",wE=Object.keys(gr),kp=["normal leave","timeout leave","kick","role change"],ME=10,_s=2e3,pc=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],An=10*1e3;var Up=function(){return new URLSearchParams(location.search).get("trtc_env")||""},Rn=i=>Number(i)<14e8,ti=function(i,t){let e;In?e=In:e=Rn(i)?Uu:Lu;let r=Math.floor(Math.random()*gn(2,31));return`${e}/v5/AVQualityReportSvc/C2S?random=${r}&sdkappid=${i}&cmdtype=${t}`},bn="unknown";function vn(){if(bn!=="unknown")return bn;let{userAgent:i,connection:t}=navigator,e=(i.match(/NetType\/\S+/)||[])[0]||"";e=e.toLowerCase().replace("nettype/",""),e==="3gnet"&&(e="3g");let r=t&&t.type&&t.type.toLowerCase(),o=t&&t.effectiveType&&t.effectiveType.toLowerCase();return o==="slow-2"&&(o="2g"),r&&(bn=Vp(r,o)),bn}function Vp(i,t){if(vo[i])return i;switch(i){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";case"none":case"other":default:return"unknown"}}function Fp(i){bn=Vp(i)}function hc(){return vo[vn()]}function $p(i,t){for(let e of Reflect.ownKeys(t))if(e!=="constructor"&&e!=="prototype"&&e!=="name"){let r=Object.getOwnPropertyDescriptor(t,e)||"";Object.defineProperty(i,e,r)}return i}function Bp(i,t=48e3){return Gu(i/4,t)}function Gu(i,t=48e3){return i*1e3/t}function Hp(i,t=48e3){return ju(i,t)*4}function ju(i,t=48e3){return i*t/1e3}var Cn=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{},_r=()=>{let i=navigator.language;return i=i.substring(0,2),i==="zh"},xt=function(i){if(!i||typeof i!="object"||Object.prototype.toString.call(i)!="[object Object]")return!1;let t=Object.getPrototypeOf(i);if(t===null)return!0;let e=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function No(i,t=1,e=1){return i<=1?e:No(i-1,e,t+e)}function Wp(i){return i>8?30*1e3:No(i)*1e3}function nt(i){return Reflect.apply(Object.prototype.toString,i,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var He=i=>typeof i=="function",V=i=>typeof i=="undefined",ve=i=>typeof i=="string",We=i=>typeof i=="number",dt=i=>typeof i=="boolean",Er=i=>nt(i)==="object",it=i=>nt(i)==="array",Gp=i=>nt(i)==="MediaStreamTrack".toLowerCase(),jp=i=>i.isRemote,Ui=i=>nt(i)==="promise",wo=i=>He(i)&&i.prototype.constructor===i,Ts=i=>wo(i)?i.prototype.constructor.name:"",qp=typeof AudioWorkletNode!="undefined";function Dn(i){return new Promise((t,e)=>{let r=[];i.forEach(o=>{o.then(t).catch(s=>{r.push(s),r.length===i.length&&e(r)})})})}function Te(){return!performance||!performance.now?Date.now():Math.floor(performance.now())}var Lp=i=>+i<10?`0${i}`:i,zp=i=>{let t=i.match(/^\d+\.\d+\.\d+/)[0];if(!t)return i;let e=t.split("."),r=Lp(e[1])+Lp(e[2]);return e[1]-15>0&&(e[1]="15"),e[2]-15>0&&(e[2]="15"),`${e.join(".")}.${r}`},OE=Object.prototype.hasOwnProperty,{toString:GS}=Object.prototype;function Is(i){if(i==null)return!0;if(typeof i=="boolean")return!1;if(typeof i=="number")return i===0;if(typeof i=="string"||typeof i=="function"||Array.isArray(i))return i.length===0;if(i instanceof Error)return i.message==="";if(xt(i))switch(Object.prototype.toString.call(i)){case"[object File]":case"[object Map]":case"[object Set]":return i.size===0;case"[object Object]":{for(let t in i)if(OE.call(i,t))return!1;return!0}}return!1}function Nn(i,t){return{userId:t,hasAudio:!!(i&Es),hasVideo:!!(i&gs),hasAuxiliary:!!(i&Sn),hasSmall:!!(i&Fu),audioMuted:!!(i&uc),videoMuted:!!(i&lc),audioAvailable:!!(i&Es)&&!(i&uc),videoAvailable:!!(i&gs)&&!(i&lc)}}function Jp(i){let t={urls:i.url.startsWith("turn:")||i.url.startsWith("turns:")?i.url:`turn:${i.url}`};return!V(i.username)&&!V(i.credential)&&(t.username=i.username,t.credential=i.credential,t.credentialType="password",V(i.credentialType)||(t.credentialType=i.credentialType)),t}function Ss(i,t=!0){if(!ve(i))return 0;let e=i.split(".");return t?(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 Lr=function(i,t,e,r){if(!(Er(i)&&Er(t)))return 0;let o=0,s=Object.keys(t),n;for(let d=0,m=s.length;d<m;d++)if(n=s[d],!(V(t[n])||e&&e.includes(n)))if(Er(i[n])&&Er(t[n]))o+=Lr(i[n],t[n],e,r);else{if(r&&r.includes(t[n]))continue;i[n]!==t[n]&&(i[n]=Do(t[n]),o+=1)}return o};function Do(i){if(it(i)){let t=[];return i.forEach((e,r)=>{t[r]=Do(e)}),t}if(Er(i)){let t={};return Object.keys(i).forEach(e=>{t[e]=Do(i[e])}),t}return i}var ys=i=>{let t=[];if(it(i))t=[...i];else if(ve(i)){let e=document.getElementById(i);e&&t.push(e)}else i&&t.push(i);return t},Xp=i=>ve(i)?document.getElementById(i):i,PE=i=>{let t=m=>m<10?`0${m}`:`${m}`,e=i.getFullYear(),r=i.getMonth()+1,o=i.getDate(),s=t(i.getHours()),n=t(i.getMinutes()),d=t(i.getSeconds());return`${e}/${r}/${o} ${s}:${n}:${d}`},fc=()=>PE(new Date);function ar(i,{keysToInclude:t,keysToExclude:e}){try{if(it(i))return`[${i.map(n=>ar(n,{keysToInclude:t,keysToExclude:e})).join(",")}]`;if(!xt(i)||!it(t)&&!it(e))return JSON.stringify(i);let r={},o=new Set(t),s=new Set(e);return Object.keys(i).forEach(n=>{(s.size===0&&o.has(n)||o.size===0&&!s.has(n))&&(r[n]=xt(i[n])||it(i[n])?JSON.parse(ar(i[n],{keysToExclude:e,keysToInclude:t})):i[n])}),JSON.stringify(r)}catch(r){return"{}"}}function gc(i,t=!1){let e=[];return Object.keys(i).forEach(r=>{t===i[r]&&e.push(r)}),ar(i,{keysToInclude:e})}function Qp(i){return i.replace(/[\u4e00-\u9fa5]/g,"aa").length}var Ec=()=>{var i,t,e,r;return(i=window.screen)!=null&&i.orientation?!!((r=(e=(t=window.screen)==null?void 0:t.orientation)==null?void 0:e.type)!=null&&r.includes("portrait")):window.orientation===0||window.orientation===180},As=i=>A(void 0,null,function*(){return new Promise((t,e)=>{let r;if(ve(i))r=new Image,r.crossOrigin="anonymous",r.src=i;else if(r=i,r.complete){t(r);return}r.onload=()=>t(r),r.onerror=()=>{e(new ae({code:q.INVALID_PARAMETER,message:`load image failed, url: ${i}`}))}})}),_c=i=>{let t=i.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]<<0},wn=i=>(Object.keys(i).forEach(t=>{We(i[t])&&(t.startsWith("uint")||t.startsWith("int"))?i[t]=Math.floor(i[t]):(xt(i[t])||it(i[t]))&&wn(i[t])}),i);function Mn(i,t){return new Promise(e=>{let r=setTimeout(e,i);t&&t(r)})}function Tc(i,t){let e=null;return function(...r){return e||(e=i.apply(t||this,r),e.finally(()=>e=null),e)}}function Mo(i){return i.replace(/(^|[^:])\/{2,}/g,"$1/")}function Ic(i){var t;try{let{width:e,height:r,frameRate:o,sampleRate:s,sampleSize:n,channelCount:d}=(t=i.getSettings)==null?void 0:t.call(i),m=i.kind===N.AUDIO?`${s}x${n}@${d}`:`${e}x${r}@${o}`,l=i.stats?` stats: ${JSON.stringify(i.stats).replaceAll('"',"")}`:"";return`${i.id} ${i.readyState} muted:${i.muted} ${i.kind} ${i.label} ${m}${l}`}catch(e){return""}}function ri({url:i,body:t,method:e="POST",timeout:r,priority:o}){return new Promise((s,n)=>{if("fetch"in window)return fetch(i,{method:e,body:t,priority:o}).then(m=>m.text()).then(m=>{try{s({data:JSON.parse(m)})}catch(l){s({data:m})}},n);let d=new XMLHttpRequest;d.onreadystatechange=()=>{if(d.readyState===4)if(d.status>=200&&d.status<300)try{let m=JSON.parse(d.response);s({data:m})}catch(m){s({data:d.response})}else n({status:d.status,statusText:d.statusText||"request failed!"})},d.timeout=r||5e3,d.open(e,i,!0),d.send(t)})}function qu(i){return A(this,null,function*(){let t=Te(),e=JSON.stringify(i);try{if(!CompressionStream||e.length<=2800)return e;let o=new Blob([e],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),d=yield(yield(yield new Response(o)).blob()).arrayBuffer();return F.debug(`compressJSON ${e.length} -> ${d.byteLength} ${Te()-t}ms`),d}catch(r){return e}})}var xE=Object.prototype.hasOwnProperty;var Vi=i=>typeof i=="function",Yp=i=>typeof i=="undefined";var Zp=i=>typeof i=="boolean";var zu=i=>i.isRemote;var kE=function(i){if(!i||typeof i!="object"||Object.prototype.toString.call(i)!="[object Object]")return!1;let t=Object.getPrototypeOf(i);if(t===null)return!0;let e=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&Function.prototype.toString.call(e)===Function.prototype.toString.call(Object)};function Kp(i){if(i==null)return!0;if(typeof i=="boolean")return!1;if(typeof i=="number")return i===0;if(typeof i=="string"||typeof i=="function"||Array.isArray(i))return i.length===0;if(i instanceof Error)return i.message==="";if(kE(i))switch(Object.prototype.toString.call(i)){case"[object File]":case"[object Map]":case"[object Set]":return i.size===0;case"[object Object]":{for(let t in i)if(xE.call(i,t))return!1;return!0}}return!1}var LE=0,UE=1,eh=2;function VE({retryFunction:i,settings:t,onError:e,onRetrying:r,onRetryFailed:o,onRetrySuccess:s,context:n}){return function(...d){let{retries:m=5,timeout:l=1e3}=t,g=0,_=-1,S=LE,v=(x,P)=>A(this,null,function*(){let M=n||this;try{let G=yield i.apply(M,d);g>0&&s&&s.call(this,g),g=0,x(G)}catch(G){let se=()=>{clearTimeout(_),g=0,S=eh,P(G)},ne=()=>{S!==eh&&g<(Vi(m)?m():m)?(g++,S=UE,Vi(r)&&r.call(this,g,se),_=window.setTimeout(()=>{_=-1,v(x,P)},Vi(l)?l(g):l)):(se(),Vi(o)&&o.call(this,G))};Vi(e)?e.call(this,{error:G,retry:ne,reject:P,retryFuncArgs:d,retriedCount:g}):ne()}});return new Promise(v)}}var Fi=VE;var bs=class{constructor(t){u(this,"userId");u(this,"remoteUserId");u(this,"id");u(this,"sdkAppId");u(this,"type");u(this,"isLocal");this.id=t.id,this.userId=t.userId,this.sdkAppId=t.sdkAppId,this.remoteUserId=t.remoteUserId,this.isLocal=Zp(t.isLocal)?t.isLocal:!0,this.type=this.isLocal?"":t.type}createChild(t){return Object.setPrototypeOf(t,this)}setUserId(t){this.userId=t}setSdkAppId(t){this.sdkAppId=t}log(t,e){let r=this.isLocal?this.userId:this.remoteUserId;e.unshift(`[${this.isLocal?"\u2191":"\u2193"}${this.type&&this.type!=="main"?"*":""}${this.id}${r?`|${r}`:""}]`),F.log(t,e,Yp(this.userId)||Kp(this.userId),this.userId,this.sdkAppId)}info(...t){this.log(2,t)}debug(...t){this.log(1,t)}warn(...t){this.log(3,t)}error(...t){this.log(4,t)}};var ks={};Yr(ks,{ANDROID_VERSION:()=>Qu,CHROME_MAJOR_VERSION:()=>oi,CHROME_VERSION:()=>Vc,EDGE_VERSION:()=>yc,EDG_MAJOR_VERSION:()=>Zu,EDG_VERSION:()=>Ac,FIREFOX_MAJOR_VERSION:()=>Yu,FIREFOX_VERSION:()=>Sc,HUAWEI_VERSION:()=>Pc,IE_VERSION:()=>WE,IOS_MAIN_VERSION:()=>er,IOS_VERSION:()=>Hi,IPADQQB_VERSION:()=>Mc,IS_ANDROID:()=>ut,IS_ANDROID_WEBVIEW:()=>zE,IS_ANY_SAFARI:()=>Bi,IS_CHROME:()=>Ps,IS_CHROME_OS:()=>Ku,IS_CHROMIUM_BASE:()=>ii,IS_DESKTOP_IOS_CHROME:()=>al,IS_EDG:()=>Ds,IS_EDGE:()=>Cs,IS_ELECTRON:()=>jE,IS_FIREFOX:()=>Ht,IS_HEADLESS_CHROME:()=>ol,IS_HONOR:()=>rl,IS_HUAWEI:()=>tl,IS_HUAWEIBROWSER:()=>Fn,IS_IE:()=>oh,IS_IE8:()=>HE,IS_IOS:()=>mt,IS_IOS_13_OR_14:()=>nl,IS_IOS_15_1:()=>sl,IS_IOS_CHROME:()=>sh,IS_IPAD:()=>vs,IS_IPADQQB:()=>Ln,IS_IPAD_PRO:()=>Xu,IS_IPHONE:()=>$i,IS_IPOD:()=>ih,IS_LINUX:()=>Un,IS_LOCAL:()=>yr,IS_MAC:()=>Sr,IS_MACQQB:()=>kn,IS_MIBROWSER:()=>Vn,IS_MQQB:()=>Os,IS_NATIVE_ANDROID:()=>BE,IS_OLD_ANDROID:()=>$E,IS_OPENHARMONY:()=>il,IS_OPPOBROWSER:()=>Bn,IS_SAFARI:()=>At,IS_SAFARI_15_1:()=>XE,IS_SAMSUNGBROWSER:()=>$n,IS_SOGOU:()=>Pn,IS_SOGOUM:()=>On,IS_TBS:()=>Ir,IS_UCBROWSER:()=>el,IS_VIVOBROWSER:()=>Hn,IS_WECHAT:()=>ws,IS_WIN:()=>Oo,IS_WQQB:()=>xn,IS_WX:()=>GE,IS_X5MQQB:()=>Ms,IS_XWEB:()=>Ns,MACQQB_VERSION:()=>wc,MI_VERSION:()=>Oc,MQQB_VERSION:()=>Rs,OPENHARMONY_VERSION:()=>qE,OPPO_VERSION:()=>kc,SAFARI_VERSION:()=>si,SAMSUNG_VERSION:()=>xc,SOGOUM_VERSION:()=>bc,SOGOU_VERSION:()=>Rc,TBS_VERSION:()=>vc,UA_DATA_STRING:()=>Tr,USER_AGENT:()=>Kt,VIVO_VERSION:()=>Lc,WECHAT_VERSION:()=>Dc,WQQB_VERSION:()=>Nc,XWEB_VERSION:()=>Cc,browserInfo:()=>Vr,getBrowserInfo:()=>nh,getChromeMajorVersion:()=>Uc,getDeviceModel:()=>Gn,getGPUInfo:()=>dl,getOSName:()=>xs,getOSNumber:()=>jn,getOSString:()=>Po,getOSType:()=>ll,getTerminalType:()=>ul,getUserAgentData:()=>Wn,isLocalStorageEnabled:()=>ni,isMobile:()=>cl,isVersionSmallerThan:()=>JE});var Kt=typeof navigator=="undefined"?"":navigator.userAgent,Ie=i=>new RegExp(i,"i").test(Kt),ft=i=>{if(Ie(i)){let t=new RegExp(`${i}\\/([\\d.]+)`),e=Kt.match(t);if(e&&e[1])return e[1]}return""},Ju=i=>{if(Ie(i)){let t=new RegExp(`${i}\\/(\\d+)`),e=Kt.match(t);if(e&&e[1])return parseFloat(e[1])}return NaN},th=/AppleWebKit\/([\d.]+)/i.exec(Kt),FE=th?parseFloat(th[1]):NaN,vs=Ie("iPad"),Xu=typeof navigator!="undefined"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Ie("Macintosh"),$i=Ie("iPhone")&&!vs,ih=Ie("iPod"),mt=$i||vs||ih||Xu,ut=Ie("Android"),Qu=function(){if(ut){let i=Kt.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(i){let t=i[1]&&parseFloat(i[1]),e=i[2]&&parseFloat(i[2]);if(t&&e)return parseFloat(`${i[1]}.${i[2]}`);if(t)return t}}return NaN}(),$E=ut&&Ie("webkit")&&Qu<2.3,BE=ut&&Qu<5&&FE<537,Ht=Ie("Firefox"),Sc=ft("Firefox"),Yu=Ju("Firefox"),Cs=Ie("Edge"),yc=ft("Edge"),Ds=Ie("Edg"),Ac=ft("Edg"),Zu=Ju("Edg"),On=Ie("SogouMobileBrowser"),bc=ft("SogouMobileBrowser"),Pn=Ie("MetaSr\\s"),Rc=ft("MetaSr\\s"),Ir=Ie("TBS"),vc=ft("TBS"),Ns=Ie("XWEB"),Cc=ft("XWEB"),HE=Ie("MSIE\\s8\\.0"),oh=Ie("MSIE\\/\\d+"),WE=function(){if(oh){let i=/MSIE\s(\d+)\.\d/.exec(Kt),t=i&&parseFloat(i[1]);return!t&&/Trident\/7.0/i.test(Kt)&&/rv:11.0/.test(Kt)&&(t=11),t}return NaN}(),ws=Ie("(micromessenger|webbrowser)"),Dc=ft("MicroMessenger"),Ms=!Ir&&Ie("MQQBrowser")&&Ie("COVC"),Os=!Ir&&Ie("MQQBrowser")&&!Ie("COVC"),Rs=Os||Ms?ft("MQQBrowser"):"",xn=!Ir&&Ie(" QQBrowser"),Nc=ft(" QQBrowser"),kn=!Ir&&Ie("QQBrowserLite"),wc=ft("QQBrowserLite"),Ln=!Ir&&Ie("MQBHD"),Mc=ft("MQBHD"),Oo=Ie("Windows"),Sr=!mt&&Ie("MAC OS X"),Un=!ut&&Ie("Linux"),Ku=Ie("CrOS"),GE=Ie("MicroMessenger"),el=Ie("UCBrowser"),jE=Ie("Electron"),Vn=Ie("MiuiBrowser"),Oc=ft("MiuiBrowser"),Fn=Ie("HuaweiBrowser"),tl=Ie("Huawei")||Ie("HUAWEI"),rl=Ie("Honor")||Ie("HONOR"),Pc=ft("HuaweiBrowser"),$n=Ie("SamsungBrowser"),xc=ft("SamsungBrowser"),Bn=Ie("HeyTapBrowser"),kc=ft("HeyTapBrowser"),Hn=Ie("VivoBrowser"),Lc=ft("VivoBrowser"),il=Ie("OpenHarmony"),qE=ft("OpenHarmony"),Uc=()=>Ju("Chrome"),ii=Ie("Chrome"),Ps=!Cs&&!Pn&&!On&&!Ir&&!Ns&&!Ds&&!xn&&!Vn&&!Fn&&!$n&&!Bn&&!Hn&&ii,ol=Ie("HeadlessChrome"),oi=Uc(),Vc=ft("Chrome"),At=!ii&&!Os&&!Ms&&!kn&&!Ln&&Ie("Safari"),Bi=At||mt,si=ft("Version"),zE=/Android.*(wv|.0.0.0)/.test(Kt),Hi=(()=>{if(Xu)return si;if(mt){let i=Kt.match(/OS (\d+)_(\d+)/i);if(i&&i[1]){let t=i[1];return i[2]&&(t+=`.${i[2]}`),t}}return""})();function JE(i,t){let e=i.split(".").map(o=>Number(o)),r=t.split(".").map(o=>Number(o));for(let o=0;o<Math.max(e.length,r.length);o++){let s=e[o]||0,n=r[o]||0;if(s<n)return!0;if(s>n)return!1}return!1}var er=Number(Hi.split(".")[0]),XE=si==="15.1",sl=Hi==="15.1",nl=(()=>{let i=Number(Hi.split(".")[0]);return i===14||i===13})(),sh=Ie("CriOS"),al=sh&&si==="11.1.1",yr=typeof location=="undefined"?!1:location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1",ni=(()=>{let i;return()=>{if(typeof i=="undefined")try{i=!!window.localStorage}catch(t){i=!1}return i}})(),Vr=nh();function nh(){let i=new Map([[Ht,["Firefox",Sc]],[Ds,["Edg",Ac]],[Ps,["Chrome",Vc]],[At,["Safari",si]],[Ir,["TBS",vc]],[Ns,["XWEB",Cc]],[ws&&$i,["WeChat",Dc]],[xn,["QQ(Win)",Nc]],[Os,["QQ(Mobile)",Rs]],[Ms,["QQ(Mobile X5)",Rs]],[kn,["QQ(Mac)",wc]],[Ln,["QQ(iPad)",Mc]],[Vn,["MI",Oc]],[Fn,["HW",Pc]],[$n,["Samsung",xc]],[Bn,["OPPO",kc]],[Hn,["VIVO",Lc]],[Cs,["EDGE",yc]],[On,["SogouMobile",bc]],[Pn,["Sogou",Rc]]]),t="unknown",e="unknown";return i.has(!0)&&([t,e]=i.get(!0)),{name:t,version:e}}var Ge=null;function cl(){return Ge&&typeof Ge.mobile=="boolean"?Ge.mobile:ut||mt||$i||vs||il}var Tr="";function Wn(){return A(this,null,function*(){if(Ge)return Ge;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return Ge=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]),Ge&&!Tr&&(Tr=`UAData: ${Ge.platform}/${Ge.platformVersion}`,Ge.architecture&&Ge.bitness&&(Tr+=` ${Ge.architecture}/${Ge.bitness}`),Ge.mobile&&(Tr+=" mobile"),Ge.model&&(Tr+=` model: ${Ge.model.replace(/\s+/g,"/")}`),Ge.fullVersionList&&(Tr+=` ${Ge.fullVersionList.filter(i=>i.brand!=="Not/A)Brand").map(i=>`${i.brand}/${i.version}`).join(",")}`)),Ge}catch(i){return null}})}function dl(){try{let i=document.createElement("canvas"),t=i.getContext("webgl")||i.getContext("experimental-webgl");if(!t)return"";let e=t.getExtension("WEBGL_debug_renderer_info");if(e){let r=t.getParameter(e.UNMASKED_VENDOR_WEBGL),o=t.getParameter(e.UNMASKED_RENDERER_WEBGL);return`${r} ${o}`}return""}catch(i){return""}}function Gn(){return(Ge==null?void 0:Ge.model)||""}var rh=new Map([[ut,"Android"],[mt,"iOS"],[Oo,"Windows"],[Sr,"MacOS"],[Un,"Linux"],[Ku,"ChromeOS"]]),xs=function(){return rh.get(!0)?rh.get(!0):Ge?Ge.platform:"unknown"};function jn(){return Oo?1:ut?2:Sr?3:mt?4:Un?5:Ku?6:0}var Po=()=>{let i=xs();return i+=`/${Vr.name}/${At?Vr.version:Vr.version.split(".")[0]}`,Ge!=null&&Ge.platformVersion&&(i+=`/${Ge.platformVersion}`),Ge!=null&&Ge.architecture&&(i+=`/${Ge.architecture}`),i};function ul(){return ut?4:$i?2:vs?3:Sr?12:Oo?5:Un?13:il?22:1}function ll(){return ut?"Android":$i?"iPhone":vs?"iPad":Sr?"Mac":Oo?"Windows":Un?"Linux":"unknown"}var ch=ki(Wi(),1),ZE=new ch.default,L=ZE;var Gi=(le=>(le.ROOM_DESTROY="1",le.JOIN_START="21",le.JOIN_SCHEDULE_SUCCESS="22",le.JOIN_SIGNAL_CONNECTION_START="23",le.JOIN_SIGNAL_CONNECTION_END="24",le.JOIN_SEND_CMD="25",le.JOIN_RECEIVED_CMD_RES="26",le.JOIN_SUCCESS="27",le.JOIN_FAILED="28",le.LEAVE_START="51",le.LEAVE_SEND_CMD="52",le.LEAVE_SUCCESS="53",le.PUBLISH_START="61",le.SEND_FIRST_VIDEO_FRAME="62",le.PUBLISH_FAILED="63",le.SUBSCRIBE_START="81",le.SUBSCRIBE_SUCCESS="82",le.SUBSCRIBE_FAILED="84",le.UNSUBSCRIBE_SUCCESS="83",le.LOCAL_TRACK_CAPTURE_START="101",le.LOCAL_TRACK_CAPTURE_SUCCESS="102",le.LOCAL_TRACK_CAPTURE_FAILED="103",le.LOCAL_TRACK_PUBLISHED="104",le.LOCAL_TRACK_UNPUBLISHED="105",le.LOCAL_TRACK_REPLACED="106",le.SWITCH_DEVICE_SUCCESS="107",le.TRACK_MUTED="108",le.TRACK_UNMUTED="109",le.REMOTE_TRACK_SUBSCRIBED="110",le.REMOTE_TRACK_UNSUBSCRIBED="111",le.LOCAL_TRACK_RECAPTURE="112",le.LOCAL_AUDIO_STARTED="113",le.LOCAL_AUDIO_STOPPED="114",le.REMOTE_AUDIO_STARTED="115",le.REMOTE_AUDIO_STOPPED="116",le.PLAY_TRACK_START="151",le.PLAYER_STATE_CHANGED="152",le.VIDEO_LOADED_DATA="153",le.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",le.SIGNAL_CONNECTION_STATE_CHANGED="201",le.PEER_CONNECTION_STATE_CHANGED="202",le.SINGLE_CONNECTION_STAT="203",le.SPC_RECONNECTED="204",le.HEARTBEAT_REPORT="251",le.RECEIVED_PUBLISHED_USER_LIST="252",le.REMOTE_PUBLISH_STATE_CHANGED="253",le.AUDIO_LEVEL_INTERVAL="260",le.NETWORK_QUALITY="261",le.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",le.QUALITY_LIMITATION_CHANGED="263",le.LOG="264",le))(Gi||{});var U=Gi;var KE="%cTRTC%c%s",e_="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",t_="display: inline",$c=class $c{constructor(){u(this,"_isEnableUploadLog",!0);u(this,"_localJoinedUser",new Map);u(this,"_queue",[]);u(this,"_timeoutId",-1);u(this,"_logLevel",1);u(this,"_logLevelToUpload",2);!fs&&!Tn&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){L.on(U.JOIN_SCHEDULE_SUCCESS,({schedule:t})=>{var e;(e=t==null?void 0:t.config)!=null&&e.logLevelToUpload&&gr[t.config.logLevelToUpload]&&(this._logLevelToUpload=t.config.logLevelToUpload)}),L.on(U.JOIN_SUCCESS,({room:t})=>{this.addJoinedUser({userId:t.userId,sdkAppId:t.sdkAppId}),this.startUpload()}),L.once(U.JOIN_FAILED,()=>{this.startUpload()}),L.on(U.LEAVE_SUCCESS,({room:t})=>{this.deleteJoinedUser(t.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(t){this._localJoinedUser.set(t.userId,t),this.startUpload()}deleteJoinedUser(t){this._localJoinedUser.delete(t)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),5e3)}getLogsToUpload(){let t={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return t;let e=0;for(;e<this._queue.length&&e!==50;e++){let r=this._queue[e];if(r.forAllJoinedClients)this._localJoinedUser.forEach(({userId:o,sdkAppId:s})=>{t.map.has(o)?t.map.get(o).logs.push(r):t.map.set(o,{userId:o,sdkAppId:s,logs:[r]})});else if(ve(r.userId)&&We(r.sdkAppId)){let{userId:o,sdkAppId:s}=r;t.map.has(o)?t.map.get(o).logs.push(r):t.map.set(o,{userId:o,sdkAppId:s,logs:[r]})}}return t.map.size>0&&(t.splicedQueue=this._queue.splice(0,e)),t}upload(){return A(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:t,splicedQueue:e}=this.getLogsToUpload();if(t.size===0)return;try{let o=[...t.values()];for(let s=0;s<o.length;s++){let{userId:n,sdkAppId:d,logs:m}=o[s];yield this.uploadLogWithRetry(JSON.stringify({timestamp:ic(),sdkAppId:String(d),userId:n,version:st,log:m.map(l=>l.log).join(`
|
|
4
|
+
`)}),d),m.forEach(l=>l.uploaded=!0)}}catch(o){}let r=e.filter(o=>!o.uploaded);r.length>0&&(this._queue=r.concat(this._queue))})}uploadLogWithRetry(t,e){return Fi({retryFunction:()=>ri({url:ti(e,Li.LOG),body:t,timeout:5e3,priority:"low"}),settings:{retries:3,timeout:2e3},onError:({retry:r})=>{r()}})()}getPrefix(t){let e=new Date;return e.setTime(_n()),`[${oc(e)}] <${gr[t]}>`}getLogLevel(){return this._logLevel}setLogLevel(t){V(gr[t])||(this._logLevel!==t&&this.info("setLogLevel",t),this._logLevel=t)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(t){if(ve(t))return t;try{return t instanceof Error?t.toString():JSON.stringify(t)}catch(e){return""}}log(t,e,r=!0,o,s){var m;e.unshift(this.getPrefix(t));let n={log:e.reduce((l,g)=>`${l} ${this.logChunkToString(g)}`.trim(),""),level:t,userId:o,sdkAppId:s,forAllJoinedClients:r};if(L.emit(U.LOG,{log:n}),this._isEnableUploadLog&&t>=this._logLevelToUpload&&this._queue.push(n),t<this._logLevel)return;let d=((m=gr[t])==null?void 0:m.toLowerCase())||"info";$c.PRINT_LOG_TAG?console[d](KE,e_,t_,...e):console[d](...e)}debug(...t){this.log(1,t)}info(...t){this.log(2,t)}warn(...t){this.log(3,t)}error(...t){this.log(4,t)}createLogger(t){return new bs(t)}checkURLParam(){let e=new URLSearchParams(location.search).get("logLevelToUpload"),r=e?Number(e):-1;gr[r]&&(this._logLevelToUpload=r)}getQueue(){return this._queue}};u($c,"PRINT_LOG_TAG",!(mt||ut||ol));var pl=$c,F=new pl;var r_=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let t=Math.random()*16|0;return(i=="x"?t:t&3|8).toString(16)})},zn=r_;var hl=class{constructor(){u(this,"_prefix","TRTC");u(this,"_queue",new Map)}getRealKey(t){return`${this._prefix}_${t}`}checkStorage(){if(!ni())return;setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(r=>{if(r.startsWith(this._prefix))try{let o=localStorage.getItem(r);if(!o)return!1;let s=JSON.parse(o);if(s&&s.expiresIn<Date.now())return!0}catch(o){return!1}return!1}).forEach(r=>localStorage.removeItem(r))}doFlush(){if(ni())try{for(let[t,e]of this._queue)localStorage.setItem(t,JSON.stringify(e))}catch(t){F.warn(t)}}getItem(t){if(!ni())return null;try{let e=localStorage.getItem(this.getRealKey(t));if(!e)return null;let r=JSON.parse(e);return r&&r.expiresIn>=Date.now()?r.value:null}catch(e){F.warn(e)}}setItem(t,e){if(ni())try{let r={expiresIn:Date.now()+nc,value:e};this._queue.set(this.getRealKey(t),r)}catch(r){F.warn(r)}}deleteItem(t){if(!ni())return!1;try{return t=this.getRealKey(t),this._queue.delete(t),localStorage.removeItem(t),!0}catch(e){return F.warn(e),!1}}clear(){if(ni())try{localStorage.clear()}catch(t){F.warn(t)}}},Ls=new hl;var zi={};Yr(zi,{HTTPS_API:()=>I_,IS_GET_CAPABILITIES_SUPPORTED:()=>Ll,IS_GET_SETTINGS_SUPPORTED:()=>Fs,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>N_,IS_INSERTABLE_STREAM_SUPPORTED:()=>ia,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>P_,IS_RTC_RTP_SENDER_SUPPORTED:()=>ra,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>kh,IS_SEI_SUPPORTED:()=>oa,IS_SPC_SUPPORTED:()=>R_,basis:()=>M_,capabilityCheck:()=>Vl,checkSystemRequirementsInternal:()=>Zc,decodeSupportStatus:()=>Nh,encodeSupportStatus:()=>Ol,getBrowserInfo:()=>Qc,getDisplayResolution:()=>wh,isAddTransceiverSupported:()=>kl,isBrowserSupported:()=>Pl,isGetReceiversSupported:()=>A_,isGetSendersSupported:()=>xh,isGetTransceiversSupported:()=>b_,isGetUserMediaSupported:()=>Mh,isMediaDevicesSupported:()=>Yc,isMediaSessionSupported:()=>Uh,isMediaStreamTrackProcessorSupported:()=>xl,isReplaceTrackSupported:()=>C_,isRequestVideoFrameCallbackSupported:()=>li,isSIMDSupported:()=>w_,isScreenCaptureApiAvailable:()=>ea,isSelectedCandidatePair:()=>S_,isSetParametersSupported:()=>D_,isSmallStreamAPISupported:()=>Ph,isSmallStreamSupported:()=>ta,isStopTransceiverSupported:()=>v_,isTRTCSupported:()=>__,isUnifiedPlanDefault:()=>y_,isUsedInHttpProtocol:()=>ui,isWebAudioSupported:()=>Oh,isWebCodecSupported:()=>Lh,isWebCodecsSupported:()=>Dh,isWebRTCSupported:()=>Ul,isWebTransportSupported:()=>Vh});var vl={};Yr(vl,{AUDIO_LEVEL_SCALE:()=>ci,AudioCodecPipelineType:()=>jc,AudioDecoderDowngradeState:()=>El,AudioPlayerMode:()=>Sl,AudioType:()=>Tl,BASIC_TYPE:()=>qi,BannedReason:()=>yl,CONNECTION_CLOSED_REASON:()=>uh,ClientEvent:()=>fl,CodecType:()=>Eh,ConnectionEvent:()=>dh,ConnectionState:()=>Hc,DECODE_FAILED_ERROR_CODE:()=>Rl,FacingMode:()=>Wc,LeaveReason:()=>Al,LocalTrackEvent:()=>Bc,MULTI_VIDEO_DATA_TYPE:()=>ai,MediaType:()=>Dt,MediaTypeLabel:()=>i_,MonitorEventId:()=>Qn,MutedFlag:()=>mh,NetworkQualityValue:()=>fh,PlayerState:()=>xo,ReceiveMode:()=>gh,RemoteStreamType:()=>$r,RemoteTrackEvent:()=>Us,RoomEvent:()=>ji,SceneNumber:()=>gl,StreamEvent:()=>lh,StreamType:()=>hh,SubscribeMediaType:()=>Jn,TIMER_TYPE:()=>Lo,TRACK_ACTION:()=>ph,TRACK_KIND:()=>_l,TrackEvent:()=>Fr,UserRole:()=>zt,UserRoleNumber:()=>ko,VideoCodec:()=>bl,VideoCodecPipelineType:()=>Yn,VideoContentHint:()=>Zn,VideoDecoderDowngradeState:()=>Xn,VideoPlayerMode:()=>Gc,VideoType:()=>Il});var dh=(P=>(P.TRACK_ADDED="track-added",P.TRACK_UPDATED="track-updated",P.TRACK_SUBSCRIBED="track-subscribed",P.STREAM_ADDED="stream-added",P.STREAM_REMOVED="stream-removed",P.STREAM_UPDATED="stream-updated",P.STREAM_PUBLISHED="stream-published",P.STREAM_SUBSCRIBED="stream-subscribed",P.STREAM_UNSUBSCRIBED="stream-unsubscribed",P.STATE_CHANGED="state-changed",P.ERROR="error",P.CONNECTION_STATE_CHANGED="connection-state-changed",P.FIREWALL_RESTRICTION="firewall-restriction",P.SEI_MESSAGE="sei-message",P.CLOSED="closed",P))(dh||{}),uh=(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))(uh||{}),fl=(M=>(M.STREAM_ADDED="stream-added",M.STREAM_REMOVED="stream-removed",M.STREAM_UPDATED="stream-updated",M.STREAM_SUBSCRIBED="stream-subscribed",M.CONNECTION_STATE_CHANGED="connection-state-changed",M.PEER_JOIN="peer-join",M.PEER_LEAVE="peer-leave",M.MUTE_AUDIO="mute-audio",M.MUTE_VIDEO="mute-video",M.UNMUTE_AUDIO="unmute-audio",M.UNMUTE_VIDEO="unmute-video",M.CLIENT_BANNED="client-banned",M.NETWORK_QUALITY="network-quality",M.AUDIO_VOLUME="audio-volume",M.SEI_MESSAGE="sei-message",M.ERROR="error",M))(fl||{}),lh=(s=>(s.PLAYER_STATE_CHANGED="player-state-changed",s.SCREEN_SHARING_STOPPED="screen-sharing-stopped",s.CONNECTION_STATE_CHANGED="connection-state-changed",s.DEVICE_AUTO_RECOVERED="device-auto-recovered",s.ERROR="error",s))(lh||{}),Bc=(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))(Bc||{}),xo=(r=>(r.PAUSED="PAUSED",r.PLAYING="PLAYING",r.STOPPED="STOPPED",r))(xo||{}),ji=(ne=>(ne.PEER_JOIN="peer-join",ne.PEER_LEAVE="peer-leave",ne.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",ne.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",ne.BANNED="banned",ne.NETWORK_QUALITY="network-quality",ne.AUDIO_VOLUME="audio-volume",ne.SEI_MESSAGE="sei-message",ne.ERROR="error",ne.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",ne.REMOTE_PUBLISHED="remote-published",ne.REMOTE_UNPUBLISHED="remote-unpublished",ne.FIREWALL_RESTRICTION="firewall-restriction",ne.HEARTBEAT_REPORT="heartbeat-report",ne.CUSTOM_MESSAGE="custom-message",ne.LAYER_DATA="layerData",ne.FIRST_VIDEO_FRAME="first-video-frame",ne.DUMP="dump",ne.AUDIO_FRAME="audio-frame",ne))(ji||{}),Fr=(d=>(d.PLAYER_STATE_CHANGED="player-state-changed",d.MUTE="mute",d.UNMUTE="unmute",d.ERROR="error",d.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",d.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",d.FIRST_VIDEO_FRAME="first-video-frame",d))(Fr||{}),Us=(e=>(e.DECODE_FAILED="decode-failed",e.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",e))(Us||{}),mh=(d=>(d[d.VIDEO=1]="VIDEO",d[d.SMALL=2]="SMALL",d[d.AUX=4]="AUX",d[d.AUDIO=8]="AUDIO",d[d.VIDEO_MUTE=16]="VIDEO_MUTE",d[d.AUX_MUTE=32]="AUX_MUTE",d[d.AUDIO_MUTE=64]="AUDIO_MUTE",d))(mh||{}),gl=(e=>(e[e.RTC=1]="RTC",e[e.LIVE=2]="LIVE",e))(gl||{}),ko=(e=>(e[e.ANCHOR=20]="ANCHOR",e[e.AUDIENCE=21]="AUDIENCE",e))(ko||{}),zt=(e=>(e.ANCHOR="anchor",e.AUDIENCE="audience",e))(zt||{}),Hc=(s=>(s.CONNECTED="CONNECTED",s.DISCONNECTED="DISCONNECTED",s.CONNECTING="CONNECTING",s.RECONNECTED="RECONNECTED",s.RECONNECTING="RECONNECTING",s))(Hc||{}),El=(o=>(o.INITIALIZED="INITIALIZED",o.STARTING="STARTING",o.STARTED="STARTED",o.FAILED="FAILED",o))(El||{}),Xn=(o=>(o.INITIALIZED="INITIALIZED",o.STARTING="STARTING",o.STARTED="STARTED",o.FAILED="FAILED",o))(Xn||{}),_l=(r=>(r.AUDIO="audio",r.VIDEO="video",r.AUXILIARY="auxVideo",r))(_l||{}),ph=(e=>(e.ADD="add",e.REMOVE="remove",e))(ph||{}),Dt=(s=>(s[s.NULL=0]="NULL",s[s.AUDIO=1]="AUDIO",s[s.AUX_VIDEO=2]="AUX_VIDEO",s[s.BIG_VIDEO=4]="BIG_VIDEO",s[s.SMALL_VIDEO=8]="SMALL_VIDEO",s))(Dt||{}),i_={1:"audio",2:"auxVideo",4:"video"},Tl=(t=>(t[t.opus=111]="opus",t))(Tl||{}),Il=(e=>(e[e.h264=100]="h264",e[e.vp8=101]="vp8",e))(Il||{}),hh=(e=>(e.Big="big",e.Small="small",e))(hh||{}),$r=(e=>(e.Main="main",e.Aux="auxiliary",e))($r||{}),ai=(s=>(s[s.MULTI_DATA_AUDIO=1]="MULTI_DATA_AUDIO",s[s.MULTI_DATA_BIG_IMG=2]="MULTI_DATA_BIG_IMG",s[s.MULTI_DATA_SMALL_IMG=3]="MULTI_DATA_SMALL_IMG",s[s.MULTI_DATA_AUX_IMG=7]="MULTI_DATA_AUX_IMG",s[s.MULTI_DATA_TYPE_BUTT=12]="MULTI_DATA_TYPE_BUTT",s))(ai||{}),Qn=(W=>(W[W.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",W[W.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",W[W.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",W[W.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",W[W.MUTE_AUDIO=32772]="MUTE_AUDIO",W[W.MUTE_VIDEO=32773]="MUTE_VIDEO",W[W.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",W[W.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",W[W.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",W[W.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",W[W.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",W[W.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",W[W.SWITCH_CAMERA=32780]="SWITCH_CAMERA",W[W.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",W[W.REPLACE_VIDEO=32782]="REPLACE_VIDEO",W[W.REPLACE_AUDIO=32783]="REPLACE_AUDIO",W[W.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",W[W.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",W[W.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",W[W.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",W[W.JOIN=32788]="JOIN",W[W.LEAVE=32789]="LEAVE",W[W.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",W[W.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",W[W.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",W[W.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",W[W.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",W[W.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",W[W.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",W[W.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",W[W.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",W[W.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",W[W.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",W[W.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",W[W.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",W[W.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",W[W.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",W[W.PUBLISH_AUX=32805]="PUBLISH_AUX",W[W.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",W[W.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",W[W.VIDEO_ENCODER=4004]="VIDEO_ENCODER",W[W.VIDEO_DECODER=4005]="VIDEO_DECODER",W))(Qn||{}),fh=(d=>(d[d.UNKNOWN=0]="UNKNOWN",d[d.EXCELLENT=1]="EXCELLENT",d[d.GOOD=2]="GOOD",d[d.POOR=3]="POOR",d[d.BAD=4]="BAD",d[d.VERY_BAD=5]="VERY_BAD",d[d.DISCONNECTED=6]="DISCONNECTED",d))(fh||{}),gh=(o=>(o[o.MANUAL=0]="MANUAL",o[o.AUTO_AUDIO=1]="AUTO_AUDIO",o[o.AUTO_VIDEO=2]="AUTO_VIDEO",o[o.AUTO_ALL=3]="AUTO_ALL",o))(gh||{}),Wc=(e=>(e.user="user",e.environment="environment",e))(Wc||{}),Gc=(r=>(r[r.ELEMENT=0]="ELEMENT",r[r.CANVAS_FROM_ELEMENT=1]="CANVAS_FROM_ELEMENT",r[r.CANVAS_WITHOUT_ELEMENT=2]="CANVAS_WITHOUT_ELEMENT",r))(Gc||{}),Sl=(e=>(e[e.ELEMENT=0]="ELEMENT",e[e.CONTEXT=1]="CONTEXT",e))(Sl||{}),yl=(o=>(o.BANNED="banned",o.KICK="kick",o.USER_TIME_OUT="user_time_out",o.ROOM_DISBAND="room_disband",o))(yl||{}),Al=(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))(Al||{}),ci=1e8,Jn=class{constructor(){u(this,"mediaType",0)}set audio(t){t?this.mediaType|=1:this.mediaType&=-2}get audio(){return!!(this.mediaType&1)}set video(t){t?this.mediaType|=4:this.mediaType&=-5}get video(){return!!(this.mediaType&4)}set auxiliary(t){t?this.mediaType|=2:this.mediaType&=-3}get auxiliary(){return!!(this.mediaType&2)}set smallVideo(t){t?this.mediaType|=8:this.mediaType&=-9}get smallVideo(){return!!(this.mediaType&8)}},qi=(s=>(s.String="string",s.Number="number",s.Boolean="boolean",s.Array="array",s.Object="object",s))(qi||{}),bl=(r=>(r.H264="h264",r.H265="h265",r.VP8="vp8",r))(bl||{}),Yn=(o=>(o[o.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",o[o.DUMP=1]="DUMP",o[o.SEI=2]="SEI",o[o.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",o))(Yn||{}),jc=(o=>(o[o.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",o[o.NTP_TO_AUDIO_FRAME=1]="NTP_TO_AUDIO_FRAME",o[o.DUMP=2]="DUMP",o[o.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",o))(jc||{}),Eh=(r=>(r.WebRTC="webrtc",r.WebCodecs="webcodecs",r.WebAssembly="webassembly",r))(Eh||{}),Rl=(S=>(S[S.SUCCESS=0]="SUCCESS",S[S.FAILED=1]="FAILED",S[S.WEBCODEC_INIT=2]="WEBCODEC_INIT",S[S.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",S[S.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",S[S.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",S[S.WASM_INIT=6]="WASM_INIT",S[S.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",S[S.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",S[S.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",S[S.TEST=10]="TEST",S[S.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",S))(Rl||{}),Zn=(o=>(o.NONE="",o.DETAIL="detail",o.MOTION="motion",o.TEXT="text",o))(Zn||{}),Lo=(s=>(s.INTERVAL="interval",s.TIMEOUT="timeout",s.RAF="raf",s.RIC="ric",s.INTERVAL_IN_WORKER="intervalInWorker",s))(Lo||{});var Fe={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"},Jt={AVOID_REPEATED_CALL(i){return`previous ${i.name}() is ongoing, please avoid repeated calls.`},INVALID_PARAMETER_REQUIRED({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' is a required param when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_TYPE({key:i,rule:t,fnName:e,value:r}){let o=`${i||t.name}`,s="";return Array.isArray(t.type)?s=t.type.join("|"):s=t.type,`'${o}' must be type of ${s} when calling ${e}(), received type: ${nt(r)}.`},INVALID_PARAMETER_EMPTY({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' cannot be '${r}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:i,rule:t,fnName:e,value:r}){let o=`${i||t.name}`,s=`${t.instanceOf.name||t.instanceOf}`;return`'${o}' must be instanceof ${s} when calling ${e}(), received type: ${nt(r)}.`},INVALID_PARAMETER_RANGE({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' must be one of ${t.values.join("|")} when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_MIN({key:i,rule:t,fnName:e,value:r}){return`the min value of ${i||t.name} is ${t.min}, received: ${r}.`},INVALID_PARAMETER_MAX({key:i,rule:t,fnName:e,value:r}){return`the max value of ${i||t.name} is ${t.max}, received: ${r}.`},API_CALL_TIMEOUT(i){return`${i.commandDesc||i.command} timeout observed.`},SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED(i){return`SignalChannel setup failure: (errorCode: ${i.errorCode}, errorMsg: ${i.errorMsg} }).`},ERROR_MESSAGE(i){let t=`${i.type} failed`;return i.message&&(t=`${t}: ${i.message}.`),t},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED(i){return`exchange sdp failed ${i.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(i){return`'${i}' must be validate string when useStringRoomId is true.`},INVALID_ROOMID_INTEGER(i){return`'${i}' 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:i,code:t}){return`Failed to join room - ${i} code: ${t}`},REJOIN_ROOM_FAILED(i){return`reJoin room: ${i.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(i){return`duplicate ${i} stream publishing, please unpublish your prev ${i} 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:i,userId:t,streamType:e}){return`failed to subscribe ${t} ${e} stream, reason: ${i}.`},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(i){return`switchRole failed, errCode: ${i.code} errMsg: ${i.message}.`},CLIENT_BANNED(i){return`client was banned because of ${i.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(i){return`startPublishCDNStream failed, errMsg: ${i.message}.`},STOP_PUBLISH_CDN_FAILED(i){return`stopPublishCDNStream failed, errMsg: ${i.message}.`},INVALID_STREAM_ID(i){return`'${i}' 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(i){return`cannot replace ${i.kind} track because stream has not ${i.kind} track`},NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED(i){return`startMixTranscode failed, errMsg: ${i.message}.`},STOP_MIX_TRANSCODE_FAILED(i){return`stopMixTranscode failed, errMsg: ${i.message}.`},MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO({key:i,rule:t,fnName:e,value:r}){return`'${i||t.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(i){return`'${i}' 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:i,fnName:t})=>`'${i}' is not found in the document object when calling ${t}().`,INVALID_ELEMENT_ID_TYPE:({key:i,fnName:t,type:e})=>`the element corresponding to '${i}' must be instanceof HTMLElement when calling ${t}(), received: ${e}.`,PLAY_FAILED:i=>`${i.media} play failed, browser exception: ${i.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(i){return`${i}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(i){return`${i.signalResponse} failed, response code is ${i.code} , errMsg: ${i.message}.`},CATCH_HANDLER_ERROR({name:i,event:t}){return`an error was caught in ${i}.on('${t}', handler), please check your code in 'handler'.`},API_NOT_EXIST({name:i}){return`experimental api ${i} does not exist.`},REPEAT_JOIN:i=>"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:i}){return`failed to call ${i}() because client was destroyed.`},SEI_NOT_SUPPORT:i=>`not support to sendSEIMessage${i===!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:i,name:t,timesInSecond:e,maxSizeInSecond:r})=>`api ${t} call ${i?"size":"times"} is over ${i?`${r} bytes`:e} in a second.`,CONNECTION_ABORTED(i){return`connection aborted due to: ${i}`},API_CALL_ABORTED(i){let t;return i.message.includes("REMOTE_STREAM_NOT_EXIST")?t=`Subscribe ${i.userId} ${i.streamType} stream aborted, reason: remote user ${i.userId} unpublished stream.`:t=`API aborted, reason: ${i.message}`,t},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:i=>`'streamType' is required when 'userId' is not '*', calling ${i}()`};var _h=(i,t)=>t?`${Pr}/${i}/${t}`:`${Pr}/${i}/index.html`;var o_=()=>{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 i=localStorage==null?void 0:localStorage.getItem(Vu);if(i){i=JSON.parse(i);let t=document.createElement("script");t.type="text/javascript",t.text=i.message,document.body.appendChild(t);let e=window.TRTC_ERROR_INFO,r=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:e,TRTC_ERROR_LINK:r}}return{}};function $e(i){let{key:t,data:e,link:r,addDocLink:o=!0}=i,s="",n="",d="";He(Jt[t])?s=Jt[t](e):ve(Jt[t])&&(s=Jt[t]);let{TRTC_ERROR_INFO:m,TRTC_ERROR_LINK:l}=o_();r?d=`${r.className}.html#${r.fnName}`:l&&l[t]&&(He(l[t])?d=l[t](e):ve(l[t])&&(d=l[t]));let g=s;return _r()&&(m&&m[t]&&(He(m[t])?n=m[t](e):ve(m[t])&&(n=m[t])),n&&(o?g=`${n}
|
|
5
|
+
\u8BF7\u67E5\u770B\u6587\u6863: ${_h("zh-cn",d)}
|
|
8
6
|
|
|
9
|
-
`:
|
|
7
|
+
`:g=`${n}
|
|
10
8
|
|
|
11
|
-
`,
|
|
12
|
-
Refer to: ${
|
|
13
|
-
`),u}var Rd=Be(Ah(),1);var a_=1,c_=0,Kn=class{constructor(i=!0){c(this,"countMap",new Map);c(this,"distributionMap",new Map);c(this,"version");c(this,"log",C.createLogger({id:"kv"}));i&&(S.on("102",({track:e,cost:t})=>{this.addSuccessEvent({key:e.kind===m.AUDIO?501700:511700,cost:t})}),S.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:Cn(this.version||Oe),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 d=t.length-1;d>0;d--)if(e>t[d]){n=d;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:a_,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=I.UNKNOWN;e&&(Y(e)?t=e:(!T(e.extraCode)||!T(e.code))&&(t=e.extraCode||e.code)),this.addEnum({key:i,value:c_,useUV:!1}),this.addEnum({key:i,value:Math.abs(t),useUV:!1})}},Zn=(G=>(G[G.enterRoom=500700]="enterRoom",G[G.exitRoom=500701]="exitRoom",G[G.switchRole=500702]="switchRole",G[G.destroy=500703]="destroy",G[G.startLocalAudio=500704]="startLocalAudio",G[G.updateLocalAudio=500705]="updateLocalAudio",G[G.stopLocalAudio=500706]="stopLocalAudio",G[G.startLocalVideo=500707]="startLocalVideo",G[G.updateLocalVideo=500708]="updateLocalVideo",G[G.stopLocalVideo=500709]="stopLocalVideo",G[G.startScreenShare=500710]="startScreenShare",G[G.updateScreenShare=500711]="updateScreenShare",G[G.stopScreenShare=500712]="stopScreenShare",G[G.startRemoteVideo=500713]="startRemoteVideo",G[G.updateRemoteVideo=500714]="updateRemoteVideo",G[G.stopRemoteVideo=500715]="stopRemoteVideo",G[G.muteRemoteAudio=500716]="muteRemoteAudio",G[G.setRemoteAudioVolume=500717]="setRemoteAudioVolume",G[G.use=500718]="use",G[G.sendSEIMessage=5e5]="sendSEIMessage",G[G.sendCustomMessage=500001]="sendCustomMessage",G))(Zn||{}),Id=(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))(Id||{}),Ad=(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))(Ad||{}),Cd=(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))(Cd||{});var d_=new Kn(!0),Ir=new Kn(!1);var N=d_;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}},l_=new Map([[se,["Firefox",vn]],[is,["Edg",On]],[cs,["Chrome",Wn]],[Me,["Safari",Ai]],[Ot,["TBS",Ln]],[rs,["XWEB",Pn]],[ss&&qi,["WeChat",wn]],[so,["QQ(Win)",xn]],[ns,["QQ(Mobile)",Zr]],[os,["QQ(Mobile X5)",Zr]],[oo,["QQ(Mac)",Un]],[no,["QQ(iPad)",Vn]],[co,["MI",Bn]],[lo,["HW",Fn]],[uo,["Samsung",Hn]],[ho,["OPPO",$n]],[mo,["VIVO",Gn]],[ts,["EDGE",Dn]],[io,["SogouMobile",kn]],[ro,["Sogou",Mn]]]);function u_(){let s=l_.get(!0),i=s?s[0]:"unknown",e=s?s[1]:"unknown";return{browserName:i,browserVersion:e}}var bd=function(){return!(Xc||ts||is&&jc<80||se&&to<56)},Rh=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every(i=>i in window)},ta=function(){if(!navigator.mediaDevices)return vi()||C.error(Pe.NOT_SUPPORTED_MEDIA),!1;let s=["getUserMedia","enumerateDevices"];return s.filter(i=>i in navigator.mediaDevices).length===s.length},Ch=!1;function vi(){return location.protocol==="http:"&&!Mt?(Ch||C.error(V({key:U.NOT_SUPPORTED_HTTP})),Ch=!0,!0):!1}var Nd=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},yd=function(){return p(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}}})},ia=function(){return p(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}}})},ra=Rn(()=>p(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=bd(),e=kd(),t=Rh(),r=ta(),{isH264EncodeSupported:o,isVp8EncodeSupported:n}=yield yd(),{isH264DecodeSupported:a,isVp8DecodeSupported:d}=yield ia();if(!o||!n){let l=yield yd();C.warn(`detect encode again h264:${o} vp8:${n} result: ${JSON.stringify(l)}`),o=l.isH264EncodeSupported,n=l.isVp8EncodeSupported}if(o&&a&&he&&Qe&&!rs&&!Ot){let{encode:l,decode:u}=yield m_();o=l,a=u}return ie.result=i&&e&&r&&(o||n)&&(a||d),ie.detail.isBrowserSupported=i,ie.detail.isWebRTCSupported=e,ie.detail.isWebCodecsSupported=t,ie.detail.isMediaDevicesSupported=r,ie.detail.isScreenShareSupported=Io(),ie.detail.isSmallStreamSupported=Ao(),ie.detail.isH264EncodeSupported=o,ie.detail.isVp8EncodeSupported=n,ie.detail.isH264DecodeSupported=a,ie.detail.isVp8DecodeSupported=d,ie.result||C.error(`${navigator.userAgent} ${In(ie.detail,!1)}`),E_(),N.addNumber({key:523800,value:Date.now()-s}),ie})),h_=function(){return ie.result},Io=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},ea=null;function m_(){return p(this,null,function*(){return ea||(ea=new Promise(s=>p(this,null,function*(){let i={encode:!1,decode:!1},e=()=>{};try{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(),u.close(),d.getTracks().forEach(_=>_.stop())},a=setTimeout(()=>{e(),s(i)},2*1e3);let d=t.captureStream(),l=new RTCPeerConnection({}),u=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});l.addEventListener("icecandidate",_=>u.addIceCandidate(_.candidate)),u.addEventListener("icecandidate",_=>l.addIceCandidate(_.candidate)),l.addTrack(d.getVideoTracks()[0],d);let h=yield l.createOffer();yield l.setLocalDescription(h),yield u.setRemoteDescription(h);let f=yield u.createAnswer(),g=Rd.default.parse(f.sdp),D=g.media[0].rtp.findIndex(_=>_.codec==="H264");g.media[0].rtp=[g.media[0].rtp[D]],g.media[0].fmtp=g.media[0].fmtp.filter(_=>_.payload===g.media[0].rtp[0].payload),g.media[0].rtcpFb&&(g.media[0].rtcpFb=g.media[0].rtcpFb.filter(_=>_.payload===g.media[0].rtp[0].payload)),f.sdp=Rd.default.write(g),yield u.setLocalDescription(f),yield l.setRemoteDescription(f),n=setInterval(()=>p(this,null,function*(){i.encode&&i.decode&&(e(),s(i));let[_,R]=yield Promise.all([l.getSenders()[0].getStats(),u.getReceivers()[0].getStats()]);i.encode||_.forEach(k=>{k.type==="outbound-rtp"&&k.mediaType===m.VIDEO&&k.bytesSent>0&&(i.encode=!0)}),i.decode||R.forEach(k=>{k.type==="inbound-rtp"&&k.mediaType===m.VIDEO&&k.bytesReceived>0&&(i.decode=!0)})}),100)}catch(t){e(),C.warn("detectH264Supported failed",t),s({encode:!0,decode:!0})}})).then(s=>(s.encode||(s.decode=!0),(!s.encode||!s.decode)&&C.warn(`detectH264Supported encode: ${s.encode} decode: ${s.decode} ${vt}`),s)),ea)})}var p_=(s,i,e)=>{location.protocol==="http:"&&!Mt&&(s[i]=()=>{throw new b({code:I.INVALID_OPERATION,message:Pe.NOT_SUPPORTED_HTTP})})},Yi=function(s){return s.type==="candidate-pair"&&s.nominated&&(s.state==="in-progress"||s.state==="succeeded")?!(_e(s.selected)&&!s.selected):!1};function yh(){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 bh(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function Nh(){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 vh(){return"captureStream"in HTMLCanvasElement.prototype}function Ao(){return ss||Te||lt&<<63?!1:!!(bd()&&vh())}var f_=function(){if(T(window.RTCRtpTransceiver)||!mt()||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let s=null,i=!1;try{s=new RTCPeerConnection({sdpSemantics:Ji}),s.addTransceiver(m.AUDIO),i=!0}catch(e){}return s==null||s.close(),i};function Ar(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function Ki(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function Yt(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function mt(){return ut===11&&!id?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var ms=!(!mt()||Qe&<<86);function __(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var Co="RTCRtpSender"in window;function vd(){return Co&&"replaceTrack"in window.RTCRtpSender.prototype}function Ro(){return Co&&"setParameters"in window.RTCRtpSender.prototype&&Ki()}var Dd="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,Kt=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,Od=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,Di=Co&&"createEncodedStreams"in window.RTCRtpSender.prototype&&as()>=86,sa="RTCRtpScriptTransform"in window,yo=Co&&(Di||sa),kd=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(i=>i in window).length>0};function Dh(){let s={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return T(window.AudioDecoder)||(s.AudioDecoder=!0),T(window.AudioEncoder)||(s.AudioEncoder=!0),T(window.VideoDecoder)||(s.VideoDecoder=!0),T(window.VideoEncoder)||(s.VideoEncoder=!0),T(window.ImageDecoder)||(s.ImageDecoder=!0),s}function Oh(){return"mediaSession"in navigator&&!T(navigator.mediaSession.setActionHandler)}function kh(){return!T(window.WebTransport)}function g_(){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 T_(){let s={browser:`${qt.name}/${qt.version}`,os:Jn(),displayResolution:yh(),isScreenShareSupported:Io(),isWebRTCSupported:kd(),isGetUserMediaSupported:bh(),isWebAudioSupported:Nh(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:Dh(),isMediaSessionSupported:Oh(),isWebTransportSupported:kh()};return navigator.userAgent.includes("miniProgram")&&(s.browser=`mini/${s.browser}`),s}var Mh="checkResult";function E_(){ls.setItem(Mh,{ua:navigator.userAgent,checkResult:ie})}function Md(){vi();let s=ls.getItem(Mh);s&&s.ua===navigator.userAgent&&(ie=s.checkResult),ra()}function Cr(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var oa="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;var Ph=Be(ze(),1);var Lh=Symbol("instance"),vS=Symbol("abortCtrl"),na=Symbol("cacheResult"),bo=class{constructor(i,e,t){this.oldState=i,this.newState=e,this.action=t,this.aborted=!1}abort(i){this.aborted=!0,Do.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},No=class extends Error{constructor(i,e,t){super(e),this.state=i,this.message=e,this.cause=t}};function S_(s){return typeof s=="object"&&s&&"then"in s}var vo=new Map;function pe(s,i,e={}){return(t,r,o)=>{let n=e.action||r;if(!e.context){let d=vo.get(t)||[];vo.has(t)||vo.set(t,d),d.push({from:s,to:i,action:n})}let a=o.value;o.value=function(...d){let l=this;if(e.context&&(l=F.get(typeof e.context=="function"?e.context.call(this,...d):e.context)),l.state===i)return e.sync?l[na]:Promise.resolve(l[na]);l.state instanceof bo&&l.state.action==e.abortAction&&l.state.abort(l);let u=null;Array.isArray(s)?s.length==0?l.state instanceof bo&&l.state.abort(l):(typeof l.state!="string"||!s.includes(l.state))&&(u=new No(l._state,`${l.name} ${n} to ${i} failed: current state ${l._state} not from ${s.join("|")}`)):s!==l.state&&(u=new No(l._state,`${l.name} ${n} to ${i} failed: current state ${l._state} not from ${s}`));let h=R=>{if(e.fail&&e.fail.call(this,R),e.sync){if(e.ignoreError)return R;throw R}else return e.ignoreError?Promise.resolve(R):Promise.reject(R)};if(u)return h(u);let f=l.state,g=new bo(f,i,n);Do.call(l,g);let D=R=>{var k;return l[na]=R,g.aborted||(Do.call(l,i),(k=e.success)===null||k===void 0||k.call(this,l[na])),R},_=R=>(Do.call(l,f,R),h(R));try{let R=a.apply(this,d);return S_(R)?R.then(D).catch(_):e.sync?D(R):Promise.resolve(D(R))}catch(R){return _(new No(l._state,`${l.name} ${n} from ${s} to ${i} failed: ${R}`,R instanceof Error?R:new Error(String(R))))}}}}var I_=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 Do(s,i){let e=this._state;this._state=s;let t=s.toString();s&&this.emit(t,e),this.emit(F.STATECHANGED,s,e,i),this.updateDevTools({value:s,old:e,err:i instanceof Error?i.message:String(i)})}var F=class s extends Ph.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[Lh];r?this.name=r.name+"-"+r.count++:t[Lh]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let i=Object.getPrototypeOf(this),e=vo.get(i)||[],t=new Set,r=[],o=[],n=new Set,a=Object.getPrototypeOf(i);vo.has(a)&&(a.stateDiagram.forEach(l=>t.add(l)),a.allStates.forEach(l=>n.add(l))),e.forEach(({from:l,to:u,action:h})=>{typeof l=="string"?r.push({from:l,to:u,action:h}):l.length?l.forEach(f=>{r.push({from:f,to:u,action:h})}):o.push({to:u,action:h})}),r.forEach(({from:l,to:u,action:h})=>{n.add(l),n.add(u),n.add(h+"ing"),t.add(`${l} --> ${h}ing : ${h}`),t.add(`${h}ing --> ${u} : ${h} \u{1F7E2}`),t.add(`${h}ing --> ${l} : ${h} \u{1F534}`)}),o.forEach(({to:l,action:u})=>{t.add(`${u}ing --> ${l} : ${u} \u{1F7E2}`),n.forEach(h=>{h!==l&&t.add(`${h} --> ${u}ing : ${u}`)})});let d=[...t];return Object.defineProperties(i,{stateDiagram:{value:d},allStates:{value:n}}),d}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={}){I_(s.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){Do.call(this,i)}};F.STATECHANGED="stateChanged";F.UPDATEAFSM="updateAFSM";F.INIT="[*]";F.ON="on";F.OFF="off";F.instances=new Map;F.instances2=new WeakMap;var Pd=typeof window!="undefined",wh=Pd&&window.requestIdleCallback||function(s){let i=Date.now();return setTimeout(()=>{s({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-i))}})},1e3)},A_=Pd&&window.cancelIdleCallback||function(s){clearTimeout(s)},xh=Pd&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),Ne=class Ne{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=L(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,Ne.isBreakLoop(i)};return i.intervalID=setInterval(e,i.delay)}static intervalInWorker(i){Ne.sharedWorker||(Ne.sharedWorker=new Worker(URL.createObjectURL(new Blob([`
|
|
9
|
+
`,g+=s)),o&&(g+=`
|
|
10
|
+
Refer to: ${_h("en",d)}
|
|
11
|
+
`),g}var Ml=ki(vh(),1);var h_=1,f_=0,zc=class{constructor(t=!0){u(this,"countMap",new Map);u(this,"distributionMap",new Map);u(this,"version");u(this,"log",F.createLogger({id:"kv"}));t&&(L.on("102",({track:e,cost:r})=>{this.addSuccessEvent({key:e.kind===N.AUDIO?501700:511700,cost:r})}),L.on("103",({track:e,error:r})=>{this.addFailedEvent({key:e.kind===N.AUDIO?501700:511700,error:r})}))}getReportData(){let t={msg_sdk_basic_info:{uint32_sdk_version:_c(this.version||st),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(([e,r])=>({uint32_key:e,uint32_count:r})),stats_distribution:[...this.distributionMap.entries()].map(([e,r])=>({uint32_key:e,distribution_items:[...r.entries()].map(([o,s])=>({uint32_item_key:o,uint32_item_value:s}))}))};return this.countMap.clear(),this.distributionMap.clear(),t}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(t){let e=+String(t).slice(-3);return e>=700&&e<799}isErrorCodeKey(t){let e=+String(t).slice(-3);return e>=600&&e<699}isCountKey(t){let e=+String(t).slice(-3);return e>=0&&e<599}isNumberKey(t){let e=+String(t).slice(-3);return e>=800&&e<899}addCount({key:t,useUV:e=!1}){if(!this.isCountKey(t)){this.log.debug(`${t} is not count key, last 3 number should be 0~599`);return}e&&this.countMap.has(t)||this.countMap.set(t,(this.countMap.get(t)||0)+1)}addEnum({key:t,value:e,useUV:r=!0}){var s;if(!this.isEnumKey(t))return this.log.debug(`${t} is not enum key, last 3 number should be 700~799`);if(r&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let o=((s=this.distributionMap)==null?void 0:s.get(t))||new Map;o.set(e,(o.get(e)||0)+1),this.distributionMap.set(t,o)}addNumber({key:t,value:e,split:r=100,useUV:o=!1}){var d;if(!this.isNumberKey(t))return this.log.debug(`${t} is not number key, last 3 number should be 800~899`);if(o&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let s=((d=this.distributionMap)==null?void 0:d.get(t))||new Map,n=0;if(We(r))n=Math.floor(e/r);else for(let m=r.length-1;m>0;m--)if(e>r[m]){n=m;break}s.set(n,(s.get(n)||0)+1),this.distributionMap.set(t,s)}addSuccessEvent({key:t,cost:e,timeKey:r,split:o}){if(t&&(this.addEnum({key:t,value:h_,useUV:!1}),e)){let s=+String(t).slice(-3);s<800&&s>=700?this.addNumber({key:r||t+100,value:e,split:o}):r||this.log.debug(`time stat ignored, ${t}`)}}addFailedEvent({key:t,error:e}){if(!t)return;let r=q.UNKNOWN;e&&(We(e)?r=e:(!V(e.extraCode)||!V(e.code))&&(r=e.extraCode||e.code)),this.addEnum({key:t,value:f_,useUV:!1}),this.addEnum({key:t,value:Math.abs(r),useUV:!1})}},Jc=(ie=>(ie[ie.enterRoom=500700]="enterRoom",ie[ie.exitRoom=500701]="exitRoom",ie[ie.switchRole=500702]="switchRole",ie[ie.destroy=500703]="destroy",ie[ie.startLocalAudio=500704]="startLocalAudio",ie[ie.updateLocalAudio=500705]="updateLocalAudio",ie[ie.stopLocalAudio=500706]="stopLocalAudio",ie[ie.startLocalVideo=500707]="startLocalVideo",ie[ie.updateLocalVideo=500708]="updateLocalVideo",ie[ie.stopLocalVideo=500709]="stopLocalVideo",ie[ie.startScreenShare=500710]="startScreenShare",ie[ie.updateScreenShare=500711]="updateScreenShare",ie[ie.stopScreenShare=500712]="stopScreenShare",ie[ie.startRemoteVideo=500713]="startRemoteVideo",ie[ie.updateRemoteVideo=500714]="updateRemoteVideo",ie[ie.stopRemoteVideo=500715]="stopRemoteVideo",ie[ie.muteRemoteAudio=500716]="muteRemoteAudio",ie[ie.setRemoteAudioVolume=500717]="setRemoteAudioVolume",ie[ie.use=500718]="use",ie[ie.sendSEIMessage=5e5]="sendSEIMessage",ie[ie.sendCustomMessage=500001]="sendCustomMessage",ie))(Jc||{}),Dl=(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))(Dl||{}),Nl=(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))(Nl||{}),wl=(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))(wl||{});var g_=new zc(!0),Vo=new zc(!1);var X=g_;var xe={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1}},E_=new Map([[Ht,["Firefox",Sc]],[Ds,["Edg",Ac]],[Ps,["Chrome",Vc]],[At,["Safari",si]],[Ir,["TBS",vc]],[Ns,["XWEB",Cc]],[ws&&$i,["WeChat",Dc]],[xn,["QQ(Win)",Nc]],[Os,["QQ(Mobile)",Rs]],[Ms,["QQ(Mobile X5)",Rs]],[kn,["QQ(Mac)",wc]],[Ln,["QQ(iPad)",Mc]],[Vn,["MI",Oc]],[Fn,["HW",Pc]],[$n,["Samsung",xc]],[Bn,["OPPO",kc]],[Hn,["VIVO",Lc]],[Cs,["EDGE",yc]],[On,["SogouMobile",bc]],[Pn,["Sogou",Rc]]]);function Qc(){let i=E_.get(!0),t=i?i[0]:"unknown",e=i?i[1]:"unknown";return{browserName:t,browserVersion:e}}var Pl=function(){return!(el||Cs||Ds&&Zu<80||Ht&&Yu<56)},Dh=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder","MediaStreamTrackGenerator"].every(t=>t in window)},Yc=function(){if(!navigator.mediaDevices)return ui()||F.error(Jt.NOT_SUPPORTED_MEDIA),!1;let i=["getUserMedia","enumerateDevices"];return i.filter(t=>t in navigator.mediaDevices).length===i.length},Ch=!1;function ui(){return location.protocol==="http:"&&!yr?(Ch||F.error($e({key:Fe.NOT_SUPPORTED_HTTP})),Ch=!0,!0):!1}var xl=function(){return(window==null?void 0:window.OffscreenCanvas)&&(window==null?void 0:window.MediaStreamTrackProcessor)&&(window==null?void 0:window.MediaStreamTrackGenerator)},Ol=function(){return A(this,null,function*(){if(xe.detail.isH264EncodeSupported&&xe.detail.isVp8EncodeSupported)return{isH264EncodeSupported:xe.detail.isH264EncodeSupported,isVp8EncodeSupported:xe.detail.isVp8EncodeSupported};let i,t=!1,e=!1;try{let r=new RTCPeerConnection,o=document.createElement(N.CANVAS);o.getContext("2d");let s=o.captureStream(0);return r.addTrack(s.getVideoTracks()[0],s),i=yield r.createOffer(),i.sdp.toLowerCase().indexOf("h264")!==-1&&(t=!0),i.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),r.close(),xe.detail.isH264EncodeSupported=t,xe.detail.isVp8EncodeSupported=e,{isH264EncodeSupported:xe.detail.isH264EncodeSupported,isVp8EncodeSupported:xe.detail.isVp8EncodeSupported}}catch(r){return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1}}})},Nh=function(){return A(this,null,function*(){if(xe.detail.isH264DecodeSupported&&xe.detail.isVp8DecodeSupported)return{isH264DecodeSupported:xe.detail.isH264DecodeSupported,isVp8DecodeSupported:xe.detail.isVp8DecodeSupported};let i,t=!1,e=!1;try{let r=new RTCPeerConnection;return i=yield r.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0}),i.sdp.toLowerCase().indexOf("h264")!==-1&&(t=!0),i.sdp.toLowerCase().indexOf("vp8")!==-1&&(e=!0),r.close(),{isH264DecodeSupported:t,isVp8DecodeSupported:e}}catch(r){return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1}}})},Zc=Tc(()=>A(void 0,null,function*(){if(xe.result&&xe.detail.isH264EncodeSupported&&xe.detail.isVp8EncodeSupported&&xe.detail.isH264DecodeSupported&&xe.detail.isVp8DecodeSupported)return xe;let i=Date.now(),t=Pl(),e=Ul(),r=Dh(),o=Yc(),{isH264EncodeSupported:s,isVp8EncodeSupported:n}=yield Ol(),{isH264DecodeSupported:d,isVp8DecodeSupported:m}=yield Nh();if(!s||!n){let l=yield Ol();F.warn(`detect encode again h264:${s} vp8:${n} result: ${JSON.stringify(l)}`),s=l.isH264EncodeSupported,n=l.isVp8EncodeSupported}if(s&&d&&ut&&ii&&!Ns&&!Ir){let{encode:l,decode:g}=yield T_();s=l,d=g}return xe.result=t&&e&&o&&(s||n)&&(d||m),xe.detail.isBrowserSupported=t,xe.detail.isWebRTCSupported=e,xe.detail.isWebCodecsSupported=r,xe.detail.isMediaDevicesSupported=o,xe.detail.isScreenShareSupported=ea(),xe.detail.isSmallStreamSupported=ta(),xe.detail.isH264EncodeSupported=s,xe.detail.isVp8EncodeSupported=n,xe.detail.isH264DecodeSupported=d,xe.detail.isVp8DecodeSupported=m,xe.result||F.error(`${navigator.userAgent} ${gc(xe.detail,!1)}`),O_(),X.addNumber({key:523800,value:Date.now()-i}),xe})),__=function(){return xe.result},ea=function(){return!!(navigator.mediaDevices&&navigator.mediaDevices.getDisplayMedia)},Xc=null;function T_(){return A(this,null,function*(){return Xc||(Xc=new Promise(i=>A(this,null,function*(){let t={encode:!1,decode:!1},e=()=>{};try{let r=document.createElement("canvas"),o=r.getContext("2d");r.width=320,r.height=240;let s=setInterval(()=>{o.fillText("test",Math.floor(Math.random()*320),Math.floor(Math.random()*240))},66),n=-1,d=-1;e=()=>{clearInterval(n),clearInterval(s),clearTimeout(d),l.close(),g.close(),m.getTracks().forEach(P=>P.stop())},d=setTimeout(()=>{e(),i(t)},2*1e3);let m=r.captureStream(),l=new RTCPeerConnection({}),g=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});l.addEventListener("icecandidate",P=>g.addIceCandidate(P.candidate)),g.addEventListener("icecandidate",P=>l.addIceCandidate(P.candidate)),l.addTrack(m.getVideoTracks()[0],m);let _=yield l.createOffer();yield l.setLocalDescription(_),yield g.setRemoteDescription(_);let S=yield g.createAnswer(),v=Ml.default.parse(S.sdp),x=v.media[0].rtp.findIndex(P=>P.codec==="H264");v.media[0].rtp=[v.media[0].rtp[x]],v.media[0].fmtp=v.media[0].fmtp.filter(P=>P.payload===v.media[0].rtp[0].payload),v.media[0].rtcpFb&&(v.media[0].rtcpFb=v.media[0].rtcpFb.filter(P=>P.payload===v.media[0].rtp[0].payload)),S.sdp=Ml.default.write(v),yield g.setLocalDescription(S),yield l.setRemoteDescription(S),n=setInterval(()=>A(this,null,function*(){t.encode&&t.decode&&(e(),i(t));let[P,M]=yield Promise.all([l.getSenders()[0].getStats(),g.getReceivers()[0].getStats()]);t.encode||P.forEach(G=>{G.type==="outbound-rtp"&&G.mediaType===N.VIDEO&&G.bytesSent>0&&(t.encode=!0)}),t.decode||M.forEach(G=>{G.type==="inbound-rtp"&&G.mediaType===N.VIDEO&&G.bytesReceived>0&&(t.decode=!0)})}),100)}catch(r){e(),F.warn("detectH264Supported failed",r),i({encode:!0,decode:!0})}})).then(i=>(i.encode||(i.decode=!0),(!i.encode||!i.decode)&&F.warn(`detectH264Supported encode: ${i.encode} decode: ${i.decode} ${Tr}`),i)),Xc)})}var I_=(i,t,e)=>{location.protocol==="http:"&&!yr&&(i[t]=()=>{throw new ae({code:q.INVALID_OPERATION,message:Jt.NOT_SUPPORTED_HTTP})})},S_=function(i){return i.type==="candidate-pair"&&i.nominated&&(i.state==="in-progress"||i.state==="succeeded")?!(dt(i.selected)&&!i.selected):!1};function wh(){let i="";if(screen.width){let t=screen.width?screen.width*window.devicePixelRatio:"",e=screen.height?screen.height*window.devicePixelRatio:"";i+=`${t} * ${e}`}return i}function Mh(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function Oh(){let i={isSupported:!1},t=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let e=0;e<t.length;e++)if(t[e]in window){i.isSupported=!0;break}return i.isSupported}function Ph(){return"captureStream"in HTMLCanvasElement.prototype}function ta(){return ws||mt||oi&&oi<63?!1:!!(Pl()&&Ph())}var y_=function(){if(V(window.RTCRtpTransceiver)||!kl()||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;let i=null,t=!1;try{i=new RTCPeerConnection({sdpSemantics:Bu}),i.addTransceiver(N.AUDIO),t=!0}catch(e){}return i==null||i.close(),t};function A_(){return"RTCPeerConnection"in window&&"getReceivers"in window.RTCPeerConnection.prototype}function xh(){return"RTCPeerConnection"in window&&"getSenders"in window.RTCPeerConnection.prototype}function b_(){return"RTCPeerConnection"in window&&"getTransceivers"in window.RTCPeerConnection.prototype}function kl(){return er===11&&!al?!1:"RTCPeerConnection"in window&&"addTransceiver"in window.RTCPeerConnection.prototype}var R_=!(!kl()||ii&&oi<86);function v_(){return"RTCRtpTransceiver"in window&&"stop"in window.RTCRtpTransceiver.prototype}var ra="RTCRtpSender"in window;function C_(){return ra&&"replaceTrack"in window.RTCRtpSender.prototype}function D_(){return ra&&"setParameters"in window.RTCRtpSender.prototype&&xh()}var N_="RTCRtpReceiver"in window&&"getSynchronizationSources"in window.RTCRtpReceiver.prototype,Fs=window.MediaStreamTrack&&"getSettings"in MediaStreamTrack.prototype,Ll=window.MediaStreamTrack&&"getCapabilities"in MediaStreamTrack.prototype,ia=ra&&"createEncodedStreams"in window.RTCRtpSender.prototype&&Uc()>=86,kh="RTCRtpScriptTransform"in window,oa=ra&&(ia||kh),Ul=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(t=>t in window).length>0};function Lh(){let i={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return V(window.AudioDecoder)||(i.AudioDecoder=!0),V(window.AudioEncoder)||(i.AudioEncoder=!0),V(window.VideoDecoder)||(i.VideoDecoder=!0),V(window.VideoEncoder)||(i.VideoEncoder=!0),V(window.ImageDecoder)||(i.ImageDecoder=!0),i}function Uh(){return"mediaSession"in navigator&&!V(navigator.mediaSession.setActionHandler)}function Vh(){return!V(window.WebTransport)}function w_(){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 M_(){let i={browser:`${Vr.name}/${Vr.version}`,os:xs(),displayResolution:wh(),isScreenShareSupported:ea(),isWebRTCSupported:Ul(),isGetUserMediaSupported:Mh(),isWebAudioSupported:Oh(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:Lh(),isMediaSessionSupported:Uh(),isWebTransportSupported:Vh()};return navigator.userAgent.includes("miniProgram")&&(i.browser=`mini/${i.browser}`),i}var Fh="checkResult";function O_(){Ls.setItem(Fh,{ua:navigator.userAgent,checkResult:xe})}function Vl(){ui();let i=Ls.getItem(Fh);i&&i.ua===navigator.userAgent&&(xe=i.checkResult),Zc()}function li(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var P_="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;var Bh=ki(Wi(),1);var $h=Symbol("instance"),cA=Symbol("abortCtrl"),Kc=Symbol("cacheResult"),sa=class{constructor(t,e,r){this.oldState=t,this.newState=e,this.action=r,this.aborted=!1}abort(t){this.aborted=!0,ca.call(t,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},na=class extends Error{constructor(t,e,r){super(e),this.state=t,this.message=e,this.cause=r}};function x_(i){return typeof i=="object"&&i&&"then"in i}var aa=new Map;function Je(i,t,e={}){return(r,o,s)=>{let n=e.action||o;if(!e.context){let m=aa.get(r)||[];aa.has(r)||aa.set(r,m),m.push({from:i,to:t,action:n})}let d=s.value;s.value=function(...m){let l=this;if(e.context&&(l=oe.get(typeof e.context=="function"?e.context.call(this,...m):e.context)),l.state===t)return e.sync?l[Kc]:Promise.resolve(l[Kc]);l.state instanceof sa&&l.state.action==e.abortAction&&l.state.abort(l);let g=null;Array.isArray(i)?i.length==0?l.state instanceof sa&&l.state.abort(l):(typeof l.state!="string"||!i.includes(l.state))&&(g=new na(l._state,`${l.name} ${n} to ${t} failed: current state ${l._state} not from ${i.join("|")}`)):i!==l.state&&(g=new na(l._state,`${l.name} ${n} to ${t} failed: current state ${l._state} not from ${i}`));let _=M=>{if(e.fail&&e.fail.call(this,M),e.sync){if(e.ignoreError)return M;throw M}else return e.ignoreError?Promise.resolve(M):Promise.reject(M)};if(g)return _(g);let S=l.state,v=new sa(S,t,n);ca.call(l,v);let x=M=>{var G;return l[Kc]=M,v.aborted||(ca.call(l,t),(G=e.success)===null||G===void 0||G.call(this,l[Kc])),M},P=M=>(ca.call(l,S,M),_(M));try{let M=d.apply(this,m);return x_(M)?M.then(x).catch(P):e.sync?x(M):Promise.resolve(x(M))}catch(M){return P(new na(l._state,`${l.name} ${n} from ${i} to ${t} failed: ${M}`,M instanceof Error?M:new Error(String(M))))}}}}var k_=typeof window!="undefined"&&window.__AFSM__?(e,r)=>{window.dispatchEvent(new CustomEvent(e,{detail:r}))}:typeof importScripts!="undefined"?(e,r)=>{postMessage({type:e,payload:r})}:()=>{};function ca(i,t){let e=this._state;this._state=i;let r=i.toString();i&&this.emit(r,e),this.emit(oe.STATECHANGED,i,e,t),this.updateDevTools({value:i,old:e,err:t instanceof Error?t.message:String(t)})}var oe=class i extends Bh.default{constructor(t,e,r){super(),this.name=t,this.groupName=e,this._state=i.INIT,t||(t=Date.now().toString(36)),r?Object.setPrototypeOf(this,r):r=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let o=r[$h];o?this.name=o.name+"-"+o.count++:r[$h]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let t=Object.getPrototypeOf(this),e=aa.get(t)||[],r=new Set,o=[],s=[],n=new Set,d=Object.getPrototypeOf(t);aa.has(d)&&(d.stateDiagram.forEach(l=>r.add(l)),d.allStates.forEach(l=>n.add(l))),e.forEach(({from:l,to:g,action:_})=>{typeof l=="string"?o.push({from:l,to:g,action:_}):l.length?l.forEach(S=>{o.push({from:S,to:g,action:_})}):s.push({to:g,action:_})}),o.forEach(({from:l,to:g,action:_})=>{n.add(l),n.add(g),n.add(_+"ing"),r.add(`${l} --> ${_}ing : ${_}`),r.add(`${_}ing --> ${g} : ${_} \u{1F7E2}`),r.add(`${_}ing --> ${l} : ${_} \u{1F534}`)}),s.forEach(({to:l,action:g})=>{r.add(`${g}ing --> ${l} : ${g} \u{1F7E2}`),n.forEach(_=>{_!==l&&r.add(`${_} --> ${g}ing : ${g}`)})});let m=[...r];return Object.defineProperties(t,{stateDiagram:{value:m},allStates:{value:n}}),m}static get(t){let e;return typeof t=="string"?(e=i.instances.get(t),e||i.instances.set(t,e=new i(t,void 0,Object.create(i.prototype)))):(e=i.instances2.get(t),e||i.instances2.set(t,e=new i(t.constructor.name,void 0,Object.create(i.prototype)))),e}static getState(t){var e;return(e=i.get(t))===null||e===void 0?void 0:e.state}updateDevTools(t={}){k_(i.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(t){ca.call(this,t)}};oe.STATECHANGED="stateChanged";oe.UPDATEAFSM="updateAFSM";oe.INIT="[*]";oe.ON="on";oe.OFF="off";oe.instances=new Map;oe.instances2=new WeakMap;var $l=typeof window!="undefined",Hh=$l&&window.requestIdleCallback||function(i){let t=Date.now();return setTimeout(()=>{i({didTimeout:!1,timeRemaining(){return Math.max(0,50-(Date.now()-t))}})},1e3)},L_=$l&&window.cancelIdleCallback||function(i){clearTimeout(i)},Wh=$l&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),gt=class gt{static generateTaskID(){return this.currentTaskID++}static run(t,e,r){r!=null&&r.fps&&(r.delay=r.delay||Number((1e3/r.fps).toFixed(2))),t==="interval"?r=Z({delay:2e3,count:0,backgroundTask:!0},r):t==="ric"?r=Z({delay:1e4,count:0},r):t==="raf"?r=Z({fps:60,delay:16.6,count:0,backgroundTask:!0},r):r=Z({delay:2e3,count:0,backgroundTask:!0},r);let o=Ee(Z({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:t,callback:e},r),{delay:r.delay});return this.taskMap.set(o.taskID,o),this[t](o),o.taskID}static interval(t){let e=()=>{t.callback(),t.loopCount+=1,gt.isBreakLoop(t)};return t.intervalID=setInterval(e,t.delay)}static intervalInWorker(t){gt.sharedWorker||(gt.sharedWorker=new Worker(URL.createObjectURL(new Blob([`
|
|
14
12
|
const timers = new Map();
|
|
15
13
|
self.onmessage = function(e) {
|
|
16
14
|
const { taskId, delay, type } = e.data;
|
|
@@ -23,14 +21,14 @@ Refer to: ${ph("en",a)}
|
|
|
23
21
|
timers.delete(taskId);
|
|
24
22
|
}
|
|
25
23
|
};
|
|
26
|
-
`],{type:"application/javascript"}))),
|
|
27
|
-
${t.stack}`)),this.sendRequest(gi(this._configs.sdkAppId,$i.LOG),r)}sendRequest(i,e){setTimeout(()=>Si({url:i,body:JSON.stringify(e),priority:"low"}).catch(()=>{}),2e3)}},te=new wd;var ti=new WeakMap;function ot({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:d,retry:l,reject:u,retryFuncArgs:h}){var f;i?i.call(this,d,()=>{var g;(g=ti.get(r))!=null&&g.has(o)?l():u(d)},u,h):(f=ti.get(r))!=null&&f.has(o)?l():u(d)},onRetrying(d,l){var u;Jt(e)&&e.call(this,d,l),(u=ti.get(r))!=null&&u.has(o)&&(ti.get(r).get(o).stopRetry=l)},onRetryFailed:t});return n.value=function(...d){let l=ti.get(r);return l?l.set(o,{args:d}):ti.set(r,new Map([[o,{args:d}]])),a.apply(this,d).finally(()=>{var u;return(u=ti.get(r))==null?void 0:u.delete(o)})},n}}function ko({fnName:s,callback:i,validateArgs:e=!0}){return function(t,r,o){let n=o.value;return o.value=function(...a){var d,l;if((d=ti.get(t))!=null&&d.has(s)){let{stopRetry:u,args:h}=ti.get(t).get(s),f=!0;if(e){for(let g of h)if(!a.find(D=>D===g)){f=!1;break}}f&&(i&&i.apply(this,a),u&&u(),(l=ti.get(t))==null||l.delete(s))}return n.apply(this,a)},o}}var ii=class extends F{constructor(e,t){super(e.id,`${t}-player`);this.kind=t;c(this,"id");c(this,"element",null);c(this,"track");c(this,"url");c(this,"attr");c(this,"mode");c(this,"muted");c(this,"_log");c(this,"_pausedRetryCount");c(this,"_isElementPlayingFired",!1);c(this,"_interval");c(this,"_delayDestroyTimeoutId",0);c(this,"_playSuccessResolve");c(this,"_isReplayByRecreateMediaStreamCalled",!1);c(this,"isInAutoPlayFailedState",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=Pc,this._state="STOPPED",this.bindTrackEvents(),this._log.info(`create ${t}-player ${this.id}`)}get isPlaying(){var e;return this._state==="PLAYING"&&((e=this.element)==null?void 0:e.paused)===!1}get isStopped(){return this._state==="STOPPED"}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,e!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return p(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:U.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:I.PLAY_NOT_ALLOWED,message:t})}})}stop(e=0){this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!Xi?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():ed?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 $e(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);ei==null||ei.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(){S.on(E.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(e=this.track){e&&Re(e)}unbindEvents(){this.element&&Re(this.element),this.unbindTrackEvents(),S.off(E.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),Te&&(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}`),te.uploadEvent({log:`stat-${this.kind}-${it.PLAYER_ERROR}-${r}-${navigator.userAgent}`,error:this.element.error}),Qc||zc?this.emit(le.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case m.LOADEDDATA:this.kind===m.VIDEO&&this.emit(le.LOADED_DATA);break;case m.LOADEDMETADATA:this.kind===m.VIDEO&&this.emit(le.LOADED_META_DATA);break}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),te.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),N.addSuccessEvent({key:this.kind===m.AUDIO?506700:516700})}).catch(()=>{var t;this._log.error("replayByRecreateMediaStream failed"),te.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(le.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((t,r)=>{Ei(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)}),Ei(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(le.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(le.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(le.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};y([ot({settings:{retries:2,timeout:0},onError(e,t,r,o){o[0]=(o[0]||1e3)+1e3,t()}})],ii.prototype,"doReplayByRecreateMediaStream",1),y([pe([],"PLAYING",{sync:!0})],ii.prototype,"handlePlaying",1),y([pe("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],ii.prototype,"handlePaused",1),y([pe([],"STOPPED",{sync:!0})],ii.prototype,"handleStopped",1);var Oi="trtc_autoplay",xd=`${Oi}_mask`,ps=`${Oi}_wrapper`,Uh=`${Oi}_header`,Ud=`${Oi}_content`,aa=`${Oi}_action_wrapper`,Vd=`${Oi}_question`,Bd=`${Oi}_collapse`,ca=`${Oi}_action_confirm`,Vh=`${Oi}_detail`,Bh="#2473E8",Hd="dialog",R_=`${Hd}-show`,y_=`${Hd}-1`,b_=`${Hd}-2`,Fh=!1,$d=()=>!!document.querySelector(`.${ps}`),$h=`${Ht}/${bt()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,Hh=`<br><a href='${$h}' target='_blank'>${bt()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,N_=`${bt()?`\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${Hh}`:`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. ${Hh}`}`,Fd=class{constructor(){c(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");c(this,"_dialogNode",null);c(this,"_bodyPosition","");c(this,"_showDetail",!1);c(this,"_isCollapseClicked",!1);c(this,"_isQuestionClicked",!1);if(bt()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!Fh){let i=document.createElement("style");i.innerHTML=`.${xd}{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;}.${xd} div:not(.${aa}){display:block !important;}.${ps}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${ps} a{color:${Bh};}.${Uh}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${Ud}{margin:8px 0;}.${aa}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${Bd}{margin-right:auto;cursor:pointer}.${Vd}{height:100%;line-height:16px;cursor:pointer;}.${ca}{margin-left:8px;color:#fff;background:${Bh};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${ca}:hover{opacity:0.9;}.${Bd},.${ca},.${Ud},.${Vd}{font-size:14px;}@media screen and (max-width:750px){.${ps}{width:80vw;}}`,document.head.appendChild(i),Fh=!0}this.addDiaLog()}createDiaLog(){let i=document.createElement("template");i.innerHTML=`<div class="${xd}"><div class='${ps}'><div class='${Uh}'>${location.host}</div><div class='${Ud}'>${this.content}</div><div class='${Vh}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${N_}</div><div class='${aa}'></div></div></div>`.trim();let e=document.createElement("button");e.className=ca,e.innerText=bt()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let t=document.createElement("div");t.className=Vd,t.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
|
|
24
|
+
`],{type:"application/javascript"}))),gt.sharedWorker.onmessage=e=>{var r;if(e.data.type==="tick"){let o=gt.workerTasks.get(e.data.taskId);o&&(gt.isBreakLoop(o)?((r=gt.sharedWorker)==null||r.postMessage({type:"stop",taskId:o.taskID}),gt.workerTasks.delete(o.taskID)):(o.callback(),o.loopCount+=1))}}),gt.workerTasks.set(t.taskID,t),gt.sharedWorker.postMessage({taskId:t.taskID,delay:t.delay,type:"start"})}static timeout(t){let e=()=>{if(t.callback(),t.loopCount+=1,!gt.isBreakLoop(t))return t.timeoutID=setTimeout(e,t.delay)};return t.timeoutID=setTimeout(e,t.delay)}static ric(t){let e=Te(),r,o=()=>{if(r=Te()-e,r>=t.delay&&(e=Te()-Math.floor(r%t.delay),t.callback(),t.loopCount+=1),!gt.isBreakLoop(t))return t.ricID=Hh(o,{timeout:t.delay})};return t.ricID=Hh(o,{timeout:t.delay})}static raf(t){let e=Te(),r,o=()=>{if(document.hidden&&t.backgroundTask)return r=Te()-e,e=Te(),t.callback(),t.loopCount+=1,gt.isBreakLoop(t)?void 0:t.timeoutID=setTimeout(o,t.delay-Math.floor(r%t.delay));if(r=Te()-e,r>=t.delay&&(e=Te()-Math.floor(r%t.delay),t.callback(),t.loopCount+=1),!gt.isBreakLoop(t))return t.rafID=requestAnimationFrame(o)};if(t.rafID=requestAnimationFrame(o),t.backgroundTask){let s=()=>{if(document.hidden){let n=Te()-e;n>=t.delay?o():t.timeoutID=setTimeout(o,t.delay-n)}};document.addEventListener("visibilitychange",s),t.onVisibilitychange=s,document.hidden&&s()}return t.taskID}static hasTask(t){return this.taskMap.has(t)}static clearTask(t){if(!this.taskMap.has(t))return!0;let{intervalID:e,timeoutID:r,rafID:o,ricID:s,onVisibilitychange:n}=this.taskMap.get(t);return e&&clearInterval(e),r&&clearTimeout(r),o&&Wh&&Wh(o),s&&L_(s),n&&document.removeEventListener("visibilitychange",n),this.taskMap.delete(t),!0}static isBreakLoop(t){return this.hasTask(t.taskID)?t.count!==0&&t.loopCount>=t.count?(this.clearTask(t.taskID),!0):!1:!0}};u(gt,"taskMap",new Map),u(gt,"currentTaskID",1),u(gt,"sharedWorker",null),u(gt,"workerTasks",new Map);var Fl=gt,bt=Fl;var _A={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:N.SEI_MESSAGE,ERROR:"error"};var Ze={LOADED_DATA:N.LOADEDDATA,LOADED_META_DATA:N.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error"};var Hr={};Yr(Hr,{create:()=>Lt,remove:()=>pt});var da=new WeakMap;function Lt(i,t){da.has(i)||da.set(i,[]);let e=da.get(i),o={add:(s,n)=>("addEventListener"in t?(e.push(t.removeEventListener.bind(t,s,n)),t.addEventListener(s,n)):(e.push(t.off.bind(t,s,n)),t.on(s,n)),o)};return o}function pt(i){let t=da.get(i);t&&(t.forEach(e=>e()),da.delete(i))}var Bl=class{constructor(){u(this,"_roomIdMap",new Map);u(this,"_configs");typeof registerProcessor=="undefined"&&(this._configs={sdkAppId:"",userId:"",version:st,env:Zr.QCLOUD,browserVersion:Vr.name+Vr.version,ua:navigator.userAgent})}setConfig({sdkAppId:t,env:e,userId:r,roomId:o}){t!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(t)),this._configs.env=e,this._configs.userId=r,this._roomIdMap.set(r,String(o))}logSuccessEvent(t){yr||!F.isAbleToUpload||this._configs.env===Zr.QCLOUD&&this.uploadEventToKibana(Ee(Z({},t),{result:"success"}))}logFailedEvent(t){if(yr||!F.isAbleToUpload)return;let{eventType:e,code:r,error:o,userId:s}=t,n={roomId:this._roomIdMap.get(s||this._configs.userId),userId:s,eventType:e,result:"failed",code:r||(o==null?void 0:o.extraCode)||(o==null?void 0:o.code)||q.UNKNOWN};this._configs.env===Zr.QCLOUD&&this.uploadEventToKibana(Ee(Z({},n),{error:o}))}uploadEventToKibana(t){let e=`stat-${t.eventType}-${t.result}`;(t.eventType==="delta-join"||t.eventType==="delta-leave"||t.eventType==="delta-publish")&&(e=`${t.eventType}:${t.delta}`),this.uploadEvent({log:e,userId:t.userId}),t.result==="failed"&&(e=`stat-${t.eventType}-${t.result}-${t.code}`,this.uploadEvent({log:e,userId:t.userId,error:t.error}))}uploadEvent({log:t,userId:e,error:r}){let o={timestamp:ic(),sdkAppId:this._configs.sdkAppId,userId:e||this._configs.userId,version:st,log:t};r&&(o.errorInfo=r.message,r.stack&&(o.errorInfo+=`
|
|
25
|
+
${r.stack}`)),this.sendRequest(ti(this._configs.sdkAppId,Li.LOG),o)}sendRequest(t,e){setTimeout(()=>ri({url:t,body:JSON.stringify(e),priority:"low"}).catch(()=>{}),2e3)}},je=new Bl;var Fo=new WeakMap;function Ji({settings:i={retries:5,timeout:2e3},onError:t,onRetrying:e,onRetryFailed:r}){return function(o,s,n){let d=Fi({retryFunction:n.value,settings:i,onError({error:m,retry:l,reject:g,retryFuncArgs:_}){var S;t?t.call(this,m,()=>{var v;(v=Fo.get(o))!=null&&v.has(s)?l():g(m)},g,_):(S=Fo.get(o))!=null&&S.has(s)?l():g(m)},onRetrying(m,l){var g;Vi(e)&&e.call(this,m,l),(g=Fo.get(o))!=null&&g.has(s)&&(Fo.get(o).get(s).stopRetry=l)},onRetryFailed:r});return n.value=function(...m){let l=Fo.get(o);return l?l.set(s,{args:m}):Fo.set(o,new Map([[s,{args:m}]])),d.apply(this,m).finally(()=>{var g;return(g=Fo.get(o))==null?void 0:g.delete(s)})},n}}var Wr=class extends oe{constructor(e,r){super(e.id,`${r}-player`);this.kind=r;u(this,"id");u(this,"element",null);u(this,"track");u(this,"url");u(this,"attr");u(this,"mode");u(this,"muted");u(this,"_log");u(this,"_pausedRetryCount");u(this,"_isElementPlayingFired",!1);u(this,"_interval");u(this,"_delayDestroyTimeoutId",0);u(this,"_playSuccessResolve");u(this,"_isReplayByRecreateMediaStreamCalled",!1);u(this,"isInAutoPlayFailedState",!1);this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=Hu,this._state="STOPPED",this.bindTrackEvents(),this._log.info(`create ${r}-player ${this.id}`)}get isPlaying(){var e;return this._state==="PLAYING"&&((e=this.element)==null?void 0:e.paused)===!1}get isStopped(){return this._state==="STOPPED"}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,e!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}play(){return A(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,r)=>{this._playSuccessResolve=e,this.element.play().then(e,r)})}catch(e){let r=$e({key:Fe.PLAY_FAILED,data:{media:this.kind,error:e}});if(this.track&&!this.track.muted&&this._log.warn(e),r.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new ae({code:q.PLAY_NOT_ALLOWED,message:r})}})}stop(e=0){this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!Bi?this._delayDestroyTimeoutId||(this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(N.ENDED),this._interval>0&&bt.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():sl?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 Lt(this.element,this.element).add(N.PLAYING,e).add(N.ENDED,e).add(N.PAUSE,e).add(N.ERROR,e).add(N.LOADEDDATA,e).add(N.LOADEDMETADATA,e)}}bindTrackEvents(e=this.track){if(e){let r=this.handleTrackEvent.bind(this);Hr==null||Hr.create(e,e).add(N.ENDED,r).add(N.MUTE,r).add(N.UNMUTE,r),e.readyState===N.ENDED&&this.handleTrackEvent({type:N.ENDED}),e.muted&&this.handleTrackEvent({type:N.MUTE})}}bindAutoPlayEvent(){L.on(U.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}unbindTrackEvents(e=this.track){e&&pt(e)}unbindEvents(){this.element&&pt(this.element),this.unbindTrackEvents(),L.off(U.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this)}handleElementEvent(e){switch(e.type){case N.PLAYING:this.isInAutoPlayFailedState=!1,this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(N.PLAYING),this._interval&&(bt.clearTask(this._interval),this._interval=-1);break;case N.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(N.ENDED);break;case N.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(N.PAUSE),mt&&(this._interval=bt.run("timeout",()=>{this.element&&this._state==="PAUSED"&&this.resume()},{delay:3e3}));break;case N.ERROR:if(this.element&&this.element.error){this.handlePaused(N.ERROR);let{code:o,message:s}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${o} message: ${s} userAgent: ${navigator.userAgent}`),je.uploadEvent({log:`stat-${this.kind}-${Kr.PLAYER_ERROR}-${o}-${navigator.userAgent}`,error:this.element.error}),rl||tl?this.emit(Ze.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case N.LOADEDDATA:this.kind===N.VIDEO&&this.emit(Ze.LOADED_DATA);break;case N.LOADEDMETADATA:this.kind===N.VIDEO&&this.emit(Ze.LOADED_META_DATA);break}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),je.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),X.addSuccessEvent({key:this.kind===N.AUDIO?506700:516700})}).catch(()=>{var r;this._log.error("replayByRecreateMediaStream failed"),je.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),X.addFailedEvent({key:this.kind===N.AUDIO?506700:516700,error:(r=this.element)==null?void 0:r.error}),this.emit(Ze.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((r,o)=>{Mn(e).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var s,n,d;this._log.warn(`element onerror ${(n=(s=this.element)==null?void 0:s.error)==null?void 0:n.code} fired after recreated mediaStream`),o((d=this.element)==null?void 0:d.error)}),Mn(5e3).then(()=>{var s,n;(!this.isPlaying||(s=this.element)!=null&&s.error)&&o((n=this.element)==null?void 0:n.error),r()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(e){switch(e.type){case N.ENDED:this.handleStopped(N.ENDED);break;case N.MUTE:this.handlePaused(N.MUTE);break;case N.UNMUTE:this._isElementPlayingFired?this.handlePlaying(N.UNMUTE):this.mode>0&&this.handlePlaying(this.mode.toString());break}}handlePlaying(e){var r;(r=this._playSuccessResolve)==null||r.call(this,e),this.emit(Ze.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}handlePaused(e){this.emit(Ze.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}handleStopped(e){this.emit(Ze.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}getElement(){return this.element}};J([Ji({settings:{retries:2,timeout:0},onError(e,r,o,s){s[0]=(s[0]||1e3)+1e3,r()}})],Wr.prototype,"doReplayByRecreateMediaStream",1),J([Je([],"PLAYING",{sync:!0})],Wr.prototype,"handlePlaying",1),J([Je("PLAYING","PAUSED",{ignoreError:!0,sync:!0})],Wr.prototype,"handlePaused",1),J([Je([],"STOPPED",{sync:!0})],Wr.prototype,"handleStopped",1);var mi="trtc_autoplay",Hl=`${mi}_mask`,$s=`${mi}_wrapper`,Gh=`${mi}_header`,Wl=`${mi}_content`,ed=`${mi}_action_wrapper`,Gl=`${mi}_question`,jl=`${mi}_collapse`,td=`${mi}_action_confirm`,jh=`${mi}_detail`,qh="#2473E8",zl="dialog",V_=`${zl}-show`,F_=`${zl}-1`,$_=`${zl}-2`,zh=!1,Jl=()=>!!document.querySelector(`.${$s}`),Xh=`${Pr}/${_r()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,Jh=`<br><a href='${Xh}' target='_blank'>${_r()?"\u5176\u4ED6\u65B9\u6848\uFF1F":"Any other solution?"}</a>`,B_=`${_r()?`\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${Jh}`:`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. ${Jh}`}`,ql=class{constructor(){u(this,"content","\u97F3\u89C6\u9891\u64AD\u653E\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF0C\u8BF7\u70B9\u51FB\u201C\u6062\u590D\u64AD\u653E\u201D\u3002");u(this,"_dialogNode",null);u(this,"_bodyPosition","");u(this,"_showDetail",!1);u(this,"_isCollapseClicked",!1);u(this,"_isQuestionClicked",!1);if(_r()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!zh){let t=document.createElement("style");t.innerHTML=`.${Hl}{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;}.${Hl} div:not(.${ed}){display:block !important;}.${$s}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${$s} a{color:${qh};}.${Gh}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${Wl}{margin:8px 0;}.${ed}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${jl}{margin-right:auto;cursor:pointer}.${Gl}{height:100%;line-height:16px;cursor:pointer;}.${td}{margin-left:8px;color:#fff;background:${qh};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${td}:hover{opacity:0.9;}.${jl},.${td},.${Wl},.${Gl}{font-size:14px;}@media screen and (max-width:750px){.${$s}{width:80vw;}}`,document.head.appendChild(t),zh=!0}this.addDiaLog()}createDiaLog(){let t=document.createElement("template");t.innerHTML=`<div class="${Hl}"><div class='${$s}'><div class='${Gh}'>${location.host}</div><div class='${Wl}'>${this.content}</div><div class='${jh}' style="visibility:hidden;width:100%;height:0;font-size:12px;color:gray;">${B_}</div><div class='${ed}'></div></div></div>`.trim();let e=document.createElement("button");e.className=td,e.innerText=_r()?"\u6062\u590D\u64AD\u653E":"Resume",e.onclick=this.onConfirm.bind(this);let r=document.createElement("div");r.className=Gl,r.innerHTML=`<?xml version="1.0" encoding="UTF-8"?>
|
|
28
26
|
<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
27
|
<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
28
|
<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
29
|
<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
30
|
</svg>
|
|
33
|
-
`,t.onclick=this.onQuestionClick.bind(this);let r=document.createElement("div");r.className=Bd,r.innerText=`${bt()?"\u8BE6\u60C5 >":"Detail >"}`,r.onclick=this.onCollapseClick.bind(this);let o=i.content.firstChild,n=o.querySelector(`.${aa}`);return n.appendChild(r),n.appendChild(t),n.appendChild(e),o}addDiaLog(){$d()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${ps}`).onclick=i=>i.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",C.info("show autoplay dialog"),te.uploadEvent({log:R_}))}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"),S.emit(E.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let i=this._dialogNode.querySelector(`.${Vh}`);i.style.visibility=`${this._showDetail?"hidden":"visible"}`,i.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||te.uploadEvent({log:y_}),this._isCollapseClicked=!0}onQuestionClick(){window.open($h,"_blank"),this._isQuestionClicked||te.uploadEvent({log:b_}),this._isQuestionClicked=!0}},Gh=Fd;var pt=class extends ii{constructor(e){super(e,m.VIDEO);c(this,"stat",{});c(this,"_calculateTimeout",-1);c(this,"viewMirror",!1);c(this,"objectFit");c(this,"container");c(this,"canvas");this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,T(e.viewMirror)||(this.viewMirror=e.viewMirror),T(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}get isPlaying(){var e;return this._state!=="PLAYING"||this.element&&this.element.paused?!1:((e=this.track)==null?void 0:e.readyState)==="live"&&!this.track.muted}initializeElement(){var t;let e=document.createElement(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.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&&!$d()&&(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}setPoster(e){this.element&&(this.element.poster=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(le.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(Cr()&&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 Rr(s,i){return p(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 Mo;typeof AudioContext!="undefined"?Mo=AudioContext:typeof webkitAudioContext!="undefined"?Mo=webkitAudioContext:typeof mozAudioContext!="undefined"&&(Mo=mozAudioContext);var wt,Wh=-1;Jh();function Jh(){try{if(wt)return;wt=new Mo({sampleRate:48e3}),wt.onstatechange=()=>{C.info(`context state: ${wt.state}${wt.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),fs()},clearTimeout(Wh)}catch(s){C.error(`initAudioContext failed: ${s} typeof AudioContextClass: ${typeof Mo}`),Wh=setTimeout(Jh,1e3)}}var fs=()=>{wt.state==="suspended"?(_s(),document.addEventListener("click",fs)):wt.state==="interrupted"?_s():(document.removeEventListener("visibilitychange",fs),document.removeEventListener("click",fs))},Gd=0,Wd=-1;function _s(){return new Promise((s,i)=>{if(wt.state==="running")return s();Date.now()-Gd<1e3?(clearTimeout(Wd),Wd=setTimeout(()=>{Gd=Date.now(),wt.resume().then(s,i)},1e3)):(clearTimeout(Wd),Gd=Date.now(),wt.resume().then(s,i))}).catch(s=>{C.warn(`context resume failed: ${s}`),document.addEventListener("visibilitychange",fs)})}document.addEventListener("click",fs);var ve=s=>wt;var Ge=class{constructor(){c(this,"node");c(this,"node2");c(this,"pre",new Set);c(this,"next",new Set);c(this,"context");c(this,"connectedNodes",new Set);c(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(i){this._channelCount=i,this.setChannelCount(this.node,i),this.setChannelCount(this.node2,i),this.next.forEach(e=>e.channelCount=i)}setChannelCount(i,e){!i||i instanceof ScriptProcessorNode||(i.channelCountMode="explicit",i.channelCount=e||this.channelCount||1)}setContext(i){this.context=i,this.node&&i.addMixWeight()}removeContext(){var i;this.node&&((i=this.context)==null||i.reduceMixWeight()),delete this.context}replaceNode(i){var e;if(i!==this.node)try{this.node?this._disconnect():(e=this.context)==null||e.addMixWeight(),this.node=i,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(t){C.error(t)}}setNode(i,e){var t;if(!this.node)try{(t=this.context)==null||t.addMixWeight(),this.node=i,this.setChannelCount(this.node),e&&(this.node2=e,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),N.addSuccessEvent({key:502701})}catch(r){C.error(r),N.addFailedEvent({key:502701,error:r})}}deleteNode(){var i;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(i=this.context)==null||i.reduceMixWeight(),this.preNodeReconnect(),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.node2||this.node).connect(i),this.connectedNodes.add(i),!0)}_disconnect(){this.connectedNodes.forEach(i=>{var e;return(e=this.node2||this.node)==null?void 0:e.disconnect(i)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(...i){return i.forEach(e=>{this.next.add(e),e.pre.add(this)}),this}},da=class extends Ge{constructor(e=256){super();this.fftSize=e;c(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}},Lo=class{constructor(){c(this,"source",new Ge);c(this,"gain",new Ge);c(this,"destination",new Ge)}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(ve().createGain()),this.gain.node.gain.value=i}replaceSource(i){this.source.replaceNode(Jd(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}},gs=class extends Lo{constructor(e){super();this.context=e;c(this,"denoiser",new Ge);c(this,"voiceChanger",new Ge);this.source.pipeTo(this.denoiser.pipeTo(this.voiceChanger.pipeTo(this.gain.pipeTo(this.destination))))}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.denoiser.setContext(this.context),this.voiceChanger.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){this.context.inputs.has(this)&&(this.destination.deleteNode(),this.source.removeContext(),this.denoiser.removeContext(),this.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.denoiser.deleteNode(),this.voiceChanger.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){if(e===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e}},la=class{constructor(){c(this,"audioContext",ve("audio-mixer"));c(this,"destination",this.audioContext.createMediaStreamDestination());c(this,"inputs",new Set);c(this,"mixWeight",0);this.destination.channelCount=1}addMixWeight(i=1){this.mixWeight+=i,this.mixWeight-1===i+1>>1&&this.mixOnChange()}reduceMixWeight(i=1){this.addMixWeight(-i)}close(){this.inputs.forEach(i=>i.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},jh=new WeakMap;function Jd(s){let i=jh.get(s);if(i)return i;let e=ve();if(s instanceof HTMLAudioElement)i=e.createMediaElementSource(s);else if(s instanceof MediaStreamTrack)i=e.createMediaStreamSource(new MediaStream([s]));else return s;return jh.set(s,i),i}var ft=class ft{constructor(i){c(this,"_volume",0);c(this,"_volumeDb",0);c(this,"_log");c(this,"_scriptProcessorNode",null);c(this,"_audioWorkletNode",null);c(this,"_interval",200);c(this,"ready",this.preload());let{log:e}=i;this._log=e,S.on(E.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-ft.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!ft.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);';ft.workletReady=Rr(ft.audioContext,URL.createObjectURL(new Blob([i],{type:"application/javascript"})))}return ft.workletReady.then(()=>this.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(ft.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=e=>{ft.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}`),te.logFailedEvent({userId:this._log.userId,eventType:it.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=ve("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{ft.lastMessageTime=Date.now();let e=i.inputBuffer.getChannelData(0),t=0;for(let r=0;r<e.length;++r)t+=e[r]*e[r];this._volume=Math.sqrt(t/e.length)||0}}catch(i){this._log.error(`volumeMeter init script processor error: ${i}`)}}destroy(){this._scriptProcessorNode&&(this._scriptProcessorNode.onaudioprocess=null),this._audioWorkletNode&&(this._audioWorkletNode.port.postMessage({name:"stop"}),this._audioWorkletNode.port.onmessage=null),this._audioWorkletNode=null,this._scriptProcessorNode=null,S.off(E.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})}};c(ft,"lastMessageTime",0),c(ft,"audioContext",ve("volume-meter")),c(ft,"workletReady");var ua=ft,ha=class extends Ge{constructor(e){super();c(this,"_volumeMeter");this._volumeMeter=new ua(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return p(this,null,function*(){yield this._volumeMeter.preload(),this.setNode(this._volumeMeter.node)})}getCalculatedVolume(){return this._volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this._volumeMeter.getInternalAudioLevel()}getVolumeDb(){return this._volumeMeter.getVolumeDb()}write(e){if(this.node){let t=e.allocationSize({planeIndex:0}),r=new Float32Array(t>>2);e.copyTo(r,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:r},[r.buffer]),e.close()}}},yr=ua;var Qh=Be(ze(),1);var Xh=s=>i=>i.deviceId===s;var Po=class{constructor(i,e="Input"){c(this,"kind");c(this,"type");c(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&&Ts(this.devices[0])){this.devices=t;return}e&&(t.forEach(r=>{if(r.deviceId&&!this.devices.find(Xh(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(Xh(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)}},jd=class extends Qh.EventEmitter{constructor(){super();c(this,"audioInputs",new Po(m.AUDIO));c(this,"videoInputs",new Po(m.VIDEO));c(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(){ma().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return p(this,arguments,function*(e=0){let t=yield ma(e);return this.audioInputs.update(t,this),this.videoInputs.update(t,this),this.audioOutputs.update(t,this),this})}},ke=Gs||Gr?null:new jd;function Ts(s){return s.deviceId===s.groupId&&s.groupId===""}function ma(){return p(this,arguments,function*(s=0){if(vi()||!ta())return[];let i=yield navigator.mediaDevices.enumerateDevices();if(s!==0){let e={audio:!1,video:!1};if(i.forEach(t=>{Ts(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&&_s()}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&&qd.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(r.getCapabilities=()=>e.getCapabilities()),r})})}function nt(s=!1){return ke.update(s?1:0).then(i=>i.audioInputs.devices)}function _t(s=!1){return ke.update(s?2:0).then(i=>i.videoInputs.devices)}var zh=!1;function Yh(){return p(this,null,function*(){try{zh||(zh=!0,C.info(`speakers:${(yield Zi()).map(s=>` ${s.deviceId.slice(0,8)}: ${s.label}`)}`))}catch(s){}})}function Zi(s=!1){return p(this,null,function*(){return(Te||Me)&&(s=!1),ke.update(s?1:0).then(i=>i.audioOutputs.devices)})}var qd=new Set;function Kh(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!!qd.has(t)}function Zh(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!!qd.has(t)}function Xd(s,i){return p(this,null,function*(){let t=(yield nt()).find(r=>r.deviceId===lr);return!i&&(t==null?void 0:t.groupId)===s||(t==null?void 0:t.groupId)===s&&t.label===i})}function em(o){return p(this,arguments,function*({newDeviceId:s,oldDeviceId:i,oldGroupId:e,oldLabel:t,kind:r}){return s!==i?!1:r===m.AUDIO&&s===lr?yield Xd(e,t):!0})}var pa,zd=class extends Lo{constructor(e){super();this.log=e;c(this,"volumeMeter");c(this,"volumeDestination");c(this,"analyser",new da);this.volumeMeter=new ha({log:this.log}),this.volumeDestination=new Ge,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},fa=class s extends ii{constructor(e){super(e,m.AUDIO);c(this,"_outputDeviceId");c(this,"_volume",1);c(this,"_destination",ve("player").createMediaStreamDestination());c(this,"pipeline");c(this,"volumeMeterMode","worklet");this.mode=0,this.pipeline=new zd(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((Xt==="15.2"||Xt==="15.3"||Xt==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let r=pa||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===pa&&(pa=void 0),this.bindElementEvents()}play(e){return p(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(ve("player").createAnalyser()),Yh(),Fe(s.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(e)}setSinkId(e){return p(this,null,function*(){var t,r;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(r=(t=this.element).setSinkId)==null?void 0:r.call(t,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){this.element&&(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}},_a=class extends fa{setTrack(i){this.track!==i&&(this.unbindTrackEvents(),this.track=i,this.emit(le.MEDIA_TRACK_CHANGED,i),i&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([i]))))}setVolume(i){this._volume=i,this.element&&(this.element.volume=i)}},ga=class extends fa{constructor(e){super(e);c(this,"_sourceElement");c(this,"_output",new Ge);this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter.pipeTo(this._output),this.pipeline.destination))}setOutput(){this.mode=1,this._output.setNode(ve("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(le.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"):Te||(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),Re(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&&Xi&&(pa=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var br=class extends F{constructor({userId:e,sdkAppId:t,mediaType:r,room:o,PlayerClass:n=r===1?ga:pt}){var a;super();c(this,"id",_o());c(this,"userId","");c(this,"isRemote");c(this,"mediaType");c(this,"room");c(this,"user");c(this,"_log");c(this,"_inputTrack");c(this,"_outputTrack");c(this,"isPlayCalled");c(this,"container",null);c(this,"player");c(this,"subVideoPlayerMap");c(this,"muted",!1);c(this,"abortCtrl");c(this,"objectFit","cover");c(this,"mirror");c(this,"isScreen",!1);c(this,"manager");c(this,"trackSettings");c(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 ki?void 0:this.userId,sdkAppId:t,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof ki}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(le.PLAYER_STATE_CHANGED,d=>{S.emit(E.PLAYER_STATE_CHANGED,v({track:this},d)),this.emit("player-state-changed",d)}),this.kind===m.VIDEO&&(this.player.on(le.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(le.LOADED_DATA),S.emit(E.VIDEO_LOADED_DATA,{track:this})}),this.player.on(le.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(le.LOADED_META_DATA)}),this.player.on(le.MEDIA_TRACK_CHANGED,d=>{var l;(l=this.subVideoPlayerMap)==null||l.forEach(u=>u.setTrack(d))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(le.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 p(this,null,function*(){let r=Ie(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(t)}`),t&&!T(t.muted)&&this.setPlayerMute(t.muted),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof pt&&(this.player.setObjectFit(this.objectFit),this.container!==r&&r&&(this.container=r,this.player.setContainer(r)),Ie(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),t)));return}if(t&&!T(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===m.VIDEO)&&this.setPlayerMute(!0),t&&!T(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof pt&&(this.player.setObjectFit(this.objectFit),t&&!T(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,r&&(this.container=r,this.player instanceof pt&&this.player.setContainer(r)),S.emit(E.PLAY_TRACK_START,{track:this}),!this._outputTrack){this.log.info("play has not mediaTrack, abort");return}this._log.info(`play with options: ${JSON.stringify(t)}`);try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(t),Ie(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||T(e)||e===this.mirror)return;this.mirror=e;let r=this.player;t&&(r=t);let o=this.manager;if(_e(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 p(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(d=>n===d)||(o.stop(),(a=this.subVideoPlayerMap)==null||a.delete(n))});for(let[o,n]of e.entries()){let a=this.subVideoPlayerMap.get(n);a?t&&(T(t.objectFit)||a.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(n,new pt({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($c(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(t=>{t.stop()}),this.container=null)}resume(){return p(this,null,function*(){var e;this.isPlayCalled&&(yield(e=this.player)==null?void 0:e.resume())})}close(){this.log.info("close"),this.isPlayCalled&&this.stop(!0)}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),S.emit(e?E.TRACK_MUTED:E.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(e){$e(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){Re(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($c(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 Gh;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 pt?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var n,a,d;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)||((d=this.player.element)==null?void 0:d.videoHeight)||0;e===le.LOADED_META_DATA&&!r&&!o||(e===le.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([pe([],F.INIT,{sync:!0})],br.prototype,"close",1);var v_=Object.prototype.hasOwnProperty,{toString:sC}=Object.prototype;function D_(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(rt(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(v_.call(s,i))return!1;return!0}}return!1}var ri=D_;var O_=function(s){return p(this,null,function*(){let i=M_(s);C.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let e=[],t=[],r=["label","deviceId","groupId"];i.audio&&(e=yield nt(),C.info(`microphones: ${Tt(e.map(o=>L(v({},o),{groupId:o.groupId.substring(0,8)})),{keysToInclude:r})}`)),i.video&&(t=yield _t(),C.info(`cameras: ${Tt(t,{keysToInclude:r})}`));try{let o=yield navigator.mediaDevices.getUserMedia(i);return Od&&o.getTracks().forEach(n=>{C.info(`${n.kind} capabilities: ${Tt(n.getCapabilities(),{keysToInclude:En})}`)}),i.audio&&_s(),o}catch(o){let{message:n}=o;throw o.name==="NotFoundError"&&(s.video&&t&&t.length===0&&(n=V({key:U.CAMERA_NOT_FOUND})),s.audio&&e&&e.length===0&&(n=V({key:U.MICROPHONE_NOT_FOUND}))),new b({code:I.INITIALIZE_FAILED,name:o.name,message:n,constraint:o.constraint})}})},k_=jt({retryFunction:O_,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,(!Me||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&&tm(t[0].microphoneId,!1),t[0].cameraId&&tm(t[0].cameraId,!0)},onRetrying:s=>{C.warn(`getUserMedia NotReadableError observed, retrying [${s}/3]`)},onRetryFailed:s=>{te.logFailedEvent({eventType:it.GET_USER_MEDIA_RETRY,error:s})},onRetrySuccess:s=>{te.logSuccessEvent({eventType:it.GET_USER_MEDIA_RETRY}),te.uploadEvent({log:`stat-${it.GET_USER_MEDIA_RETRY}-success-${s}`})}});function tm(s,i){return p(this,null,function*(){let t=(i?yield _t():yield nt()).find(r=>r.deviceId===s);t&&ce(t.getCapabilities)&&C.warn(Tt(t.getCapabilities(),{keysToInclude:En}))})}function M_(s){return{audio:L_(s),video:P_(s)}}function L_(s){if(!s.audio)return!1;if(s.useTrueAsConstraint)return!0;let i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:s.sampleRate};return!ri(s.microphoneId)&&(i.deviceId=s.useExactDeviceId?{exact:s.microphoneId}:s.microphoneId,s.useDeviceIdOnly)?i:(Y(s.channelCount)&&(i.channelCount=s.channelCount),_e(s.echoCancellation)&&!s.echoCancellation&&(i.echoCancellation=!1),_e(s.noiseSuppression)&&!s.noiseSuppression&&(i.noiseSuppression=!1),_e(s.autoGainControl)&&!s.autoGainControl&&(i.autoGainControl=!1),ri(i)?!0:i)}function P_(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&&!ri(e)?e:(s.width&&(e.width={ideal:s.width},i&&!se&&(e.width.max=s.width)),s.height&&(e.height={ideal:s.height},i&&!se&&(e.height.max=s.height)),se&&kt&&s.width&&s.height&&s.width*s.height<352*288&&(e.width=s.width,e.height=s.height),s.frameRate&&(e.frameRate=s.frameRate),ri(e)?!0:e)}var im=k_;function Ta(s){return z((i,e)=>function(...t){return p(this,null,function*(){return yield s.apply(this,t),i.apply(this,t)})})}function Ke(s){return z((i,e)=>function(...t){return p(this,null,function*(){let r=yield i.apply(this,t);return yield s.call(this,...t),r})})}function Ea(s){return z((i,e)=>function(...t){return p(this,null,function*(){try{return yield i.apply(this,t)}catch(r){s.call(this,r)}})})}function z(s){return function(i,e,t){return t.value=s(t.value,e),t}}var rm=(()=>{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 w_=0,Sa=class{constructor(){c(this,"log",C.createLogger({id:`fq${++w_}`}));c(this,"isRunning",!1);c(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,d)=>{t.resolve=a,t.reject=d});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()})}},wo=new WeakMap,Ia=new WeakMap;function si(s=!1){return function(i,e,t){let r=t.value;return t.value=function(...o){let n=wo.get(this)||new Sa;return wo.set(this,n),n.push({fn:r,args:o,context:this},s)},t}}function sm(s){return function(i,e,t){let r=t.value;return t.value=function(...o){let n=wo.get(this);if(n){let a=n.queue.filter((d,l)=>{if(l===0)return!0;let u=!0;return d.args.forEach(h=>{o.find(f=>f===h)||(u=!1)}),u?(d.reject(new b({code:I.API_CALL_ABORTED,message:s})),!1):!0});n.queue=a}return r.apply(this,o)},t}}function Aa(s){return function(i,e,t){let r=t.value;return t.value=function(...o){var a,d,l;let n=[];return(d=(a=wo.get(this))==null?void 0:a.queue)==null||d.forEach(u=>n.push(u)),(l=Ia.get(this))==null||l.forEach(u=>u==null?void 0:u.queue.forEach(h=>n.push(h))),n.forEach(u=>{u.reject(new b({code:I.API_CALL_ABORTED,message:s}))}),wo.delete(this),Ia.delete(this),r.apply(this,o)},t}}function Mi(s){return function(i,e,t){let r=t.value,o=n=>s(...n);return t.value=function(...n){let a=Ia.get(this)||new Map,d=a.get(o(n))||new Sa;return a.set(o(n),d),Ia.set(this,a),d.push({fn:r,args:n,context:this})},t}}function at(s,i){return z((e,t)=>function(...r){let o=s;try{let n=e.apply(this,r),a=P();return ji(n)?n.then(d=>(i?N.addSuccessEvent({key:o,cost:P()-a}):N.addSuccessEvent({key:o}),d)).catch(d=>{throw N.addFailedEvent({key:o,error:d}),d}):(N.addSuccessEvent({key:o}),n)}catch(n){throw N.addFailedEvent({key:o,error:n}),n}})}var Nr=class Nr extends br{constructor(e,t){super({mediaType:e,PlayerClass:t});c(this,"isRemote",!1);c(this,"deviceId");c(this,"groupId","");c(this,"label","");c(this,"sourceTrack");c(this,"_isRecapturing",!1);c(this,"_lastRecaptureTime",0);c(this,"_onMuteTimeoutId",-1);c(this,"_encodeCheckTimeoutId",-1);c(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){$e(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){Re(e)}setStateToCapture(){}capture(e){return p(this,null,function*(){var t;try{let r=P();S.emit(E.LOCAL_TRACK_CAPTURE_START,{track:this});let o;e.customSource?(o=new MediaStream,o.addTrack(e.customSource)):((t=this.mediaTrack)==null||t.stop(),o=yield im(e));let n=o.getTracks()[0];return this.sourceTrack=n,yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),S.emit(E.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:P()-r}),o}catch(r){throw S.emit(E.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:r}),this.log.error(`getUserMedia error observed ${r}`),r}})}setInputMediaStreamTrack(e){return this.state===F.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),S.emit(E.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return p(this,null,function*(){if(this.mediaTrack&&Kt){let{deviceId:e,groupId:t}=this.mediaTrack.getSettings(),{label:r}=this.mediaTrack;(yield em({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=r,t&&(this.groupId=t),ma().then(n=>{let a=n.find(d=>d.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&&!Zh(this.mediaTrack)||this.kind===m.VIDEO&&!Kh(this.mediaTrack)||this._isRecapturing||e&&kt&&Me)}onTrackMuted(){if(super.onTrackMuted(),rm(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<jr){setTimeout(()=>this.onTrackMuted(),jr);return}this._onMuteTimeoutId=setTimeout(()=>p(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((Te||he)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return p(this,null,function*(){if(Fe(Nr.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 p(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 nt():yield _t()).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}),S.emit(E.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(o=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${o.message}`),this.emit("5",o),S.emit(E.LOCAL_TRACK_RECAPTURE,{track:this,error:o})})})}getRecoverCaptureDeviceId(){return p(this,null,function*(){let e=this instanceof We;if(e&&this.facingMode)return this.facingMode;let{deviceId:t}=this;if(t){let r=(xo.get(t)||0)+1;if(xo.set(t,r),r>=3){let o=e?(yield _t()).find(n=>!xo.has(n.deviceId)):(yield nt()).find(n=>!xo.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([pe(F.INIT,"capture",{ignoreError:!0,sync:!0})],Nr.prototype,"setStateToCapture",1),y([si()],Nr.prototype,"capture",1),y([pe("capture","publish",{ignoreError:!0,success(){var t,r;this.room.localTracks.add(this),S.emit(E.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 d=this.kind===m.AUDIO,l=this.stat.bytesSent>0;N[l?"addSuccessEvent":"addFailedEvent"]({key:d?503700:513702}),l||(N.addEnum({key:d?503701:513703,value:fo()}),te.uploadEvent({log:`stat-encode-failed-${this.kind}-${_r()||Ri()}`,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===I.API_CALL_ABORTED&&(t="api-call")}this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:t,error:e.cause||e})}}),at(521714,!1)],Nr.prototype,"publish",1),y([z(e=>function(){return p(this,null,function*(){let t=this.state==="publish"?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),pe([],"capture",{sync:!0})],Nr.prototype,"unpublish",1);var ki=Nr,xo=new Map;S.on(E.SWITCH_DEVICE_SUCCESS,s=>{s.track.deviceId&&xo.delete(s.track.deviceId)});var St=class s extends ki{constructor(e){super(1,_a);c(this,"mediaType",1);c(this,"volume",0);c(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});c(this,"playerMuted",!0);c(this,"pipeline");c(this,"earMonitorGainNode",new Ge);c(this,"_output",new Ge);c(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});this.manager=e,this.pipeline=new gs(e),this.pipeline.gain.pipeTo(this.earMonitorGainNode.pipeTo(this._output),this.player.pipeline.volumeMeter),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}get dbVolume(){return yr.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}setInputMediaStreamTrack(e){return p(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 Fe(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 p(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e)if(e===lr){if(yield Xd(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}),S.emit(E.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(t){throw this.log.error(`switch microphone failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}}})}listenDeviceChange(){ke&&!ke.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&ke.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return p(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current microphone is lost: ${JSON.stringify(e)}`),ge(this.userId,{eventId:2003,param1:6,streamType:1});let t=yield nt();t[0]?this.recapture(t[0].deviceId):ke.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(o){return p(this,arguments,function*({echoCancellation:e,noiseSuppression:t,autoGainControl:r}){let n=this.sourceTrack||this.mediaTrack;if(!n)return;let a=n.getConstraints(),d=!1;!T(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,a.echoCancellation=e,d=!0),!T(t)&&t!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=t,a.noiseSuppression=t,d=!0),!T(r)&&r!==this.profile.autoGainControl&&(this.profile.autoGainControl=r,a.autoGainControl=r,d=!0),d&&(se||Me?yield n.applyConstraints(a).catch(l=>this._log.warn("update3A failed: ",l)):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})}setAudioVolume(e){super.setAudioVolume(0),Te&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(ve().createGain()),this._output.setNode(ve().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}addDenoiser(e){var t;if(lt<=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.enableTrackANS(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0))}close(){this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),ke.off("audioInputAdded",this.handleMicrophoneAdded,this),ke.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return p(this,null,function*(){try{yield Fe(s.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield nt()).find(o=>o.deviceId!==e);if(r)yield Fe(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 Li=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 Ca=class{constructor(){c(this,"_seiMessageList",[]);c(this,"_smallSeiMessageList",[]);c(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 Li(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((f,g)=>f+g.dataView.byteLength,0),d=new ArrayBuffer(a+i.data.byteLength),l=new DataView(d),u=new DataView(i.data),h=0;for(let f=0;f<n.length;f++)for(let g=0;g<n[f].dataView.byteLength;g++)l.setInt8(h++,n[f].dataView.getInt8(g));for(let f=0;f<i.data.byteLength;f++)l.setInt8(h++,u.getInt8(f));return i.data=d,n.length}return 0}};var vr=class vr extends ki{constructor(e,t=4){super(t,pt);c(this,"profile",{width:640,height:480,frameRate:15,bitrate:500});c(this,"avoidCropping",!1);c(this,"_scaleResolutionDownBy");c(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0});c(this,"small");c(this,"isNeedToSetBandwidth");c(this,"muteImage");c(this,"manager");c(this,"_seiCodec",new Ca);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(L(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(!(!Kt||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get contentHint(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)||""}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}setMute(e){return p(this,null,function*(){var t,r,o;if(Z(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,Fe(vr.prototype,this,"setMute").call(this,!1)}else yield(o=this.manager)==null?void 0:o.deleteWatermark("mute"),this.muteImage=void 0,Fe(vr.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&&he&&Qe&&(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&&td&&(t.width=r?1280:720,t.height=r?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),this.avoidCropping&&(Qe||se)&&!rd()&&t.width*t.height<=640*360&&t.width/t.height===16/9&&(this._scaleResolutionDownBy=1280/t.width,t.width=1280,t.height=720,this.log.warn(`capture 720p, scale: ${this._scaleResolutionDownBy}`)),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(L(v({},this.profile),{width:1920,height:1080})))}applyProfile(){return p(this,null,function*(){var a;if(!this.mediaTrack)return;let{width:e=0,height:t=0}=(this.sourceTrack||this.mediaTrack).getSettings(),r=e*t,o=this.settings;if(!(!(o.height!==this.profile.height||o.width!==this.profile.width||o.frameRate!==this.profile.frameRate)||!this.deviceId)&&(ut===16?yield this.recapture(this.deviceId):(yield(a=this.sourceTrack||this.mediaTrack)==null?void 0:a.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth)){this.isNeedToSetBandwidth=!1;let{width:d=0,height:l=0}=(this.sourceTrack||this.mediaTrack).getSettings(),u=d*l;if(u&&r&&u===r){this.log.warn("set bandwidth failed: resolution is not changed");return}return 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 Kt&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e}get scaleResolutionDownBy(){if(this._scaleResolutionDownBy)return this._scaleResolutionDownBy;let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:An()&&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 p(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),S.emit(E.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(t){throw this.log.error(`switch camera failed ${t}`),this.deviceId&&this.recapture(this.deviceId),t}})}listenDeviceChange(){ke&&!ke.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&ke.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return p(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current camera is lost: ${JSON.stringify(e)}`),ge(this.userId,{eventId:2003,param1:7,streamType:2});let t=yield _t();t[0]?this.recapture(t[0].deviceId):ke.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return p(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 T(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,t)}close(){ke.off("videoInputAdded",this.handleCameraAdded,this),ke.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return p(this,null,function*(){try{yield Fe(vr.prototype,this,"recapture").call(this,e)}catch(t){let r=(yield _t()).find(o=>o.deviceId!==e);if(r)yield Fe(vr.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([Ke(function(e){this.setContentHint(e.contentHint||"motion")})],vr.prototype,"capture",1);var We=vr;var nm=_o();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:nm,exposeOrigin:!0,permittedOrigins:["*"]})}catch(s){}var B_=function(s){return p(this,null,function*(){let i=null,e=$_(s);C.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let t=yield navigator.mediaDevices.getDisplayMedia(e);s.systemAudio&&t.getAudioTracks().length===0&&(cs&<<74||Me||se)&&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 F_(r,s.captureElement))}if(s.audio){let o=H_(s);C.info(`getUserMedia with constraints: ${JSON.stringify(o)}`),i=yield navigator.mediaDevices.getUserMedia(o),t.addTrack(i.getAudioTracks()[0])}return t})};function F_(s,i){return p(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&ce(s.cropTo))try{if(!(((e=s.getCaptureHandle())==null?void 0:e.handle)===nm))return;let r=yield CropTarget.fromElement(i);yield s.cropTo(r)}catch(t){C.warn(`cropTo target failed ${t}`)}})}function H_(s){let i={echoCancellation:s.echoCancellation,autoGainControl:s.autoGainControl,noiseSuppression:s.noiseSuppression,sampleRate:s.sampleRate,channelCount:s.channelCount};return T(s.microphoneId)||(i.deviceId=s.microphoneId),{audio:i,video:!1}}function $_(s){let i={preferCurrentTab:s.preferDisplaySurface==="current-tab"||!!s.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:Me?{max:s.width}:{ideal:s.width,max:s.width},height:Me?{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 am=B_;var ct=class extends We{constructor(e){super(e,2);c(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});c(this,"objectFit","contain");c(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(u){return p(this,arguments,function*({systemAudio:e=!1,autoGainControl:t,echoCancellation:r,noiseSuppression:o,audioTrack:n,videoTrack:a,captureElement:d,preferDisplaySurface:l}){try{let h;return a||n?(h=new MediaStream,a&&h.addTrack(a),n&&h.addTrack(n)):h=yield am({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:t,echoCancellation:r,noiseSuppression:o,captureElement:d,preferDisplaySurface:l}),yield this.setInputMediaStreamTrack(h.getVideoTracks()[0]),h}catch(h){throw this.log.error(`getDisplayMedia error observed ${h}`),h instanceof b?h:new b({code:I.INITIALIZE_FAILED,name:h.name,message:h.message})}})}switchDevice(e){return p(this,null,function*(){throw new Error("Method not implemented.")})}};y([Ke(function(e){this.setContentHint(e.contentHint||"detail")})],ct.prototype,"capture",1);var ni=class extends St{constructor(i){super(i),this._log.id=`s-${this._log.id}`}};var G_="registerProcessor('dumper', class extends AudioWorkletProcessor {process(inputs) {this.port.postMessage(inputs);return true;}});",Qd;function Uo(s){return p(this,null,function*(){let i=ve("dump");Qd||(Qd=Rr(i,URL.createObjectURL(new Blob([G_],{type:"application/javascript"})))),yield Qd;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 Ra=class extends la{constructor(e){super();this.room=e;c(this,"_localAudioTrack");c(this,"_localScreenAudioTrack");c(this,"log",C.createLogger({id:"am"}));c(this,"denoiser");c(this,"voiceChanger");c(this,"mixChangedDebounce");c(this,"encodePipeline",[]);c(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 u,h;if(!this._localAudioTrack)return;let t=[],r=[];(u=this._localAudioPipline)!=null&&u.source.node&&(t.push(this._localAudioPipline.source.node),r.push("mic")),(h=this._localAudioPipline)!=null&&h.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),d=()=>{for(let f=0;f<r.length;f++){let g=URL.createObjectURL(new Blob(n[f])),D=document.createElement("a");D.href=g,D.download=`${r[f]}.pcm`,D.style.display="none",document.body.appendChild(D),D.click(),URL.revokeObjectURL(g),D.remove()}clearTimeout(a),o.abort("download")},l=Uo(t).then(f=>f.pipeTo(new WritableStream({write(g){g.forEach((D,_)=>n[_]=n[_]?n[_].concat(D[0]):[D[0]])}}),o).catch(g=>d));return{then:l.then.bind(l),download:d}}getPCM(e){var n;if(T(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(d){d[0][0]&&(t.set(d[0][0],r),r+=d[0][0].length,r>=1920&&(r=0,e(t),t=new Float32Array(1920)))}}),o).catch(d=>this.log.warn(`stop getPCM reason:${d}`))),o}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return!T(this._localAudioTrack)}changeInput(e){if(e instanceof ni)return this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();if(e instanceof St)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();if(e instanceof Pi)return e.setOutputMediaStreamTrack(e.mediaTrack)}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 ni?delete this._localScreenAudioTrack:e instanceof St?delete this._localAudioTrack:e instanceof Pi}addDenoiser(e){var t;this.denoiser=e,(t=this._localAudioTrack)==null||t.addDenoiser(e)}removeDenoiser(e){var t;delete this.denoiser,(t=this._localAudioTrack)==null||t.removeDenoiser(e)}addVoiceChanger(e,t){var r;this.voiceChanger=[e,t],(r=this._localAudioTrack)==null||r.pipeline.voiceChanger.setNode(e,t)}removeVoiceChanger(){var e;delete this.voiceChanger,(e=this._localAudioTrack)==null||e.pipeline.voiceChanger.deleteNode()}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 ya(s=30,i=2){return z((e,t)=>function(...r){return new Promise((o,n)=>{let a=setTimeout(()=>{let d=new b({code:I.API_CALL_TIMEOUT,message:`checkPendingPromise ${t}() timeout ${s}s`});C.warn(d),i===2?n(d):i===1&&o()},s*1e3);e.apply(this,r).then(o,n).finally(()=>{clearTimeout(a)})})})}var wl={};mi(wl,{Events:()=>Ee,Inspect:()=>It,LastSink:()=>Dr,Sink:()=>$,Subscribe:()=>Or,TimeoutError:()=>Vo,audit:()=>Rg,bindCallback:()=>dg,bindNodeCallback:()=>lg,buffer:()=>K_,bufferCount:()=>Y_,bufferTime:()=>Gg,call:()=>cm,catchError:()=>kl,combineLatest:()=>lm,concat:()=>j_,concatMap:()=>wg,concatMapTo:()=>xg,count:()=>mg,create:()=>ee,debounce:()=>yg,debounceTime:()=>bg,defer:()=>um,delay:()=>Wg,deliver:()=>J,dispose:()=>ba,elementAt:()=>Ng,empty:()=>Ho,every:()=>Mg,exhaustMap:()=>Bg,exhaustMapTo:()=>Fg,filter:()=>ai,find:()=>vg,findIndex:()=>Dg,first:()=>Og,fromAnimationFrame:()=>ag,fromArray:()=>tg,fromEvent:()=>ue,fromEventPattern:()=>ig,fromFetch:()=>rg,fromIterable:()=>sg,fromPromise:()=>pm,fromReadableStream:()=>ng,fromReader:()=>og,groupBy:()=>Hg,identity:()=>W_,ignoreElements:()=>gg,iif:()=>X_,inspect:()=>dm,interval:()=>rl,last:()=>kg,map:()=>$o,mapTo:()=>Pg,max:()=>pg,merge:()=>tl,mergeMap:()=>Ug,mergeMapTo:()=>Vg,min:()=>fg,never:()=>ug,nothing:()=>ae,of:()=>eg,pairwise:()=>Lg,pipe:()=>de,race:()=>il,range:()=>cg,reduce:()=>sl,retry:()=>Xg,scan:()=>Ol,share:()=>wi,shareReplay:()=>q_,skip:()=>Eg,skipUntil:()=>Sg,skipWhile:()=>ka,startWith:()=>Bo,subject:()=>Ze,subscribe:()=>Ae,sum:()=>_g,switchMap:()=>Is,switchMapTo:()=>Mr,take:()=>xi,takeLast:()=>Tg,takeUntil:()=>we,takeWhile:()=>fm,tap:()=>Pl,throttle:()=>Ag,throwError:()=>hg,timeInterval:()=>$g,timeout:()=>qg,timer:()=>Fo,toPromise:()=>Jg,toReadableStream:()=>jg,withLatestFrom:()=>Q_,zip:()=>z_});function ae(...s){}var cm=s=>s(),W_=s=>s;function ba(){this.dispose()}var dm=()=>typeof __FASTRX_DEVTOOLS__!="undefined",J_=1,It=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(i){let e=new Yd(i,this,this.streamId++);return Ee.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},Dr=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=ae,this.error=ae,this.next=ae,this.dispose=ae,this.subscribe=ae,this.doDefer()}subscribe(i){return i instanceof It?i.subscribe(this):i(this),this}get bindSubscribe(){return i=>this.subscribe(i)}doDefer(){this.defers.forEach(cm),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}},$=class extends Dr{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)}},Or=class extends Dr{constructor(i,e=ae,t=ae,r=ae){if(super(),this._next=e,this._error=t,this._complete=r,this.then=ae,i instanceof It){let o={toString:()=>"subscribe",id:0,source:i};this.defer(()=>{Ee.defer(o,0)}),Ee.create(o),Ee.pipe(o),this.sourceId=o.id,this.subscribe(i),Ee.subscribe({id:o.id,end:!0}),e==ae?this._next=n=>Ee.next(o,0,n):this.next=n=>{Ee.next(o,0,n),e(n)},r==ae?this._complete=()=>Ee.complete(o,0):this.complete=()=>{this.dispose(),Ee.complete(o,0),r()},t==ae?this._error=n=>Ee.complete(o,0,n):this.error=n=>{this.dispose(),Ee.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 de(s,...i){return i.reduce((e,t)=>t(e),s)}function ee(s,i,e){if(dm()){let t=Object.defineProperties(Object.setPrototypeOf(s,It.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}});Ee.create(t);for(let r=0;r<e.length;r++){let o=e[r];typeof o=="function"&&o instanceof It&&Ee.addSource(t,o)}return t}return s}function J(s,i){return function(...e){return t=>{if(t instanceof It){let r=ee(o=>{let n=new s(o,...e);n.sourceId=r.id,n.subscribe(t)},i,arguments);return r.source=t,Ee.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 Yd=class extends ${constructor(i,e,t){super(i),this.source=e,this.id=t,this.sourceId=i.sourceId,this.defer(()=>{Ee.defer(this.source,this.id)})}next(i){Ee.next(this.source,this.id,i),this.sink.next(i)}complete(){Ee.complete(this.source,this.id),this.sink.complete()}error(i){Ee.complete(this.source,this.id,i),this.sink.error(i)}},Ee={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=J_++),er("create",{name:s.toString(),id:s.id})}},Vo=class extends Error{constructor(i){super(`timeout after ${i}ms`),this.timeout=i}};var Na=class extends Dr{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 wi(){return s=>{let i=new Na(s);if(s instanceof It){let e=ee(t=>{i.add(t)},"share",arguments);return i.sourceId=e.id,e.source=s,Ee.pipe(e),e}return ee(i.add.bind(i),"share",arguments)}}function tl(...s){return ee(i=>{let e=new $(i),t=s.length;e.complete=()=>{--t===0&&i.complete()},s.forEach(e.bindSubscribe)},"merge",arguments)}function il(...s){return ee(i=>{let e=new Map;s.forEach(t=>{let r=new $(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 j_(...s){return ee(i=>{let e=0,t=s.length,r=new $(i);r.complete=()=>{e<t&&!r.disposed?(r.doDefer(),r.subscribe(s[e++])):i.complete()},r.complete()},"concat",arguments)}function q_(s){return i=>{let e=new Na(i),t=[];return e.next=function(r){t.push(r),t.length>s&&t.shift(),this.sinks.forEach(o=>o.next(r))},ee(r=>{r.defer(()=>e.remove(r)),t.forEach(o=>r.next(o)),e.add(r)},"shareReplay",arguments)}}function X_(s,i,e){return ee(t=>s()?i(t):e(t),"iif",arguments)}function lm(...s){return ee(i=>{let e=s.length,t=e,r=e,o=new Array(e),n=()=>{--r===0&&i.complete()},a=(d,l)=>{let u=new $(i);u.next=h=>{--t===0?(u.next=f=>{o[l]=f,i.next(o)},u.next(h)):o[l]=h},u.complete=n,u.subscribe(d)};s.forEach(a)},"combineLatest",arguments)}function z_(...s){return ee(i=>{let e=s.length,t=e,r=new Array(e),o=()=>{--t===0&&i.complete()},n=(a,d)=>{let l=new $(i),u=[];r[d]=u,l.next=h=>{u.push(h),r.every(f=>f.length)&&i.next(r.map(f=>f.shift()))},l.complete=o,l.subscribe(a)};s.forEach(n)},"zip",arguments)}function Bo(...s){return i=>ee((e,t=0,r=s.length)=>{for(;t<r&&!e.disposed;)e.next(s[t++]);e.disposed||e.subscribe(i)},"startWith",arguments)}var Kd=class extends ${constructor(i,...e){super(i);let t=new $(this.sink);t.next=r=>this.buffer=r,t.complete=ae,t.subscribe(lm(...e))}next(i){this.buffer&&this.sink.next([i,...this.buffer])}},Q_=J(Kd,"withLatestFrom"),Zd=class extends ${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()}},Y_=J(Zd,"bufferCount"),el=class extends ${constructor(i,e){super(i),this.buffer=[];let t=new $(i);t.next=r=>{i.next(this.buffer),this.buffer=[]},t.complete=ae,t.subscribe(e)}next(i){this.buffer.push(i)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},K_=J(el,"buffer");var Z_=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(u){try{l(t.next(u))}catch(h){n(h)}}function d(u){try{l(t.throw(u))}catch(h){n(h)}}function l(u){u.done?o(u.value):r(u.value).then(a,d)}l((t=t.apply(s,i||[])).next())})};function Ze(s){let i=arguments,e=wi()(ee(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=ae,e.complete=ae,e.error=ae,e}function um(s){return ee(i=>i.subscribe(s()),"defer",arguments)}var hm=s=>i=>{setTimeout(()=>s(i))},mm=s=>hm(i=>{for(let e=0;!i.disposed&&e<s.length;e++)i.next(s[e]);i.complete()});function eg(...s){return ee(mm(s),"of",arguments)}function tg(s){return ee(mm(s),"fromArray",arguments)}function rl(s){return ee(i=>{let e=0,t=setInterval(()=>i.next(e++),s);return i.defer(()=>{clearInterval(t)}),"interval"},"interval",arguments)}function Fo(s,i){return ee(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 va(s,i){return e=>{let t=r=>e.next(r);e.defer(()=>i(t)),s(t)}}function ig(s,i){return ee(va(s,i),"fromEventPattern",arguments)}function ue(s,i){if("on"in s&&"off"in s)return ee(va(e=>s.on(i,e),e=>s.off(i,e)),"fromEvent",arguments);if("addListener"in s&&"removeListener"in s)return ee(va(e=>s.addListener(i,e),e=>s.removeListener(i,e)),"fromEvent",arguments);if("addEventListener"in s)return ee(va(e=>s.addEventListener(i,e),e=>s.removeEventListener(i,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function pm(s){return ee(i=>{s.then(i.next.bind(i),i.error.bind(i))},"fromPromise",arguments)}function rg(s,i){return ee(um(()=>pm(fetch(s,i))),"fromFetch",arguments)}function sg(s){return ee(hm(i=>{try{for(let e of s){if(i.disposed)return;i.next(e)}i.complete()}catch(e){i.error(e)}}),"fromIterable",arguments)}function og(s){let i=e=>Z_(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 ee(e=>{i(e)},"fromReader",arguments)}function ng(s){return ee(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 ag(){return ee(s=>{let i=requestAnimationFrame(function e(t){s.disposed||(s.next(t),i=requestAnimationFrame(e))});s.defer(()=>cancelAnimationFrame(i))},"fromAnimationFrame",arguments)}function cg(s,i){return ee((e,t=s,r=i+s)=>{for(;t<r&&!e.disposed;)e.next(t++);return e.complete(),"range"},"range",arguments)}function dg(s,i,...e){return ee(t=>{let r=e.concat(o=>(t.next(o),t.complete()));s.apply(i,r)},"bindCallback",arguments)}function lg(s,i,...e){return ee(t=>{let r=e.concat((o,n)=>o?t.error(o):(t.next(n),t.complete()));s.apply(i,r)},"bindNodeCallback",arguments)}function ug(){return ee(()=>{},"never",arguments)}function hg(s){return ee(i=>i.error(s),"throwError",arguments)}function Ho(){return ee(s=>s.complete(),"empty",arguments)}var kr=class extends ${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)}},sl=J(kr,"reduce"),mg=s=>J(kr,"count")((i,e)=>s(e)?i+1:i,0),pg=()=>J(kr,"max")(Math.max),fg=()=>J(kr,"min")(Math.min),_g=()=>J(kr,"sum")((s,i)=>s+i,0);var ol=class extends ${constructor(i,e,t){super(i),this.filter=e,this.thisArg=t}next(i){this.filter.call(this.thisArg,i)&&this.sink.next(i)}},ai=J(ol,"filter"),nl=class extends ${next(i){}},gg=J(nl,"ignoreElements"),al=class extends ${constructor(i,e){super(i),this.count=e}next(i){this.sink.next(i),--this.count===0&&this.complete()}},xi=J(al,"take"),cl=class extends ${constructor(i,e){super(i);let t=new $(i);t.next=()=>i.complete(),t.complete=ba,t.subscribe(e)}},we=J(cl,"takeUntil"),dl=class extends ${constructor(i,e){super(i),this.f=e}next(i){this.f(i)?this.sink.next(i):this.complete()}},fm=J(dl,"takeWhile"),Tg=s=>sl((i,e)=>(i.push(e),i.length>s&&i.shift(),i),[]),ll=class extends ${constructor(i,e){super(i),this.count=e}next(i){--this.count===0&&(this.next=super.next)}},Eg=J(ll,"skip"),ul=class extends ${constructor(i,e){super(i),i.next=ae;let t=new $(i);t.next=()=>{t.dispose(),i.resetNext()},t.complete=ba,t.subscribe(e)}},Sg=J(ul,"skipUntil"),hl=class extends ${constructor(i,e){super(i),this.f=e}next(i){this.f(i)||(this.next=super.next,this.next(i))}},ka=J(hl,"skipWhile"),Ig={leading:!0,trailing:!1},ml=class extends ${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)}},Da=class extends ${constructor(i,e,t=Ig){super(i),this.durationSelector=e,this.config=t,this._throttle=new ml(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=ae,this._throttle.complete(),super.complete()}},Ag=J(Da,"throttle"),Cg={leading:!1,trailing:!0},Rg=s=>J(Da,"audit")(s,Cg),pl=class extends ${next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Oa=class extends ${constructor(i,e){super(i),this.durationSelector=e,this._debounce=new pl(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()}},yg=J(Oa,"debounce"),bg=s=>J(Oa,"debounceTime")(i=>Fo(s)),fl=class extends ${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()}},Ng=J(fl,"elementAt"),vg=s=>i=>xi(1)(ka(e=>!s(e))(i)),_l=class extends ${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}},Dg=J(_l,"findIndex"),gl=class extends ${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()}},Og=J(gl,"first"),Tl=class extends ${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()}},kg=J(Tl,"last"),El=class extends ${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()}},Mg=J(El,"every");var Sl=class extends ${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))}},Ol=J(Sl,"scan"),Il=class extends ${constructor(){super(...arguments),this.hasLast=!1}next(i){this.hasLast?this.sink.next([this.last,i]):this.hasLast=!0,this.last=i}},Lg=J(Il,"pairwise"),Ma=class extends ${constructor(i,e,t){super(i),this.mapper=e,this.thisArg=t}next(i){super.next(this.mapper.call(this.thisArg,i))}},$o=J(Ma,"map"),Pg=s=>J(Ma,"mapTo")(i=>s),Es=class extends ${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 ${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()}},La=class extends Es{},Pa=class extends Ss{next(i){this.subInner(i,La),this.next=e=>{this.currentSink.dispose(),this.subInner(e,La)}}},Is=J(Pa,"switchMap");function Va(s){return(i,e)=>s(()=>i,e)}var Mr=Va(J(Pa,"switchMapTo")),Al=class extends Es{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},wa=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(),Al),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},wg=J(wa,"concatMap"),xg=Va(J(wa,"concatMapTo")),Cl=class extends Es{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},xa=class extends Ss{constructor(){super(...arguments),this.inners=new Set}next(i){this.subInner(i,Cl),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(i=>i.resetComplete()):this.dispose()}},Ug=J(xa,"mergeMap"),Vg=Va(J(xa,"mergeMapTo")),Rl=class extends Es{dispose(){this.context.resetNext(),super.dispose()}},Ua=class extends Ss{next(i){this.next=ae,this.subInner(i,Rl)}},Bg=J(Ua,"exhaustMap"),Fg=Va(J(Ua,"exhaustMapTo")),yl=class extends ${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=Ze(),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)}},Hg=J(yl,"groupBy"),bl=class extends ${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}},$g=J(bl,"timeInterval"),Nl=class extends ${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()}},Gg=J(Nl,"bufferTime"),vl=class extends ${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)}},Wg=J(vl,"delay"),Dl=class extends ${constructor(i,e){super(i),this.selector=e}error(i){this.dispose(),this.selector(i)(this.sink)}},kl=J(Dl,"catchError");var Jg=()=>s=>new Promise((i,e)=>{let t;new Or(s,r=>t=r,e,()=>i(t))}),jg=()=>s=>{let i;return new ReadableStream({start(e){i=new Or(s,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){i.dispose()}})},Ae=(s=ae,i=ae,e=ae)=>t=>new Or(t,s,i,e),Ml=class extends ${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)}))}},Pl=J(Ml,"tap"),Ll=class extends ${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()}},qg=J(Ll,"timeout"),Xg=(s=1/0)=>i=>{if(i instanceof It){let e=ee(t=>{let r=s,o=new $(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,Ee.pipe(e),e}else return e=>{let t=s,r=new $(e);r.error=o=>{t-- >0?i(r):e.error(o)},i(r)}};var ci=class ci extends br{constructor(e,t,r){super({userId:t.userId,sdkAppId:e.sdkAppId,mediaType:r,room:e});this.room=e;this.user=t;c(this,"tinyId");c(this,"isRemote",!0);c(this,"jitterBufferDelay",0);c(this,"availableState");c(this,"remotePublishState");c(this,"_triggerCheckDecodeSubject",Ze(ue(this,ci.STATE_SUBSCRIBE)));this.tinyId=t.tinyId,this.availableState=new F(`${t.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new F(`${t.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),de(tl(ue(this,F.STATECHANGED),ue(this.remotePublishState,F.STATECHANGED)),$o(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),Ae(d=>{this.availableState.state!==(d?F.ON:F.OFF)&&(this.availableState.state=d?F.ON:F.OFF),this.updatePlayingState(d)}));let o=de(ue(this.player,le.ERROR),ai(d=>d.code===MediaError.MEDIA_ERR_DECODE)),n=de(Fo(5e3),ai(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived?!1:this.player.isPlaying||(this.kind===m.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)?(this.reportDecodeResult(!0),!1):!0)),a=de(il(o,n),we(ue(this,F.INIT)));de(this._triggerCheckDecodeSubject,ai(()=>!this.ignoreDecodeError),Mr(a),Ae(d=>{this.reportDecodeResult(!1,d)}))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get ignoreDecodeError(){var t,r;return(((r=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:r.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===ci.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===F.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}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:fo()}),te.uploadEvent({log:`stat-decode-failed-${this.kind}-${_r()||Ri()}`,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.isRemotePublished||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isRemotePublished} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?F.ON:F.OFF}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};c(ci,"STATE_SUBSCRIBE","subscribe"),y([ya(5,1)],ci.prototype,"waitHasMediaTrack",1),y([pe(F.INIT,ci.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),S.emit(E.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),at(521716,!1)],ci.prototype,"subscribe",1),y([pe(ci.STATE_SUBSCRIBE,F.INIT,{sync:!0,success(){this.log.info("unsubscribed"),S.emit(E.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],ci.prototype,"unsubscribe",1);var As=ci;var Pi=class extends As{constructor(e,t){super(e,t,1);c(this,"volume",0);c(this,"mediaType",1);c(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}get dbVolume(){return yr.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 isRemotePublished(){return this.user.muteState.audioAvailable}};var Qg=[-1,-1,1,-1,-1,1,1,1],Yg=[0,0,1,0,0,1,1,1];var et=class extends F{constructor(e,t){super();this.context=e;c(this,"name");c(this,"input");c(this,"output");c(this,"texture");c(this,"ctx2d",null);c(this,"fbo");c(this,"width",0);c(this,"height",0);c(this,"x",0);c(this,"y",0);c(this,"program");c(this,"vertexShader");c(this,"fragmentShader");c(this,"totalFrames",0);c(this,"dropFrames",0);c(this,"matchInputSize",!0);c(this,"texCoordBuffer");c(this,"positionBuffer");c(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});c(this,"cost",0);c(this,"_canvas",null);c(this,"_image");c(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 Je){e.ctx&&t.create2d&&(typeof OffscreenCanvas=="function"&&ut!==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(Yg),this.positionBuffer=this.createBuffer(Qg),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:I.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${r.message||r}`}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let t=this.context.ctx,r=t.createFramebuffer();return t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0),r}connect(e,...t){return e.addInput(this,...t),this.output=e,e}addInput(e,...t){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let t=Date.now();if(this.context instanceof De&&this.render(e)||this.context instanceof Je&&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 De){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 h;let{totalFrames:e,x:t,y:r,width:o,height:n,name:a,cost:d}=this,l=Date.now(),u=(e-this.lastInfo.totalFrames)/((l-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:o,height:n,timestamp:l,fps:u,name:a,cost:d},v({parent:(h=this.input)==null?void 0:h.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([pe(F.INIT,"connected",{sync:!0})],et.prototype,"connect",1),y([pe("connected",F.INIT,{ignoreError:!0,sync:!0})],et.prototype,"disconnect",1),y([pe([],"closed",{sync:!0})],et.prototype,"close",1);var Kg=de(rl(250),$o(()=>performance.now()),wi());var gm=s=>i=>{let e=performance.now();de(Kg,ka(t=>t-e<s),xi(1))(i)};var eT=[0,1,1,1,0,0,1,0],Lr=class extends et{constructor(e,t){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t));c(this,"_intervalId",0);c(this,"_sequence",0);c(this,"checkGLError",!1);c(this,"checkVisibilityChange");e instanceof Je?this.ctx2d=e.ctx||null:e.available&&(t!=null&&t.mirrorUpAndDown)&&this.setTexBuffer(eT)}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 De){let r=this.context.ctx.getError();r&&this.context.destroy(new b({code:I.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${r}`}))}},{fps:this.context.frameRate})}render(e){var t;return(t=this.input)!=null&&t.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!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)}},Cs=class extends Lr{constructor(e,t){super(e,t);c(this,"_videoTrack");c(this,"_muteOb");c(this,"_closedOb",ue(this,"closed"));c(this,"_subscription");c(this,"_canvasContainer");Number(Ai)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=ue(this._videoTrack,"mute"),de(ue(this._videoTrack,"ended"),we(this._closedOb),Ae(()=>{this.context.destroy(new b({code:I.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=de(this._muteOb,we(this._closedOb),Mr(gm(5e3)),ai(()=>{var e;return!!((e=this._videoTrack)!=null&&e.muted)&&!document.hidden}),Ae(()=>{this.context.destroy(new b({code:I.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var e;(e=this._subscription)==null||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info(`${this.name} put canvas to body`),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,t;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack,(t=this._canvasContainer)==null||t.remove()}},Ba=class extends Cs{render(i){var e;return!!((e=this.input)!=null&&e.requestFrame(i))}};var Fa=class extends Cs{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 Go=class extends et{constructor(e,t){super(e,v({name:"imageSource"},t));c(this,"_lastImage");c(this,"_totalFrames",0);c(this,"_autoResize",!1);c(this,"_canvasRendered");c(this,"_videoCallbackId",0);c(this,"waitingFirstFrame",!0);this._autoResize=(t==null?void 0:t.autoResize)!==!1,ut===16&&(this._canvasRendered=Ze(),de(this._canvasRendered,Bo(this._image),Is(r=>r instanceof HTMLCanvasElement?ue(r,"rendered"):Ho()),we(ue(this,"closed")),Ae(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){let e=this.image;this._videoCallbackId&&e.cancelVideoFrameCallback(this._videoCallbackId),Cr()&&!document.hidden&&(this._videoCallbackId=e.requestVideoFrameCallback((t,r)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=r.presentedFrames,this.update(1))}))}_render(e,t){var a;let{width:r,height:o}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{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 d=this.context.ctx;d.texSubImage2D(d.TEXTURE_2D,0,0,0,d.RGBA,d.UNSIGNED_BYTE,n)}}else{if(t){this.useTexture();let d=this.context.ctx;d.texImage2D(d.TEXTURE_2D,0,d.RGBA,d.RGBA,d.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)}},Wo=class extends Go{constructor(e,t,r){super(e,r);this._player=t;this.name="videoPlayerSource",de(ue(this._player,le.PLAYER_STATE_CHANGED),we(ue(this,"closed")),ai(({state:o})=>o==="PLAYING"),Ae(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},Ui=class extends Wo{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(i,e,t){super(i,new pt({id:t.name,track:e,muted:!0,container:null,objectFit:"contain",log:t.logger}),t),this.name="videoTrackSource",this._player.play()}replaceTrack(i){this.waitingFirstFrame=!0,this._player.setTrack(i),this._player.play()}close(){super.close(),this._player.stop()}};var iT=`
|
|
31
|
+
`,r.onclick=this.onQuestionClick.bind(this);let o=document.createElement("div");o.className=jl,o.innerText=`${_r()?"\u8BE6\u60C5 >":"Detail >"}`,o.onclick=this.onCollapseClick.bind(this);let s=t.content.firstChild,n=s.querySelector(`.${ed}`);return n.appendChild(o),n.appendChild(r),n.appendChild(e),s}addDiaLog(){Jl()||(this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${$s}`).onclick=t=>t.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",F.info("show autoplay dialog"),je.uploadEvent({log:V_}))}deleteDiaLog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null)}onConfirm(){F.warn("confirm clicked, try resume stream"),L.emit(U.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDiaLog()}onCollapseClick(){let t=this._dialogNode.querySelector(`.${jh}`);t.style.visibility=`${this._showDetail?"hidden":"visible"}`,t.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||je.uploadEvent({log:F_}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Xh,"_blank"),this._isQuestionClicked||je.uploadEvent({log:$_}),this._isQuestionClicked=!0}},Qh=ql;var tr=class extends Wr{constructor(e){super(e,N.VIDEO);u(this,"stat",{});u(this,"_calculateTimeout",-1);u(this,"viewMirror",!1);u(this,"objectFit");u(this,"container");u(this,"canvas");this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,V(e.viewMirror)||(this.viewMirror=e.viewMirror),V(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}get isPlaying(){var e;return this._state!=="PLAYING"||this.element&&this.element.paused?!1:((e=this.track)==null?void 0:e.readyState)==="live"&&!this.track.muted}initializeElement(){var r;let e=document.createElement(N.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,(r=this.container)==null||r.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 r;this.container=e,this.track&&this.elementToRender&&((r=this.container)==null||r.appendChild(this.elementToRender))}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),e&&e.add(N.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(N.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent)}handleTrackEvent(e){var r;super.handleTrackEvent(e),e.type===N.MUTE&&((r=this.stat)!=null&&r.fps)&&(this.stat.fps=0)}handleElementEvent(e){var o;if(this.mode===2)return;super.handleElementEvent(e);let r=e.type;if(r===N.PAUSE&&(this.container&&document.getElementById(this.container.id)||this._log.warn(`${this.kind} player has been remove, element ID: ${(o=this.container)==null?void 0:o.id}`),this._pausedRetryCount>0&&!Jl()&&(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 s=this.element.style.transform;r===N.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=s.replace("scaleX(-1)",""):r===N.LEAVE_PICTURE_IN_PICTURE&&!s.includes("scaleX")&&(this.element.style.transform=`${s} scaleX(-1)`)}}setCanvas(e,r=1){var o,s,n,d;this.canvas!==e&&((o=this.canvas)==null||o.remove(),e==null||e.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?r:0,this.mode===2&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?((s=this.element)==null||s.remove(),(n=this.container)==null||n.appendChild(e)):this.element&&((d=this.container)==null||d.appendChild(this.element)))}setAttr(e){let r=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);r.style=Object.assign({width:"100%",height:"100%"},r.style),super.setAttr(r)}get mirror(){return this.viewMirror}setRect(e,r){this.elementToRender&&(this.elementToRender.style.width=`${e}px`,this.elementToRender.style.height=`${r}px`)}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit=`${e}`),this.objectFit=e}setPoster(e){this.element&&(this.element.poster=e)}stop(e=0){var r;super.stop(e),(r=this.canvas)==null||r.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(Ze.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(li()&&this.element&&this._calculateTimeout<0){let e=0,r=null,o=(s,n)=>{this.stat.width=n.width,this.stat.height=n.height,r&&(this.stat.fps=Math.round((n.presentedFrames-r.presentedFrames)/(s-e)*1e3)),e=s,r=n,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var d;return(d=this.element)==null?void 0:d.requestVideoFrameCallback(o)},2e3))};this.element.requestVideoFrameCallback(o)}}catch(e){this._log.warn("init stat failed",e)}}};function $o(i,t){return A(this,null,function*(){if(!i.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield i.audioWorklet.addModule(t),F.info("worklet addModule success")}catch(e){throw F.info(`worklet addModule catch error. ${e.message}`),e}})}var ua;typeof AudioContext!="undefined"?ua=AudioContext:typeof webkitAudioContext!="undefined"?ua=webkitAudioContext:typeof mozAudioContext!="undefined"&&(ua=mozAudioContext);var Ar,Yh=-1;Zh();function Zh(){try{if(Ar)return;Ar=new ua({sampleRate:48e3}),Ar.onstatechange=()=>{F.info(`context state: ${Ar.state}${Ar.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),Bs()},clearTimeout(Yh)}catch(i){F.error(`initAudioContext failed: ${i} typeof AudioContextClass: ${typeof ua}`),Yh=setTimeout(Zh,1e3)}}var Bs=()=>{Ar.state==="suspended"?(Hs(),document.addEventListener("click",Bs)):Ar.state==="interrupted"?Hs():(document.removeEventListener("visibilitychange",Bs),document.removeEventListener("click",Bs))},Xl=0,Ql=-1;function Hs(){return new Promise((i,t)=>{if(Ar.state==="running")return i();Date.now()-Xl<1e3?(clearTimeout(Ql),Ql=setTimeout(()=>{Xl=Date.now(),Ar.resume().then(i,t)},1e3)):(clearTimeout(Ql),Xl=Date.now(),Ar.resume().then(i,t))}).catch(i=>{F.warn(`context resume failed: ${i}`),document.addEventListener("visibilitychange",Bs)})}document.addEventListener("click",Bs);var Ke=i=>Ar;var Ut=class{constructor(){u(this,"node");u(this,"node2");u(this,"pre",new Set);u(this,"next",new Set);u(this,"context");u(this,"connectedNodes",new Set);u(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(t){this._channelCount=t,this.setChannelCount(this.node,t),this.setChannelCount(this.node2,t),this.next.forEach(e=>e.channelCount=t)}setChannelCount(t,e){!t||t instanceof ScriptProcessorNode||(t.channelCountMode="explicit",t.channelCount=e||this.channelCount||1)}setContext(t){this.context=t,this.node&&t.addMixWeight()}removeContext(){var t;this.node&&((t=this.context)==null||t.reduceMixWeight()),delete this.context}replaceNode(t){var e;if(t!==this.node)try{this.node?this._disconnect():(e=this.context)==null||e.addMixWeight(),this.node=t,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(r){F.error(r)}}setNode(t,e){var r;if(!this.node)try{(r=this.context)==null||r.addMixWeight(),this.node=t,this.setChannelCount(this.node),e&&(this.node2=e,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),X.addSuccessEvent({key:502701})}catch(o){F.error(o),X.addFailedEvent({key:502701,error:o})}}deleteNode(){var t;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(t=this.context)==null||t.reduceMixWeight(),this.preNodeReconnect(),X.addSuccessEvent({key:502702})}catch(e){F.error(e),X.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(t=>{t.node?t.reconnect():t.preNodeReconnect()})}connectNext(t){this.next.forEach(e=>{t._connect(e.node)||e.connectNext(t)})}_connect(t){return!this.node||!t?!1:((this.node2||this.node).connect(t),this.connectedNodes.add(t),!0)}_disconnect(){this.connectedNodes.forEach(t=>{var e;return(e=this.node2||this.node)==null?void 0:e.disconnect(t)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(...t){return t.forEach(e=>{this.next.add(e),e.pre.add(this)}),this}},rd=class extends Ut{constructor(e=256){super();this.fftSize=e;u(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(),r=1,o=0,s=0,n=`M${o},${s}`;for(let d=0;d<e.length;d++)s=e[d]/128*100/2,n+=`L${o},${s}`,o+=r;return n}},la=class{constructor(){u(this,"source",new Ut);u(this,"gain",new Ut);u(this,"destination",new Ut)}get volume(){var t;return((t=this.gain.node)==null?void 0:t.gain.value)||1}setVolume(t){if(t===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(Ke().createGain()),this.gain.node.gain.value=t}replaceSource(t){this.source.replaceNode(Yl(t))}get track(){var t;return(t=this.stream)==null?void 0:t.getAudioTracks()[0]}get stream(){var t;return(t=this.destination.node)==null?void 0:t.stream}},Ws=class extends la{constructor(e){super();this.context=e;u(this,"denoiser",new Ut);u(this,"voiceChanger",new Ut);this.source.pipeTo(this.denoiser.pipeTo(this.voiceChanger.pipeTo(this.gain.pipeTo(this.destination))))}connect(){this.context.inputs.has(this)||(this.destination.setNode(this.context.destination),this.source.setContext(this.context),this.denoiser.setContext(this.context),this.voiceChanger.setContext(this.context),this.gain.setContext(this.context),this.context.inputs.add(this))}disconnect(){this.context.inputs.has(this)&&(this.destination.deleteNode(),this.source.removeContext(),this.denoiser.removeContext(),this.voiceChanger.removeContext(),this.gain.removeContext(),this.context.inputs.delete(this))}remove(){this.gain.deleteNode(),this.denoiser.deleteNode(),this.voiceChanger.deleteNode(),this.source.deleteNode(),this.disconnect()}setVolume(e){if(e===1){this.gain.node&&this.gain.deleteNode();return}this.gain.node||this.gain.setNode(this.context.audioContext.createGain()),this.gain.node.gain.value=e}},id=class{constructor(){u(this,"audioContext",Ke("audio-mixer"));u(this,"destination",this.audioContext.createMediaStreamDestination());u(this,"inputs",new Set);u(this,"mixWeight",0);this.destination.channelCount=1}addMixWeight(t=1){this.mixWeight+=t,this.mixWeight-1===t+1>>1&&this.mixOnChange()}reduceMixWeight(t=1){this.addMixWeight(-t)}close(){this.inputs.forEach(t=>t.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},Kh=new WeakMap;function Yl(i){let t=Kh.get(i);if(t)return t;let e=Ke();if(i instanceof HTMLAudioElement)t=e.createMediaElementSource(i);else if(i instanceof MediaStreamTrack)t=e.createMediaStreamSource(new MediaStream([i]));else return i;return Kh.set(i,t),t}var rr=class rr{constructor(t){u(this,"_volume",0);u(this,"_volumeDb",0);u(this,"_log");u(this,"_scriptProcessorNode",null);u(this,"_audioWorkletNode",null);u(this,"_interval",200);u(this,"ready",this.preload());let{log:e}=t;this._log=e,L.on(U.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-rr.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!rr.workletReady){let t='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);';rr.workletReady=$o(rr.audioContext,URL.createObjectURL(new Blob([t],{type:"application/javascript"})))}return rr.workletReady.then(()=>this.initAudioWorklet()).catch(t=>(this._log.error(`volumeMeter preload error: ${t}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(rr.audioContext,"volume-meter");let t=!1;this._audioWorkletNode.port.onmessage=e=>{rr.lastMessageTime=Date.now(),this._volume=e.data.volume||0,this._volumeDb=e.data.volumeDb||0,!t&&e.data.cacheLen&&e.data.outputLen&&(this._log.warn("worklet play success"),t=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(t){this._log.error(`volumeMeter init audio worklet error: ${t}`),je.logFailedEvent({userId:this._log.userId,eventType:Kr.LOAD_WORKLET,error:t}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=Ke("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=t=>{rr.lastMessageTime=Date.now();let e=t.inputBuffer.getChannelData(0),r=0;for(let o=0;o<e.length;++o)r+=e[o]*e[o];this._volume=Math.sqrt(r/e.length)||0}}catch(t){this._log.error(`volumeMeter init script processor error: ${t}`)}}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,L.off(U.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(t){var r;let{interval:e}=t;this._interval=e,(r=this._audioWorkletNode)==null||r.port.postMessage({name:"setIntervalTime",intervalTime:e})}};u(rr,"lastMessageTime",0),u(rr,"audioContext",Ke("volume-meter")),u(rr,"workletReady");var od=rr,sd=class extends Ut{constructor(e){super();u(this,"_volumeMeter");this._volumeMeter=new od(e)}deleteNode(){super.deleteNode(),this._volumeMeter.destroy()}init(){return A(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 r=e.allocationSize({planeIndex:0}),o=new Float32Array(r>>2);e.copyTo(o,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:o},[o.buffer]),e.close()}}},nd=od;var of=ki(Wi(),1);var tf=i=>t=>t.deviceId===i;var ma=class{constructor(t,e="Input"){u(this,"kind");u(this,"type");u(this,"devices",[]);this.kind=t,this.type=e}update(t,e){let r=t.filter(o=>o.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);if(this.devices.length===1&&Gs(this.devices[0])){this.devices=r;return}e&&(r.forEach(o=>{if(o.deviceId&&!this.devices.find(tf(o.deviceId))){let s=`${this.kind}${this.type}Added`;F.warn(`${s}: ${JSON.stringify(o)}`),e.emit(s,o)}}),this.devices.forEach(o=>{if(o.deviceId&&!r.find(tf(o.deviceId))){let s=`${this.kind}${this.type}Removed`;F.warn(`${s}: ${JSON.stringify(o)}`),e.emit(s,o)}})),this.devices=r}hasDevice(t){return!!this.devices.find(e=>e.deviceId===t)}},Zl=class extends of.EventEmitter{constructor(){super();u(this,"audioInputs",new ma(N.AUDIO));u(this,"videoInputs",new ma(N.VIDEO));u(this,"audioOutputs",new ma(N.AUDIO,"Output"));this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||bt.run("interval",()=>{this.update()},{delay:1e4}))}init(){ad().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}update(){return A(this,arguments,function*(e=0){let r=yield ad(e);return this.audioInputs.update(r,this),this.videoInputs.update(r,this),this.audioOutputs.update(r,this),this})}},Tt=Tn||fs?null:new Zl;function Gs(i){return i.deviceId===i.groupId&&i.groupId===""}function ad(){return A(this,arguments,function*(i=0){if(ui()||!Yc())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(i!==0){let e={audio:!1,video:!1};if(t.forEach(r=>{Gs(r)&&(r.kind===N.AUDIO_INPUT?e.audio=!0:r.kind===N.VIDEO_INPUT&&(e.video=!0))}),i===2&&(e.audio=!1),i===1&&(e.video=!1),e.audio||e.video){let r;try{r=yield navigator.mediaDevices.getUserMedia(e),e.audio&&Hs()}catch(o){F.debug("capture before getDevices failed: ",o)}t=yield navigator.mediaDevices.enumerateDevices(),r==null||r.getTracks().forEach(o=>o.stop())}}return t.map((e,r)=>{let o={kind:e.kind,deviceId:e.deviceId,groupId:e.groupId,label:e.label||`${e.kind}_${r}`};return e.deviceId.length>0&&Kl.add(`${e.deviceId}_${e.kind}`),e.getCapabilities&&(o.getCapabilities=()=>e.getCapabilities()),o})})}function Xt(i=!1){return Tt.update(i?1:0).then(t=>t.audioInputs.devices)}function ir(i=!1){return Tt.update(i?2:0).then(t=>t.videoInputs.devices)}var rf=!1;function sf(){return A(this,null,function*(){try{rf||(rf=!0,F.info(`speakers:${(yield Xi()).map(i=>` ${i.deviceId.slice(0,8)}: ${i.label}`)}`))}catch(i){}})}function Xi(i=!1){return A(this,null,function*(){return(mt||At)&&(i=!1),Tt.update(i?1:0).then(t=>t.audioOutputs.devices)})}var Kl=new Set;function nf(i){if(i instanceof CanvasCaptureMediaStreamTrack||!(i instanceof MediaStreamTrack))return!1;let t=i.label.toLocaleLowerCase();if(t.includes("camera")||t.includes("webcam"))return!0;let r=`${((i==null?void 0:i.getSettings())||{}).deviceId}_${N.VIDEO_INPUT}`;return!!Kl.has(r)}function af(i){if(i instanceof CanvasCaptureMediaStreamTrack||!(i instanceof MediaStreamTrack))return!1;let t=i.label.toLocaleLowerCase();if(t.includes("mic")||t.includes("\u9EA6\u514B\u98CE"))return!0;let r=`${((i==null?void 0:i.getSettings())||{}).deviceId}_${N.AUDIO_INPUT}`;return!!Kl.has(r)}function em(i,t){return A(this,null,function*(){let r=(yield Xt()).find(o=>o.deviceId===Co);return!t&&(r==null?void 0:r.groupId)===i||(r==null?void 0:r.groupId)===i&&r.label===t})}function cf(s){return A(this,arguments,function*({newDeviceId:i,oldDeviceId:t,oldGroupId:e,oldLabel:r,kind:o}){return i!==t?!1:o===N.AUDIO&&i===Co?yield em(e,r):!0})}var cd,tm=class extends la{constructor(e){super();this.log=e;u(this,"volumeMeter");u(this,"volumeDestination");u(this,"analyser",new rd);this.volumeMeter=new sd({log:this.log}),this.volumeDestination=new Ut,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},dd=class i extends Wr{constructor(e){super(e,N.AUDIO);u(this,"_outputDeviceId");u(this,"_volume",1);u(this,"_destination",Ke("player").createMediaStreamDestination());u(this,"pipeline");u(this,"volumeMeterMode","worklet");this.mode=0,this.pipeline=new tm(this._log)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((Hi==="15.2"||Hi==="15.3"||Hi==="15.4")&&this.muted){this._log.info("audioElement is muted.");return}let o=cd||new Audio;o.setAttribute("autoplay","autoplay"),o.srcObject=this.getMediaStream(),o.muted=this.muted,this.element=o,We(e)&&(this.element.volume=Math.min(Math.max(e,0),1)),o===cd&&(cd=void 0),this.bindElementEvents()}play(e){return A(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(Ke("player").createAnalyser()),sf(),Bt(i.prototype,this,"play").call(this)})}stop(e=0){this.pipeline.destroy(),super.stop(e)}setSinkId(e){return A(this,null,function*(){var r,o;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(o=(r=this.element).setSinkId)==null?void 0:o.call(r,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()}},ud=class extends dd{setTrack(t){this.track!==t&&(this.unbindTrackEvents(),this.track=t,this.emit(Ze.MEDIA_TRACK_CHANGED,t),t&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([t]))))}setVolume(t){this._volume=t,this.element&&(this.element.volume=t)}},ld=class extends dd{constructor(e){super(e);u(this,"_sourceElement");u(this,"_output",new Ut);this.pipeline.source.pipeTo(this.pipeline.gain.pipeTo(this.pipeline.volumeMeter.pipeTo(this._output),this.pipeline.destination))}setOutput(){this.mode=1,this._output.setNode(Ke("player").destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var r,o,s;((o=(r=this.element)==null?void 0:r.error)==null?void 0:o.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(Ze.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=((s=e.getSettings())==null?void 0:s.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){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"):mt||(this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this.pipeline.destination.setNode(this._destination),pt(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play()))}stop(e=0){this.pipeline.destroy();let r=this._sourceElement||this.element;r&&Bi&&(cd=r),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}};var Bo=class extends oe{constructor({userId:e,sdkAppId:r,mediaType:o,room:s,PlayerClass:n=o===1?ld:tr}){var d;super();u(this,"id",zn());u(this,"userId","");u(this,"isRemote");u(this,"mediaType");u(this,"room");u(this,"user");u(this,"_log");u(this,"_inputTrack");u(this,"_outputTrack");u(this,"isPlayCalled");u(this,"container",null);u(this,"player");u(this,"subVideoPlayerMap");u(this,"muted",!1);u(this,"abortCtrl");u(this,"objectFit","cover");u(this,"mirror");u(this,"isScreen",!1);u(this,"manager");u(this,"trackSettings");u(this,"isFirstVideoFrameEmitted",!1);this.userId=e||"",this.mediaType=o,this._log=F.createLogger({id:`${this.kind[0]}t`,userId:(d=s||this.room)==null?void 0:d.userId,remoteUserId:this instanceof pi?void 0:this.userId,sdkAppId:r,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof pi}),this.player=new n({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log}),this.player.on(Ze.PLAYER_STATE_CHANGED,m=>{L.emit(U.PLAYER_STATE_CHANGED,Z({track:this},m)),this.emit("player-state-changed",m)}),this.kind===N.VIDEO&&(this.player.on(Ze.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(Ze.LOADED_DATA),L.emit(U.VIDEO_LOADED_DATA,{track:this})}),this.player.on(Ze.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(Ze.LOADED_META_DATA)}),this.player.on(Ze.MEDIA_TRACK_CHANGED,m=>{var l;(l=this.subVideoPlayerMap)==null||l.forEach(g=>g.setTrack(m))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(Ze.ERROR,this.onPlayerError.bind(this))}get log(){return this._log||F}get kind(){return this.mediaType===1?N.AUDIO:N.VIDEO}get strMediaType(){return this.mediaType===4?N.VIDEO:this.mediaType===2?N.SCREEN:N.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,r){return A(this,null,function*(){let o=it(e)?e[0]:e;if(this.isPlayCalled){this.log.info(`play update options: ${JSON.stringify(r)}`),r&&!V(r.muted)&&this.setPlayerMute(r.muted),r&&!V(r.objectFit)&&(this.objectFit=r.objectFit),this.player instanceof tr&&(this.player.setObjectFit(this.objectFit),this.container!==o&&o&&(this.container=o,this.player.setContainer(o)),it(e)&&e.length>=1&&(yield this.playSubContainer(e.slice(1),r)));return}if(r&&!V(r.muted)?this.setPlayerMute(r.muted):(!this.isRemote||this.kind===N.VIDEO)&&this.setPlayerMute(!0),r&&!V(r.objectFit)&&(this.objectFit=r.objectFit),this.player instanceof tr&&(this.player.setObjectFit(this.objectFit),r&&!V(r.poster)&&this.player.setPoster(r.poster)),this.isPlayCalled=!0,o&&(this.container=o,this.player instanceof tr&&this.player.setContainer(o)),L.emit(U.PLAY_TRACK_START,{track:this}),!this._outputTrack){this.log.info("play has not mediaTrack, abort");return}this._log.info(`play with options: ${JSON.stringify(r)}`);try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(r),it(e)&&e.length>1&&(yield this.playSubContainer(e.slice(1),r))}catch(s){throw this.handleAutoPlayFailed(s),s}})}setMirror(e,r){if(this.isScreen||this.kind!==N.VIDEO||V(e)||e===this.mirror)return;this.mirror=e;let o=this.player;r&&(o=r);let s=this.manager;if(dt(this.mirror)){o.setViewMirror(this.mirror),s&&(s.mirror=!1);return}switch(this.mirror){case"view":{s&&(s.mirror=!1),o.setViewMirror(!0);break}case"publish":{s&&(s.mirror=!0),o.setViewMirror(!0);break}case"both":s&&(s.mirror=!0),o.setViewMirror(!1)}}playSubContainer(e,r){return A(this,null,function*(){if(!this._outputTrack||this.kind===N.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((s,n)=>{var d;e.find(m=>n===m)||(s.stop(),(d=this.subVideoPlayerMap)==null||d.delete(n))});for(let[s,n]of e.entries()){let d=this.subVideoPlayerMap.get(n);d?r&&(V(r.objectFit)||d.setObjectFit(r.objectFit)):this.subVideoPlayerMap.set(n,new tr({id:this.userId||this.id,track:this.playerMediaTrack,container:n,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${s+1}`})}))}let o=[...this.subVideoPlayerMap.values()];for(let s of o)s.setViewMirror(this.player.mirror),yield s.play()})}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(e=!1){this.isPlayCalled&&(this.isPlayCalled=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(zu(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(r=>{r.stop()}),this.container=null)}resume(){return A(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),L.emit(e?U.TRACK_MUTED:U.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){Lt(e,e).add(N.MUTE,this.onTrackMuted).add(N.UNMUTE,this.onTrackUnmuted).add(N.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===N.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){pt(e)}setInputMediaStreamTrack(e){var o;let r=this._inputTrack;if(e!==r)return this._inputTrack=e,this.trackSettings=(o=e.getSettings)==null?void 0:o.call(e),e.enabled=!this.muted,r&&this.uninstallTrackEvent(r),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,r||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var o;let r=this._outputTrack;e!==r&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(o=e.getSettings)==null?void 0:o.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(r=>this.handleAutoPlayFailed(r)),this.log.info(`playing state updated, play ${this.kind}`);return}}else if(!this.player.isStopped){this.player.stop(zu(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 Qh;else{let r=()=>{this.resume().then(()=>{document.removeEventListener("click",r,!0)})};document.addEventListener("click",r,!0)}this.emit("error",e)}getVideoFrame(){return this.player instanceof tr?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var n,d,m;if(this.isFirstVideoFrameEmitted)return;let r=(n=this.mediaTrack)==null?void 0:n.getSettings(),o=(r==null?void 0:r.width)||((d=this.player.element)==null?void 0:d.videoWidth)||0,s=(r==null?void 0:r.height)||((m=this.player.element)==null?void 0:m.videoHeight)||0;e===Ze.LOADED_META_DATA&&!o&&!s||(e===Ze.LOADED_DATA&&!o&&!s&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,this.emit("first-video-frame",{width:o,height:s,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};J([Je([],oe.INIT,{sync:!0})],Bo.prototype,"close",1);var H_=Object.prototype.hasOwnProperty,{toString:VR}=Object.prototype;function W_(i){if(i==null)return!0;if(typeof i=="boolean")return!1;if(typeof i=="number")return i===0;if(typeof i=="string"||typeof i=="function"||Array.isArray(i))return i.length===0;if(i instanceof Error)return i.message==="";if(xt(i))switch(Object.prototype.toString.call(i)){case"[object File]":case"[object Map]":case"[object Set]":return i.size===0;case"[object Object]":{for(let t in i)if(H_.call(i,t))return!1;return!0}}return!1}var pa=W_;var G_=function(i){return A(this,null,function*(){let t=q_(i);F.info(`getUserMedia with constraints: ${JSON.stringify(t)}`);let e=[],r=[],o=["label","deviceId","groupId"];t.audio&&(e=yield Xt(),F.info(`microphones: ${ar(e.map(s=>Ee(Z({},s),{groupId:s.groupId.substring(0,8)})),{keysToInclude:o})}`)),t.video&&(r=yield ir(),F.info(`cameras: ${ar(r,{keysToInclude:o})}`));try{let s=yield navigator.mediaDevices.getUserMedia(t);return Ll&&s.getTracks().forEach(n=>{F.info(`${n.kind} capabilities: ${ar(n.getCapabilities(),{keysToInclude:pc})}`)}),t.audio&&Hs(),s}catch(s){let{message:n}=s;throw s.name==="NotFoundError"&&(i.video&&r&&r.length===0&&(n=$e({key:Fe.CAMERA_NOT_FOUND})),i.audio&&e&&e.length===0&&(n=$e({key:Fe.MICROPHONE_NOT_FOUND}))),new ae({code:q.INITIALIZE_FAILED,name:s.name,message:n,constraint:s.constraint})}})},j_=Fi({retryFunction:G_,settings:{retries:3,timeout:500},onError:({error:i,retry:t,reject:e,retryFuncArgs:r,retriedCount:o})=>{let s=o+1;i.name==="NotReadableError"||i.name==="OverconstrainedError"?(s===1?(r[0].video&&(r[0].maxResolution=!1,(!At||r[0].width*r[0].height<=1920*1080)&&r[0].frameRate&&(r[0].frameRate=r[0].frameRate>10?10:5)),r[0].retryWhenExactFailed&&r[0].useExactDeviceId&&(r[0].useExactDeviceId=!1)):s===2?r[0].useDeviceIdOnly=!0:s===3&&!r[0].useExactDeviceId&&(r[0].useTrueAsConstraint=!0),t()):e(i),r[0].microphoneId&&df(r[0].microphoneId,!1),r[0].cameraId&&df(r[0].cameraId,!0)},onRetrying:i=>{F.warn(`getUserMedia NotReadableError observed, retrying [${i}/3]`)},onRetryFailed:i=>{je.logFailedEvent({eventType:Kr.GET_USER_MEDIA_RETRY,error:i})},onRetrySuccess:i=>{je.logSuccessEvent({eventType:Kr.GET_USER_MEDIA_RETRY}),je.uploadEvent({log:`stat-${Kr.GET_USER_MEDIA_RETRY}-success-${i}`})}});function df(i,t){return A(this,null,function*(){let r=(t?yield ir():yield Xt()).find(o=>o.deviceId===i);r&&He(r.getCapabilities)&&F.warn(ar(r.getCapabilities(),{keysToInclude:pc}))})}function q_(i){return{audio:z_(i),video:J_(i)}}function z_(i){if(!i.audio)return!1;if(i.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:i.sampleRate};return!pa(i.microphoneId)&&(t.deviceId=i.useExactDeviceId?{exact:i.microphoneId}:i.microphoneId,i.useDeviceIdOnly)?t:(We(i.channelCount)&&(t.channelCount=i.channelCount),dt(i.echoCancellation)&&!i.echoCancellation&&(t.echoCancellation=!1),dt(i.noiseSuppression)&&!i.noiseSuppression&&(t.noiseSuppression=!1),dt(i.autoGainControl)&&!i.autoGainControl&&(t.autoGainControl=!1),pa(t)?!0:t)}function J_(i){if(!i.video)return!1;if(i.useTrueAsConstraint)return!0;let{maxResolution:t=!0}=i,e={};return i.cameraId?e.deviceId=i.useExactDeviceId?{exact:i.cameraId}:i.cameraId:i.facingMode&&(e.facingMode=i.facingMode),i.useDeviceIdOnly&&!pa(e)?e:(i.width&&(e.width={ideal:i.width},t&&!Ht&&(e.width.max=i.width)),i.height&&(e.height={ideal:i.height},t&&!Ht&&(e.height.max=i.height)),Ht&&Sr&&i.width&&i.height&&i.width*i.height<352*288&&(e.width=i.width,e.height=i.height),i.frameRate&&(e.frameRate=i.frameRate),pa(e)?!0:e)}var uf=j_;function Qi(i){return Me((t,e)=>function(...r){return A(this,null,function*(){let o=yield t.apply(this,r);return yield i.call(this,...r),o})})}function lf(i){return Me((t,e)=>function(...r){return A(this,null,function*(){try{return yield t.apply(this,r)}catch(o){i.call(this,o)}})})}function Me(i){return function(t,e,r){return r.value=i(r.value,e),r}}var mf=(()=>{let i=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&F.info(`visibility change: ${document.visibilityState}`),!i&&(document.addEventListener("visibilitychange",()=>{F.info(`visibility change: ${document.visibilityState}`),t=document.visibilityState}),i=!0)}})();var X_=0,md=class{constructor(){u(this,"log",F.createLogger({id:`fq${++X_}`}));u(this,"isRunning",!1);u(this,"queue",[])}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(t,e=!1){var s,n;let r=Z({},t),o=new Promise((d,m)=>{r.resolve=d,r.reject=m});return r.promise=o,e?this.length<=1?this.queue.push(r):(n=(s=this.lastQueueItem)==null?void 0:s.promise)==null||n.then(r.resolve,r.reject):this.queue.push(r),this.log.debug(`push ${this.length}`),this.isRunning||this.callNext(),o}shift(){let t=this.queue.shift();return this.log.debug(`shift ${this.length}`),t}callNext(){if(this.isRunning||this.length===0)return;this.log.debug("callNext ",this.length);let{fn:t,args:e,context:r,resolve:o,reject:s}=this.queue[0];this.isRunning=!0,t.apply(r,e).then(o,s).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},pf=new WeakMap,hf=new WeakMap;function ff(i=!1){return function(t,e,r){let o=r.value;return r.value=function(...s){let n=pf.get(this)||new md;return pf.set(this,n),n.push({fn:o,args:s,context:this},i)},r}}function pd(i){return function(t,e,r){let o=r.value,s=n=>i(...n);return r.value=function(...n){let d=hf.get(this)||new Map,m=d.get(s(n))||new md;return d.set(s(n),m),hf.set(this,d),m.push({fn:o,args:n,context:this})},r}}function hd(i,t){return Me((e,r)=>function(...o){let s=i;try{let n=e.apply(this,o),d=Te();return Ui(n)?n.then(m=>(t?X.addSuccessEvent({key:s,cost:Te()-d}):X.addSuccessEvent({key:s}),m)).catch(m=>{throw X.addFailedEvent({key:s,error:m}),m}):(X.addSuccessEvent({key:s}),n)}catch(n){throw X.addFailedEvent({key:s,error:n}),n}})}var Ho=class Ho extends Bo{constructor(e,r){super({mediaType:e,PlayerClass:r});u(this,"isRemote",!1);u(this,"deviceId");u(this,"groupId","");u(this,"label","");u(this,"sourceTrack");u(this,"_isRecapturing",!1);u(this,"_lastRecaptureTime",0);u(this,"_onMuteTimeoutId",-1);u(this,"_encodeCheckTimeoutId",-1);u(this,"profile")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}encodeFrame(e,r){throw new Error("Method not implemented.")}installTrackEvent(e){Lt(e,e).add(N.MUTE,this.onTrackMuted).add(N.UNMUTE,this.onTrackUnmuted).add(N.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===N.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){pt(e)}setStateToCapture(){}capture(e){return A(this,null,function*(){var r;try{let o=Te();L.emit(U.LOCAL_TRACK_CAPTURE_START,{track:this});let s;e.customSource?(s=new MediaStream,s.addTrack(e.customSource)):((r=this.mediaTrack)==null||r.stop(),s=yield uf(e));let n=s.getTracks()[0];return this.sourceTrack=n,yield this.setInputMediaStreamTrack(n),e.customSource||(this.updateDeviceIdInUse(),this.listenDeviceChange()),L.emit(U.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:Te()-o}),s}catch(o){throw L.emit(U.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:o}),this.log.error(`getUserMedia error observed ${o}`),o}})}setInputMediaStreamTrack(e){return this.state===oe.INIT&&this.setStateToCapture(),super.setInputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var r;if(super.setOutputMediaStreamTrack(e),this.isPublishing||this.isPublished)return(r=this.room)==null?void 0:r.replaceTrack(this)}publish(e,r){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),r}unpublish(){this.room&&this.room.localTracks.delete(this),L.emit(U.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return A(this,null,function*(){if(this.mediaTrack&&Fs){let{deviceId:e,groupId:r}=this.mediaTrack.getSettings(),{label:o}=this.mediaTrack;(yield cf({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=o,r&&(this.groupId=r),ad().then(n=>{let d=n.find(m=>m.deviceId===e);d&&this.emit("2",d)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.mediaTrack||this.kind===N.AUDIO&&!af(this.mediaTrack)||this.kind===N.VIDEO&&!nf(this.mediaTrack)||this._isRecapturing||e&&Sr&&At)}onTrackMuted(){if(super.onTrackMuted(),mf(),!!this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<_s){setTimeout(()=>this.onTrackMuted(),_s);return}this._onMuteTimeoutId=setTimeout(()=>A(this,null,function*(){var e;if((e=this.mediaTrack)!=null&&e.muted){if((mt||ut)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return A(this,null,function*(){if(Bt(Ho.prototype,this,"onTrackEnded").call(this),!!this.isNeedToRecapture()){if(Date.now()-this._lastRecaptureTime<_s){setTimeout(()=>this.onTrackEnded(),_s);return}this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){return A(this,null,function*(){var o;if(this._isRecapturing||!this._inputTrack)return;this.log.warn("recapture trying"),(o=this._inputTrack)==null||o.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let r={useExactDeviceId:!0};if(e==="user"||e==="environment")r.facingMode=e;else{let s;(this.kind==="audio"?yield Xt():yield ir()).find(d=>d.deviceId===e)&&(s=e),r.deviceId=s}return this.capture(r).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),L.emit(U.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(s=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${s.message}`),this.emit("5",s),L.emit(U.LOCAL_TRACK_RECAPTURE,{track:this,error:s})})})}getRecoverCaptureDeviceId(){return A(this,null,function*(){let e=this instanceof br;if(e&&this.facingMode)return this.facingMode;let{deviceId:r}=this;if(r){let o=(ha.get(r)||0)+1;if(ha.set(r,o),o>=3){let s=e?(yield ir()).find(n=>!ha.has(n.deviceId)):(yield Xt()).find(n=>!ha.has(n.deviceId));s&&(this.log.warn(`${r} capture fail ${o} times, change new ${s.deviceId}`),r=s.deviceId)}}return r})}close(){var e;super.close(),this._inputTrack&&(this._inputTrack.stop(),this.uninstallTrackEvent(this._inputTrack)),(e=this.manager)==null||e.removeInput(this)}};J([Je(oe.INIT,"capture",{ignoreError:!0,sync:!0})],Ho.prototype,"setStateToCapture",1),J([ff()],Ho.prototype,"capture",1),J([Je("capture","publish",{ignoreError:!0,success(){var r,o;this.room.localTracks.add(this),L.emit(U.LOCAL_TRACK_PUBLISHED,{track:this}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),!((((o=(r=this.room)==null?void 0:r.networkQuality)==null?void 0:o.uplinkNetworkQuality)||0)>3)&&(this._encodeCheckTimeoutId=setTimeout(()=>{var n,d;if(!((((d=(n=this.room)==null?void 0:n.networkQuality)==null?void 0:d.uplinkNetworkQuality)||0)>3)&&this.isPublished&&this.isMediaTrackActive){let m=this.kind===N.AUDIO,l=this.stat.bytesSent>0;X[l?"addSuccessEvent":"addFailedEvent"]({key:m?503700:513702}),l||(X.addEnum({key:m?503701:513703,value:jn()}),je.uploadEvent({log:`stat-encode-failed-${this.kind}-${Gn()||Po()}`,userId:this.userId}),this.log.warn("encode failed"),this.emit("6",this))}},5e3))},fail(e){let r="error";if(e.cause instanceof RTCError){let o=e.cause;o.message.includes("timeout")?r="timeout":o.code===q.API_CALL_ABORTED&&(r="api-call")}this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:r,error:e.cause||e})}}),hd(521714,!1)],Ho.prototype,"publish",1),J([Me(e=>function(){return A(this,null,function*(){let r=this.state==="publish"?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:r,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),Je([],"capture",{sync:!0})],Ho.prototype,"unpublish",1);var pi=Ho,ha=new Map;L.on(U.SWITCH_DEVICE_SUCCESS,i=>{i.track.deviceId&&ha.delete(i.track.deviceId)});var hi=class i extends pi{constructor(e){super(1,ud);u(this,"mediaType",1);u(this,"volume",0);u(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40});u(this,"playerMuted",!0);u(this,"pipeline");u(this,"earMonitorGainNode",new Ut);u(this,"_output",new Ut);u(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0});this.manager=e,this.pipeline=new Ws(e),this.pipeline.gain.pipeTo(this.earMonitorGainNode.pipeTo(this._output),this.player.pipeline.volumeMeter),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this)}get dbVolume(){return nd.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}setInputMediaStreamTrack(e){return A(this,null,function*(){let r=this.trackSettings||{};X.addEnum({key:501701,value:r.channelCount||0,useUV:!1}),X.addEnum({key:501702,value:r.sampleRate||0,useUV:!1}),X.addEnum({key:502700,value:0});let{sampleRate:o,channelCount:s}=r;this._log.info(`local audio track input ${JSON.stringify({sampleRate:o,channelCount:s})}`),this.pipeline.source.channelCount=s||1,this.pipeline.replaceSource(e),yield Bt(i.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture({deviceId:e,customSource:r,useExactDeviceId:o=!0,retryWhenExactFailed:s=!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:o,retryWhenExactFailed:s,customSource:r})}switchDevice(e){return A(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e)if(e===Co){if(yield em(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}),L.emit(U.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(r){throw this.log.error(`switch microphone failed ${r}`),this.deviceId&&this.recapture(this.deviceId),r}}})}listenDeviceChange(){Tt&&!Tt.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&Tt.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return A(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current microphone is lost: ${JSON.stringify(e)}`),ot(this.userId,{eventId:2003,param1:6,streamType:1});let r=yield Xt();r[0]?this.recapture(r[0].deviceId):Tt.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.log.warn(`microphone added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)}update3A(s){return A(this,arguments,function*({echoCancellation:e,noiseSuppression:r,autoGainControl:o}){let n=this.sourceTrack||this.mediaTrack;if(!n)return;let d=n.getConstraints(),m=!1;!V(e)&&e!==this.profile.echoCancellation&&(this.profile.echoCancellation=e,d.echoCancellation=e,m=!0),!V(r)&&r!==this.profile.noiseSuppression&&(this.profile.noiseSuppression=r,d.noiseSuppression=r,m=!0),!V(o)&&o!==this.profile.autoGainControl&&(this.profile.autoGainControl=o,d.autoGainControl=o,m=!0),m&&(Ht||At?yield n.applyConstraints(d).catch(l=>this._log.warn("update3A failed: ",l)):this.deviceId&&(yield this.recapture(this.deviceId)))})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&X.addEnum({key:502700,value:2})}setAudioVolume(e){super.setAudioVolume(0),mt&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(Ke().createGain()),this._output.setNode(Ke().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}addDenoiser(e){var r;if(oi<=92&&((r=this.trackSettings)==null?void 0:r.sampleRate)!==48e3){this._log.warn("denoiser only support sampleRate 48000 before chrome 93");return}X.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.enableTrackANS(!1)}removeDenoiser(e){this.pipeline.denoiser.node===e&&(this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0))}close(){this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),Tt.off("audioInputAdded",this.handleMicrophoneAdded,this),Tt.off("audioInputRemoved",this.handleMicrophoneRemoved,this),super.close()}recapture(e){return A(this,null,function*(){try{yield Bt(i.prototype,this,"recapture").call(this,e)}catch(r){let o=(yield Xt()).find(s=>s.deviceId!==e);if(o)yield Bt(i.prototype,this,"recapture").call(this,o.deviceId);else throw r}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((r,o)=>o?o({frame:r}):r,e):e}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}};var Wo=class{constructor(t,e=!1){this.dataView=t;this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let t=this.seiPayloadStartIndex,e=this.dataView.byteLength-2,r=[],o=0;for(let n=t;n<=e;n++){let d=this.dataView.getInt8(n);switch(d){case 0:case 1:case 2:case 3:o===2&&(r.push(3),o=0),d==0?o++:o=0,r.push(d);break;default:o=0,r.push(d);break}}r.push(this.dataView.getInt8(this.dataView.byteLength-1));let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,t),...r]).buffer);this.dataView=s}removePreventionByte(){let t=this.seiPayloadStartIndex,e=this.dataView.byteLength-1,r=[],o=0;for(let n=t;n<=e;n++)switch(this.dataView.getInt8(n)){case 0:o++,r.push(this.dataView.getInt8(n));break;case 3:o!==2&&r.push(this.dataView.getInt8(n)),o=0;break;default:r.push(this.dataView.getInt8(n)),o=0;break}let s=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,t),...r]).buffer);this.dataView=s}get isSEI(){return this.dataView.getUint8(4)===6}get seiPayloadStartIndex(){let t=6;for(let e=6;e<this.dataView.buffer.byteLength&&(t++,this.dataView.getUint8(e)===255);e++);return t}get seiPayloadType(){return this.isSEI?this.dataView.getUint8(5):null}get seiPayload(){if(!this.isSEI)return null;let t=0,e=6;for(let s=6;s<this.dataView.buffer.byteLength;s++){let n=this.dataView.getUint8(s);if(e++,n===255)t+=255;else{t+=n;break}}let r=new ArrayBuffer(t),o=new DataView(r);for(let s=0;s<r.byteLength;s++,e++)o.setInt8(s,this.dataView.getInt8(e));return o}};var fd=class{constructor(){u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(this,"_seiPayloadType",243)}encodeSEINalu(t){let e=t.byteLength,r=parseInt(String(e/255),10),o=e%255,s=[];s.push(0,0,0,1,6,this._seiPayloadType);for(let d=0;d<r;d++)s.push(255);s.push(o);let n=new DataView(t);return s.push(...new Uint8Array(n.buffer)),s.push(128),new Wo(new DataView(new Uint8Array(s).buffer),!0)}sendSEI(t,e){e!=null&&e.seiPayloadType&&(this._seiPayloadType=e.seiPayloadType),this._seiMessageList.push(t),e!=null&&e.small&&this._smallSeiMessageList.push(t)}isEmpty(){return!this._seiMessageList.length}getNaluCount(t){let e=0,r=0,o=new DataView(t);for(let s=0;s<t.byteLength;s++)switch(o.getUint8(s)){case 0:e++;break;case 1:(e===2||e===3)&&r++,e=0;break;default:e=0;break}return r}encode(t,e){let r=e?this._smallSeiMessageList:this._seiMessageList;if(r.length>0&&t.data.byteLength>0){let s=9-this.getNaluCount(t.data);if(s<=0)return 0;let n=r.splice(0,s).reverse().map(this.encodeSEINalu.bind(this)),d=n.reduce((S,v)=>S+v.dataView.byteLength,0),m=new ArrayBuffer(d+t.data.byteLength),l=new DataView(m),g=new DataView(t.data),_=0;for(let S=0;S<n.length;S++)for(let v=0;v<n[S].dataView.byteLength;v++)l.setInt8(_++,n[S].dataView.getInt8(v));for(let S=0;S<t.data.byteLength;S++)l.setInt8(_++,g.getInt8(S));return t.data=m,n.length}return 0}};var Go=class Go extends pi{constructor(e,r=4){super(r,tr);u(this,"profile",{width:640,height:480,frameRate:15,bitrate:500});u(this,"avoidCropping",!1);u(this,"_scaleResolutionDownBy");u(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0});u(this,"small");u(this,"isNeedToSetBandwidth");u(this,"muteImage");u(this,"manager");u(this,"_seiCodec",new fd);this.manager=e;let o=()=>{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(Ee(Z({},this.profile),{width:1920,height:1080})),this.applyProfile())};this.on("input-media-track-changed",o),this.on("publish",o),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(!(!Fs||!this.mediaTrack))return this.mediaTrack.getSettings().facingMode}get contentHint(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)||""}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}setMute(e){return A(this,null,function*(){var r,o,s;if(ve(e)){if(this.muteImage===e)return;yield(r=this.manager)==null?void 0:r.deleteWatermark("mute"),yield(o=this.manager)==null?void 0:o.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e}),this.muteImage=e,Bt(Go.prototype,this,"setMute").call(this,!1)}else yield(s=this.manager)==null?void 0:s.deleteWatermark("mute"),this.muteImage=void 0,Bt(Go.prototype,this,"setMute").call(this,e)})}capture({deviceId:e,facingMode:r,useExactDeviceId:o=!0,customSource:s,retryWhenExactFailed:n=!0}){return super.capture({audio:!1,video:!0,facingMode:r||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:o,retryWhenExactFailed:n,customSource:s})}setProfile(e){let r=Z({},e),o=r.width>r.height;r.width*r.height<=160*120&&ut&&ii&&(this.log.warn(`resolution is ${r.width}*${r.height}, fallback to 240*180`),r.width=o?240:180,r.height=o?180:240,r.bitrate=Math.max(r.bitrate,150)),r.width*r.height>1280*720&&nl&&(r.width=o?1280:720,r.height=o?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),this.avoidCropping&&(ii||Ht)&&!cl()&&r.width*r.height<=640*360&&r.width/r.height===16/9&&(this._scaleResolutionDownBy=1280/r.width,r.width=1280,r.height=720,this.log.warn(`capture 720p, scale: ${this._scaleResolutionDownBy}`)),r.bitrate&&(this.isNeedToSetBandwidth=r.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile)?super.setProfile(r):(this.log.warn("Resolution is reset to 1080p, need to upgrade ability here https://cloud.tencent.com/document/product/647/85386"),super.setProfile(Ee(Z({},this.profile),{width:1920,height:1080})))}applyProfile(){return A(this,null,function*(){var d;if(!this.mediaTrack)return;let{width:e=0,height:r=0}=(this.sourceTrack||this.mediaTrack).getSettings(),o=e*r,s=this.settings;if(!(!(s.height!==this.profile.height||s.width!==this.profile.width||s.frameRate!==this.profile.frameRate)||!this.deviceId)&&(er===16?yield this.recapture(this.deviceId):(yield(d=this.sourceTrack||this.mediaTrack)==null?void 0:d.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1}),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth)){this.isNeedToSetBandwidth=!1;let{width:m=0,height:l=0}=(this.sourceTrack||this.mediaTrack).getSettings(),g=m*l;if(g&&o&&g===o){this.log.warn("set bandwidth failed: resolution is not changed");return}return this.room.setBandWidth({bandwidth:this.profile.bitrate,type:N.VIDEO,videoType:N.BIG})}})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate};return Fs&&this.mediaTrack&&Object.assign(e,this.mediaTrack.getSettings()),e}get scaleResolutionDownBy(){if(this._scaleResolutionDownBy)return this._scaleResolutionDownBy;let{settings:e}=this;return e.width===this.profile.width&&e.height===this.profile.height?1:Ec()&&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 r;return!this.room||!this.room.scheduleResult||this.isScreen||e.height*e.width<2560*1440?!0:((r=this.room.scheduleResult.trtcAutoConf)==null?void 0:r["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return A(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e))return;let r={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?r.facingMode=e:r.deviceId=e,this.mediaTrack.stop(),yield this.capture(r),L.emit(U.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(r){throw this.log.error(`switch camera failed ${r}`),this.deviceId&&this.recapture(this.deviceId),r}})}listenDeviceChange(){Tt&&!Tt.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&Tt.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return A(this,null,function*(){if(e.deviceId===this.deviceId){this.log.warn(`current camera is lost: ${JSON.stringify(e)}`),ot(this.userId,{eventId:2003,param1:7,streamType:2});let r=yield ir();r[0]?this.recapture(r[0].deviceId):Tt.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return A(this,null,function*(){this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId)})}encodeFrame(e,r){if(!this.manager)return e;let o=r?8:this.mediaType;return this.manager.encodePipeline.reduceRight((s,n)=>n?n({frame:s,mediaType:o}):s,e)}get enableEncodeFrame(){return this.manager?this.manager.encodePipeline.some(e=>e):!1}play(e,r){return V(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,r)}close(){Tt.off("videoInputAdded",this.handleCameraAdded,this),Tt.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return A(this,null,function*(){try{yield Bt(Go.prototype,this,"recapture").call(this,e)}catch(r){let o=(yield ir()).find(s=>s.deviceId!==e);if(o)yield Bt(Go.prototype,this,"recapture").call(this,o.deviceId);else throw r}})}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))}};J([Qi(function(e){this.setContentHint(e.contentHint||"motion")})],Go.prototype,"capture",1);var br=Go;var _f=zn();if(typeof navigator!="undefined"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:_f,exposeOrigin:!0,permittedOrigins:["*"]})}catch(i){}var Z_=function(i){return A(this,null,function*(){let t=null,e=tT(i);F.info(`getDisplayMedia with constraints: ${JSON.stringify(e)}`);let r=yield navigator.mediaDevices.getDisplayMedia(e);i.systemAudio&&r.getAudioTracks().length===0&&(Ps&&oi<74||At||Ht)&&F.warn("Your browser not support capture system audio");let o=r.getVideoTracks()[0];if(o){if(i.frameRate)try{yield o.applyConstraints({frameRate:{min:i.frameRate,ideal:i.frameRate},width:i.width,height:i.height})}catch(s){F.warn(`screen applyConstraints failed: ${s}`)}i.captureElement&&(yield K_(o,i.captureElement))}if(i.audio){let s=eT(i);F.info(`getUserMedia with constraints: ${JSON.stringify(s)}`),t=yield navigator.mediaDevices.getUserMedia(s),r.addTrack(t.getAudioTracks()[0])}return r})};function K_(i,t){return A(this,null,function*(){var e;if("CropTarget"in window&&"fromElement"in CropTarget&&He(i.cropTo))try{if(!(((e=i.getCaptureHandle())==null?void 0:e.handle)===_f))return;let o=yield CropTarget.fromElement(t);yield i.cropTo(o)}catch(r){F.warn(`cropTo target failed ${r}`)}})}function eT(i){let t={echoCancellation:i.echoCancellation,autoGainControl:i.autoGainControl,noiseSuppression:i.noiseSuppression,sampleRate:i.sampleRate,channelCount:i.channelCount};return V(i.microphoneId)||(t.deviceId=i.microphoneId),{audio:t,video:!1}}function tT(i){let t={preferCurrentTab:i.preferDisplaySurface==="current-tab"||!!i.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},e={width:At?{max:i.width}:{ideal:i.width,max:i.width},height:At?{max:i.height}:{ideal:i.height,max:i.height},frameRate:i.frameRate,displaySurface:i.preferDisplaySurface||"monitor"};if(t.video=e,i.systemAudio){let{echoCancellation:r=!0,noiseSuppression:o=!1,autoGainControl:s=!1}=i;t.audio={echoCancellation:r,noiseSuppression:o,autoGainControl:s,sampleRate:48e3}}return t}var Tf=Z_;var Yi=class extends br{constructor(e){super(e,2);u(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600});u(this,"objectFit","contain");u(this,"isScreen",!0);this._log.id=`s-${this._log.id}`}capture(g){return A(this,arguments,function*({systemAudio:e=!1,autoGainControl:r,echoCancellation:o,noiseSuppression:s,audioTrack:n,videoTrack:d,captureElement:m,preferDisplaySurface:l}){try{let _;return d||n?(_=new MediaStream,d&&_.addTrack(d),n&&_.addTrack(n)):_=yield Tf({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:r,echoCancellation:o,noiseSuppression:s,captureElement:m,preferDisplaySurface:l}),yield this.setInputMediaStreamTrack(_.getVideoTracks()[0]),_}catch(_){throw this.log.error(`getDisplayMedia error observed ${_}`),_ instanceof ae?_:new ae({code:q.INITIALIZE_FAILED,name:_.name,message:_.message})}})}switchDevice(e){return A(this,null,function*(){throw new Error("Method not implemented.")})}};J([Qi(function(e){this.setContentHint(e.contentHint||"detail")})],Yi.prototype,"capture",1);var jo=class extends hi{constructor(t){super(t),this._log.id=`s-${this._log.id}`}};var rT='registerProcessor("dumper",class extends AudioWorkletProcessor{constructor(e){super(),this.sourceSampleRate=e.processorOptions.sourceSampleRate||48e3,this.targetSampleRate=e.processorOptions.targetSampleRate||48e3,this.port.onmessage=e=>{this.port2=e.data.port}}process(e){return(this.port2||this.port).postMessage(this.resampleAll(e,this.sourceSampleRate,this.targetSampleRate)),!0}resampleAll(r,s,a){if(s===a)return r;var o=[];for(let t=0;t<r.length;t++){o[t]=[];for(let e=0;e<r[t].length;e++)o[t][e]=this.resample(r[t][e],s,a)}return o}resample(t,e,r){if(e===r)return t;var s=Math.round(t.length*(this.targetSampleRate/this.sourceSampleRate)),a=new Float32Array(s),o=(t.length-1)/(s-1);a[0]=t[0];for(let e=1;e<s-1;e++){var l=e*o,p=Math.floor(l),h=Math.ceil(l);a[e]=t[p]+(t[h]-t[p])*(l-p)}return a[s-1]=t[t.length-1],a}});',im;function fa(i,t=48e3,e){return A(this,null,function*(){let r=Ke("dump");im||(im=$o(r,URL.createObjectURL(new Blob([rT],{type:"application/javascript"})))),yield im;let o=r.sampleRate,s=new AudioWorkletNode(r,"dumper",{numberOfInputs:i.length,numberOfOutputs:0,processorOptions:{sourceSampleRate:o,targetSampleRate:t}});return e&&s.port.postMessage({port:e},[e]),i.forEach((n,d)=>n.connect(s,0,d)),new ReadableStream({start(n){s.port.onmessage=d=>{n.enqueue(d.data)}},cancel(){i.forEach(n=>n.disconnect(s)),s.port.close()}})})}var gd=class extends id{constructor(e){super();this.room=e;u(this,"_localAudioTrack");u(this,"_localScreenAudioTrack");u(this,"log",F.createLogger({id:"am"}));u(this,"denoiser");u(this,"voiceChanger");u(this,"mixChangedDebounce");u(this,"encodePipeline",[]);u(this,"decodePipeline",[]);u(this,"getPCMAbortCtrlMap",new Map);u(this,"audioFrameEventConfigMap",new Map);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.installEvent()}get _localAudioPipline(){var e;return(e=this._localAudioTrack)==null?void 0:e.pipeline}dump(e){var g,_;if(!this._localAudioTrack)return;let r=[],o=[];(g=this._localAudioPipline)!=null&&g.source.node&&(r.push(this._localAudioPipline.source.node),o.push("mic")),(_=this._localAudioPipline)!=null&&_.denoiser.node&&(r.push(this._localAudioPipline.denoiser.node),o.push("mic-processed")),this.mixWeight>1&&(r.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),o.push("mix")),this.log.info(`dump audio track ${o}, duration: ${e}`);let s=new AbortController,n=[],d=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),s.abort("timeout")},e*1e3),m=()=>{for(let S=0;S<o.length;S++){let v=URL.createObjectURL(new Blob(n[S])),x=document.createElement("a");x.href=v,x.download=`${o[S]}.pcm`,x.style.display="none",document.body.appendChild(x),x.click(),URL.revokeObjectURL(v),x.remove()}clearTimeout(d),s.abort("download")},l=fa(r).then(S=>S.pipeTo(new WritableStream({write(v){v.forEach((x,P)=>n[P]=n[P]?n[P].concat(x[0]):[x[0]])}}),s).catch(v=>m));return{then:l.then.bind(l),download:m}}getPCM(e,r){var G,se,ne;if(V(WritableStream)){this.log.warn("getPCM failed: browser not support WritableStream");return}let{enable:o,sampleRate:s=48e3,channelCount:n=1,port:d}=(r===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(r)||this.audioFrameEventConfigMap.get("*"))||{};if(!o)return;this.log.info(`getPCM ${r||"local"}`);let m=Math.floor(s*.04),l=new Float32Array(m),g=new Float32Array(m),_,S,v=0,x=new AbortController,P=r===""?(G=this._localAudioTrack)==null?void 0:G.mediaTrack:(ne=(se=this.room)==null?void 0:se.remotePublishedUserMap.get(r))==null?void 0:ne.remoteAudioTrack.mediaTrack;if(!P){this.log.info(`getPCM failed: ${r||"local"} has no audio track`);return}let M=Ke().createMediaStreamSource(new MediaStream([P]));return fa([M],s,d).then(Ae=>Ae.pipeTo(new WritableStream({write(ie){ie[0][0]&&(v+ie[0][0].length>m?(l.set(ie[0][0].subarray(0,m-v),v),_=ie[0][0].subarray(m-v),g.set(ie[0][1].subarray(0,m-v),v),S=ie[0][1].subarray(m-v),v+=m-v):(_&&(l.set(_,v),v+=_.length,_=void 0),S&&(g.set(S,v),S=void 0),l.set(ie[0][0],v),g.set(ie[0][1],v),v+=ie[0][0].length),v>=m&&(v=0,e({userId:r,sampleRate:s,channelCount:n,data:n===1?l:[l,g]}),l=new Float32Array(m),g=new Float32Array(m)))}}),x).catch(ie=>this.log.warn(`stop getPCM reason:${ie}`))),x}get hasScreenAudioTrack(){return this._localScreenAudioTrack!==null}get hasAudioTrack(){return!V(this._localAudioTrack)}changeInput(e){if(e instanceof jo)return this._localScreenAudioTrack=e,e.pipeline.connect(),this.mixOnChange();if(e instanceof hi)return this._localAudioTrack=e,this.denoiser&&e.addDenoiser(this.denoiser),e.pipeline.connect(),this.mixOnChange();if(e instanceof qo)return e.setOutputMediaStreamTrack(e.mediaTrack)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var e,r;return delete this.mixChangedDebounce,Promise.all([(e=this._localAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(r=this._localScreenAudioTrack)==null?void 0:r.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(e){e instanceof jo?delete this._localScreenAudioTrack:e instanceof hi?delete this._localAudioTrack:e instanceof qo}addDenoiser(e){var r;this.denoiser=e,(r=this._localAudioTrack)==null||r.addDenoiser(e)}removeDenoiser(e){var r;delete this.denoiser,(r=this._localAudioTrack)==null||r.removeDenoiser(e)}addVoiceChanger(e,r){var o;this.voiceChanger=[e,r],(o=this._localAudioTrack)==null||o.pipeline.voiceChanger.setNode(e,r)}removeVoiceChanger(){var e;delete this.voiceChanger,(e=this._localAudioTrack)==null||e.pipeline.voiceChanger.deleteNode()}destroy(){this.close(),this.getPCMAbortCtrlMap.forEach(e=>e==null?void 0:e.abort("destroy")),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}addEncodeProcessor({processor:e,type:r}){var o;this.encodePipeline.includes(e)||(this.encodePipeline[r]=e,(o=this.room)==null||o.enableInsertableStreams())}addDecodeProcessor({processor:e,type:r}){var o;this.decodePipeline.includes(e)||(this.decodePipeline[r]=e,(o=this.room)==null||o.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}handleLocalTrackStarted({room:e,userId:r}){var s;if(e!==this.room||this.getPCMAbortCtrlMap.get(r))return;let o=this.getPCM(n=>{var d;(d=this.room)==null||d.emit("audio-frame",n)},"");this.getPCMAbortCtrlMap.set(r,o),this.getPCMAbortCtrlMap.get(r)&&((s=this._localAudioTrack)==null||s.on("input-media-track-changed",()=>{let n=this.getPCMAbortCtrlMap.get(r);n&&(n.abort("inputMediaTrackChanged"),n=this.getPCM(d=>{var m;(m=this.room)==null||m.emit("audio-frame",d)},""),this.getPCMAbortCtrlMap.set(r,n))}))}handleLocalTrackStopped({room:e,userId:r}){if(e!==this.room)return;let o=this.getPCMAbortCtrlMap.get(r);o&&(o.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(r))}handleRemoteTrackStarted({room:e,userId:r}){if(e===this.room&&!this.getPCMAbortCtrlMap.get(r)){let o=this.room.audioManager.getPCM(s=>{var n;(n=this.room)==null||n.emit("audio-frame",s)},r);this.getPCMAbortCtrlMap.set(r,o)}}handleRemoteTrackStopped({room:e,userId:r}){if(e!==this.room)return;let o=this.getPCMAbortCtrlMap.get(r);o&&(o.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(r))}installEvent(){L.on("113",this.handleLocalTrackStarted,this),L.on("114",this.handleLocalTrackStopped,this),L.on("115",this.handleRemoteTrackStarted,this),L.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){L.off("113",this.handleLocalTrackStarted),L.off("114",this.handleLocalTrackStopped),L.off("115",this.handleRemoteTrackStarted),L.off("116",this.handleRemoteTrackStopped)}};function If(i=30,t=2){return Me((e,r)=>function(...o){return new Promise((s,n)=>{let d=setTimeout(()=>{let m=new ae({code:q.API_CALL_TIMEOUT,message:`checkPendingPromise ${r}() timeout ${i}s`});F.warn(m),t===2?n(m):t===1&&s()},i*1e3);e.apply(this,o).then(s,n).finally(()=>{clearTimeout(d)})})})}var Hm={};Yr(Hm,{Events:()=>at,Inspect:()=>cr,LastSink:()=>zo,Sink:()=>me,Subscribe:()=>Jo,TimeoutError:()=>ga,audit:()=>UT,bindCallback:()=>yT,bindNodeCallback:()=>AT,buffer:()=>lT,bufferCount:()=>uT,bufferTime:()=>rI,call:()=>Sf,catchError:()=>Vm,combineLatest:()=>Af,concat:()=>sT,concatMap:()=>JT,concatMapTo:()=>XT,count:()=>vT,create:()=>Oe,debounce:()=>VT,debounceTime:()=>FT,defer:()=>bf,delay:()=>iI,deliver:()=>ge,dispose:()=>Ed,elementAt:()=>$T,empty:()=>Ta,every:()=>jT,exhaustMap:()=>ZT,exhaustMapTo:()=>KT,filter:()=>or,find:()=>BT,findIndex:()=>HT,first:()=>WT,fromAnimationFrame:()=>IT,fromArray:()=>hT,fromEvent:()=>Ce,fromEventPattern:()=>fT,fromFetch:()=>gT,fromIterable:()=>ET,fromPromise:()=>Cf,fromReadableStream:()=>TT,fromReader:()=>_T,groupBy:()=>eI,identity:()=>iT,ignoreElements:()=>wT,iif:()=>aT,inspect:()=>yf,interval:()=>um,last:()=>GT,map:()=>Ki,mapTo:()=>zT,max:()=>CT,merge:()=>cm,mergeMap:()=>QT,mergeMapTo:()=>YT,min:()=>DT,never:()=>bT,nothing:()=>Be,of:()=>pT,pairwise:()=>qT,pipe:()=>ye,race:()=>dm,range:()=>ST,reduce:()=>lm,retry:()=>nI,scan:()=>Um,share:()=>fi,shareReplay:()=>nT,skip:()=>OT,skipUntil:()=>PT,skipWhile:()=>yd,startWith:()=>Ea,subject:()=>It,subscribe:()=>ke,sum:()=>NT,switchMap:()=>eo,switchMapTo:()=>gi,take:()=>Rr,takeLast:()=>MT,takeUntil:()=>Xe,takeWhile:()=>Df,tap:()=>Ia,throttle:()=>kT,throwError:()=>RT,timeInterval:()=>tI,timeout:()=>Bm,timer:()=>_a,toPromise:()=>oI,toReadableStream:()=>sI,withLatestFrom:()=>dT,zip:()=>cT});function Be(...i){}var Sf=i=>i(),iT=i=>i;function Ed(){this.dispose()}var yf=()=>typeof __FASTRX_DEVTOOLS__!="undefined",oT=1,cr=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(t){let e=new om(t,this,this.streamId++);return at.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},zo=class{constructor(){this.defers=new Set,this.disposed=!1}next(t){}complete(){this.dispose()}error(t){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=Be,this.error=Be,this.next=Be,this.dispose=Be,this.subscribe=Be,this.doDefer()}subscribe(t){return t instanceof cr?t.subscribe(this):t(this),this}get bindSubscribe(){return t=>this.subscribe(t)}doDefer(){this.defers.forEach(Sf),this.defers.clear()}defer(t){this.defers.add(t)}removeDefer(t){this.defers.delete(t)}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}},me=class extends zo{constructor(t){super(),this.sink=t,t.defer(this.bindDispose)}next(t){this.sink.next(t)}complete(){this.sink.complete()}error(t){this.sink.error(t)}},Jo=class extends zo{constructor(t,e=Be,r=Be,o=Be){if(super(),this._next=e,this._error=r,this._complete=o,this.then=Be,t instanceof cr){let s={toString:()=>"subscribe",id:0,source:t};this.defer(()=>{at.defer(s,0)}),at.create(s),at.pipe(s),this.sourceId=s.id,this.subscribe(t),at.subscribe({id:s.id,end:!0}),e==Be?this._next=n=>at.next(s,0,n):this.next=n=>{at.next(s,0,n),e(n)},o==Be?this._complete=()=>at.complete(s,0):this.complete=()=>{this.dispose(),at.complete(s,0),o()},r==Be?this._error=n=>at.complete(s,0,n):this.error=n=>{this.dispose(),at.complete(s,0,n),r()}}else this.subscribe(t)}next(t){this._next(t)}complete(){this.dispose(),this._complete()}error(t){this.dispose(),this._error(t)}};function ye(i,...t){return t.reduce((e,r)=>r(e),i)}function Oe(i,t,e){if(yf()){let r=Object.defineProperties(Object.setPrototypeOf(i,cr.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:t,writable:!0,configurable:!0},args:{value:e,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});at.create(r);for(let o=0;o<e.length;o++){let s=e[o];typeof s=="function"&&s instanceof cr&&at.addSource(r,s)}return r}return i}function ge(i,t){return function(...e){return r=>{if(r instanceof cr){let o=Oe(s=>{let n=new i(s,...e);n.sourceId=o.id,n.subscribe(r)},t,arguments);return o.source=r,at.pipe(o),o}else return o=>r(new i(o,...e))}}}function Zi(i,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:i,payload:t}})}var om=class extends me{constructor(t,e,r){super(t),this.source=e,this.id=r,this.sourceId=t.sourceId,this.defer(()=>{at.defer(this.source,this.id)})}next(t){at.next(this.source,this.id,t),this.sink.next(t)}complete(){at.complete(this.source,this.id),this.sink.complete()}error(t){at.complete(this.source,this.id,t),this.sink.error(t)}},at={addSource(i,t){Zi("addSource",{id:i.id,name:i.toString(),source:{id:t.id,name:t.toString()}})},next(i,t,e){Zi("next",{id:i.id,streamId:t,data:e&&e.toString()})},subscribe({id:i,end:t},e){Zi("subscribe",{id:i,end:t,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(i,t,e){Zi("complete",{id:i.id,streamId:t,err:e?e.toString():null})},defer(i,t){Zi("defer",{id:i.id,streamId:t})},pipe(i){Zi("pipe",{name:i.toString(),id:i.id,source:{id:i.source.id,name:i.source.toString()}})},update(i){Zi("update",{id:i.id,name:i.toString()})},create(i){i.id||(i.id=oT++),Zi("create",{name:i.toString(),id:i.id})}},ga=class extends Error{constructor(t){super(`timeout after ${t}ms`),this.timeout=t}};var _d=class extends zo{constructor(t){super(),this.source=t,this.sinks=new Set}add(t){t.defer(()=>this.remove(t)),this.sinks.add(t).size===1&&(this.reset(),this.subscribe(this.source))}remove(t){this.sinks.delete(t),this.sinks.size===0&&this.dispose()}next(t){this.sinks.forEach(e=>e.next(t))}complete(){this.sinks.forEach(t=>t.complete()),this.sinks.clear()}error(t){this.sinks.forEach(e=>e.error(t)),this.sinks.clear()}};function fi(){return i=>{let t=new _d(i);if(i instanceof cr){let e=Oe(r=>{t.add(r)},"share",arguments);return t.sourceId=e.id,e.source=i,at.pipe(e),e}return Oe(t.add.bind(t),"share",arguments)}}function cm(...i){return Oe(t=>{let e=new me(t),r=i.length;e.complete=()=>{--r===0&&t.complete()},i.forEach(e.bindSubscribe)},"merge",arguments)}function dm(...i){return Oe(t=>{let e=new Map;i.forEach(r=>{let o=new me(t);e.set(r,o),o.complete=()=>{e.delete(r),e.size===0?t.complete():o.dispose()},o.next=s=>{e.delete(r),e.forEach(n=>n.dispose()),o.resetNext(),o.resetComplete(),o.next(s)}}),i.forEach(r=>e.get(r).subscribe(r))},"race",arguments)}function sT(...i){return Oe(t=>{let e=0,r=i.length,o=new me(t);o.complete=()=>{e<r&&!o.disposed?(o.doDefer(),o.subscribe(i[e++])):t.complete()},o.complete()},"concat",arguments)}function nT(i){return t=>{let e=new _d(t),r=[];return e.next=function(o){r.push(o),r.length>i&&r.shift(),this.sinks.forEach(s=>s.next(o))},Oe(o=>{o.defer(()=>e.remove(o)),r.forEach(s=>o.next(s)),e.add(o)},"shareReplay",arguments)}}function aT(i,t,e){return Oe(r=>i()?t(r):e(r),"iif",arguments)}function Af(...i){return Oe(t=>{let e=i.length,r=e,o=e,s=new Array(e),n=()=>{--o===0&&t.complete()},d=(m,l)=>{let g=new me(t);g.next=_=>{--r===0?(g.next=S=>{s[l]=S,t.next(s)},g.next(_)):s[l]=_},g.complete=n,g.subscribe(m)};i.forEach(d)},"combineLatest",arguments)}function cT(...i){return Oe(t=>{let e=i.length,r=e,o=new Array(e),s=()=>{--r===0&&t.complete()},n=(d,m)=>{let l=new me(t),g=[];o[m]=g,l.next=_=>{g.push(_),o.every(S=>S.length)&&t.next(o.map(S=>S.shift()))},l.complete=s,l.subscribe(d)};i.forEach(n)},"zip",arguments)}function Ea(...i){return t=>Oe((e,r=0,o=i.length)=>{for(;r<o&&!e.disposed;)e.next(i[r++]);e.disposed||e.subscribe(t)},"startWith",arguments)}var sm=class extends me{constructor(t,...e){super(t);let r=new me(this.sink);r.next=o=>this.buffer=o,r.complete=Be,r.subscribe(Af(...e))}next(t){this.buffer&&this.sink.next([t,...this.buffer])}},dT=ge(sm,"withLatestFrom"),nm=class extends me{constructor(t,e,r){super(t),this.bufferSize=e,this.startBufferEvery=r,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(t){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(t)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(t),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(t=>this.sink.next(t)),super.complete()}},uT=ge(nm,"bufferCount"),am=class extends me{constructor(t,e){super(t),this.buffer=[];let r=new me(t);r.next=o=>{t.next(this.buffer),this.buffer=[]},r.complete=Be,r.subscribe(e)}next(t){this.buffer.push(t)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},lT=ge(am,"buffer");var mT=function(i,t,e,r){function o(s){return s instanceof e?s:new e(function(n){n(s)})}return new(e||(e=Promise))(function(s,n){function d(g){try{l(r.next(g))}catch(_){n(_)}}function m(g){try{l(r.throw(g))}catch(_){n(_)}}function l(g){g.done?s(g.value):o(g.value).then(d,m)}l((r=r.apply(i,t||[])).next())})};function It(i){let t=arguments,e=fi()(Oe(r=>{e.next=o=>r.next(o),e.complete=()=>r.complete(),e.error=o=>r.error(o),i&&r.subscribe(i)},"subject",t));return e.next=Be,e.complete=Be,e.error=Be,e}function bf(i){return Oe(t=>t.subscribe(i()),"defer",arguments)}var Rf=i=>t=>{setTimeout(()=>i(t))},vf=i=>Rf(t=>{for(let e=0;!t.disposed&&e<i.length;e++)t.next(i[e]);t.complete()});function pT(...i){return Oe(vf(i),"of",arguments)}function hT(i){return Oe(vf(i),"fromArray",arguments)}function um(i){return Oe(t=>{let e=0,r=setInterval(()=>t.next(e++),i);return t.defer(()=>{clearInterval(r)}),"interval"},"interval",arguments)}function _a(i,t){return Oe(e=>{let r=0,o=setTimeout(()=>{if(e.removeDefer(s),e.next(r++),t){let n=setInterval(()=>e.next(r++),t);e.defer(()=>{clearInterval(n)})}else e.complete()},i),s=()=>{clearTimeout(o)};e.defer(s)},"timer",arguments)}function Td(i,t){return e=>{let r=o=>e.next(o);e.defer(()=>t(r)),i(r)}}function fT(i,t){return Oe(Td(i,t),"fromEventPattern",arguments)}function Ce(i,t){if("on"in i&&"off"in i)return Oe(Td(e=>i.on(t,e),e=>i.off(t,e)),"fromEvent",arguments);if("addListener"in i&&"removeListener"in i)return Oe(Td(e=>i.addListener(t,e),e=>i.removeListener(t,e)),"fromEvent",arguments);if("addEventListener"in i)return Oe(Td(e=>i.addEventListener(t,e),e=>i.removeEventListener(t,e)),"fromEvent",arguments);throw"target is not a EventDispachter"}function Cf(i){return Oe(t=>{i.then(t.next.bind(t),t.error.bind(t))},"fromPromise",arguments)}function gT(i,t){return Oe(bf(()=>Cf(fetch(i,t))),"fromFetch",arguments)}function ET(i){return Oe(Rf(t=>{try{for(let e of i){if(t.disposed)return;t.next(e)}t.complete()}catch(e){t.error(e)}}),"fromIterable",arguments)}function _T(i){let t=e=>mT(this,void 0,void 0,function*(){if(e.disposed)return;let{done:r,value:o}=yield i.read();if(r){e.complete();return}else e.next(o),t(e)});return Oe(e=>{t(e)},"fromReader",arguments)}function TT(i){return Oe(t=>{let e=new AbortController,r=e.signal;t.defer(()=>e.abort("cancelled")),i.pipeTo(new WritableStream({write(o){t.next(o)},close(){t.complete()},abort(o){t.error(o)}}),{signal:r}).then(()=>t.complete(),o=>t.error(o))},"fromReadableStream",arguments)}function IT(){return Oe(i=>{let t=requestAnimationFrame(function e(r){i.disposed||(i.next(r),t=requestAnimationFrame(e))});i.defer(()=>cancelAnimationFrame(t))},"fromAnimationFrame",arguments)}function ST(i,t){return Oe((e,r=i,o=t+i)=>{for(;r<o&&!e.disposed;)e.next(r++);return e.complete(),"range"},"range",arguments)}function yT(i,t,...e){return Oe(r=>{let o=e.concat(s=>(r.next(s),r.complete()));i.apply(t,o)},"bindCallback",arguments)}function AT(i,t,...e){return Oe(r=>{let o=e.concat((s,n)=>s?r.error(s):(r.next(n),r.complete()));i.apply(t,o)},"bindNodeCallback",arguments)}function bT(){return Oe(()=>{},"never",arguments)}function RT(i){return Oe(t=>t.error(i),"throwError",arguments)}function Ta(){return Oe(i=>i.complete(),"empty",arguments)}var Xo=class extends me{constructor(t,e,r){super(t),this.f=e;let o=()=>{this.sink.next(this.acc),this.sink.complete()};typeof r=="undefined"?this.next=s=>{this.acc=s,this.complete=o,this.resetNext()}:(this.acc=r,this.complete=o)}next(t){this.acc=this.f(this.acc,t)}},lm=ge(Xo,"reduce"),vT=i=>ge(Xo,"count")((t,e)=>i(e)?t+1:t,0),CT=()=>ge(Xo,"max")(Math.max),DT=()=>ge(Xo,"min")(Math.min),NT=()=>ge(Xo,"sum")((i,t)=>i+t,0);var mm=class extends me{constructor(t,e,r){super(t),this.filter=e,this.thisArg=r}next(t){this.filter.call(this.thisArg,t)&&this.sink.next(t)}},or=ge(mm,"filter"),pm=class extends me{next(t){}},wT=ge(pm,"ignoreElements"),hm=class extends me{constructor(t,e){super(t),this.count=e}next(t){this.sink.next(t),--this.count===0&&this.complete()}},Rr=ge(hm,"take"),fm=class extends me{constructor(t,e){super(t);let r=new me(t);r.next=()=>t.complete(),r.complete=Ed,r.subscribe(e)}},Xe=ge(fm,"takeUntil"),gm=class extends me{constructor(t,e){super(t),this.f=e}next(t){this.f(t)?this.sink.next(t):this.complete()}},Df=ge(gm,"takeWhile"),MT=i=>lm((t,e)=>(t.push(e),t.length>i&&t.shift(),t),[]),Em=class extends me{constructor(t,e){super(t),this.count=e}next(t){--this.count===0&&(this.next=super.next)}},OT=ge(Em,"skip"),_m=class extends me{constructor(t,e){super(t),t.next=Be;let r=new me(t);r.next=()=>{r.dispose(),t.resetNext()},r.complete=Ed,r.subscribe(e)}},PT=ge(_m,"skipUntil"),Tm=class extends me{constructor(t,e){super(t),this.f=e}next(t){this.f(t)||(this.next=super.next,this.next(t))}},yd=ge(Tm,"skipWhile"),xT={leading:!0,trailing:!1},Im=class extends me{constructor(t,e,r){super(t),this.durationSelector=e,this.trailing=r}cacheValue(t){this.last=t,this.disposed&&this.throttle(t)}send(t){this.sink.next(t),this.throttle(t)}throttle(t){this.reset(),this.subscribe(this.durationSelector(t))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},Id=class extends me{constructor(t,e,r=xT){super(t),this.durationSelector=e,this.config=r,this._throttle=new Im(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(t){this._throttle.disposed&&this.config.leading?this._throttle.send(t):this._throttle.cacheValue(t)}complete(){this._throttle.throttle=Be,this._throttle.complete(),super.complete()}},kT=ge(Id,"throttle"),LT={leading:!1,trailing:!0},UT=i=>ge(Id,"audit")(i,LT),Sm=class extends me{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},Sd=class extends me{constructor(t,e){super(t),this.durationSelector=e,this._debounce=new Sm(this.sink),this._debounce.dispose()}next(t){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=t,this._debounce.subscribe(this.durationSelector(t))}complete(){this._debounce.complete(),super.complete()}},VT=ge(Sd,"debounce"),FT=i=>ge(Sd,"debounceTime")(t=>_a(i)),ym=class extends me{constructor(t,e,r){super(t),this.count=e,this.defaultValue=r}next(t){this.count--===0&&(this.defaultValue=t,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()}},$T=ge(ym,"elementAt"),BT=i=>t=>Rr(1)(yd(e=>!i(e))(t)),Am=class extends me{constructor(t,e){super(t),this.f=e,this.i=0}next(t){this.f(t)?(this.sink.next(this.i++),this.complete()):++this.i}},HT=ge(Am,"findIndex"),bm=class extends me{constructor(t,e,r){super(t),this.f=e,this.defaultValue=r,this.index=0}next(t){(!this.f||this.f(t,this.index++))&&(this.defaultValue=t,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()}},WT=ge(bm,"first"),Rm=class extends me{constructor(t,e,r){super(t),this.f=e,this.defaultValue=r,this.index=0}next(t){(!this.f||this.f(t,this.index++))&&(this.defaultValue=t)}complete(){if(this.defaultValue===void 0){this.error(new Error("no elements in sequence"));return}else this.sink.next(this.defaultValue);super.complete()}},GT=ge(Rm,"last"),vm=class extends me{constructor(t,e){super(t),this.predicate=e,this.index=0}next(t){this.predicate(t,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()}},jT=ge(vm,"every");var Cm=class extends me{constructor(t,e,r){super(t),this.f=e,typeof r=="undefined"?this.next=o=>{this.acc=o,this.resetNext(),this.sink.next(this.acc)}:this.acc=r}next(t){this.sink.next(this.acc=this.f(this.acc,t))}},Um=ge(Cm,"scan"),Dm=class extends me{constructor(){super(...arguments),this.hasLast=!1}next(t){this.hasLast?this.sink.next([this.last,t]):this.hasLast=!0,this.last=t}},qT=ge(Dm,"pairwise"),Ad=class extends me{constructor(t,e,r){super(t),this.mapper=e,this.thisArg=r}next(t){super.next(this.mapper.call(this.thisArg,t))}},Ki=ge(Ad,"map"),zT=i=>ge(Ad,"mapTo")(t=>i),js=class extends me{constructor(t,e,r){super(t),this.data=e,this.context=r}next(t){let e=this.context.combineResults;e?this.sink.next(e(this.data,t)):this.sink.next(t)}tryComplete(){this.context.resetComplete(),this.dispose()}},qs=class extends me{constructor(t,e,r){super(t),this.makeSource=e,this.combineResults=r,this.index=0}subInner(t,e){let r=this.currentSink=new e(this.sink,t,this);this.complete=this.tryComplete,r.complete=r.tryComplete,r.subscribe(this.makeSource(t,this.index++))}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},bd=class extends js{},Rd=class extends qs{next(t){this.subInner(t,bd),this.next=e=>{this.currentSink.dispose(),this.subInner(e,bd)}}},eo=ge(Rd,"switchMap");function Nd(i){return(t,e)=>i(()=>t,e)}var gi=Nd(ge(Rd,"switchMapTo")),Nm=class extends js{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},vd=class extends qs{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(t){this.next2(t),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),Nm),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},JT=ge(vd,"concatMap"),XT=Nd(ge(vd,"concatMapTo")),wm=class extends js{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Cd=class extends qs{constructor(){super(...arguments),this.inners=new Set}next(t){this.subInner(t,wm),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(t=>t.resetComplete()):this.dispose()}},QT=ge(Cd,"mergeMap"),YT=Nd(ge(Cd,"mergeMapTo")),Mm=class extends js{dispose(){this.context.resetNext(),super.dispose()}},Dd=class extends qs{next(t){this.next=Be,this.subInner(t,Mm)}},ZT=ge(Dd,"exhaustMap"),KT=Nd(ge(Dd,"exhaustMapTo")),Om=class extends me{constructor(t,e){super(t),this.f=e,this.groups=new Map}next(t){let e=this.f(t),r=this.groups.get(e);typeof r=="undefined"&&(r=It(),r.key=e,this.groups.set(e,r),super.next(r)),r.next(t)}complete(){this.groups.forEach(t=>t.complete()),super.complete()}error(t){this.groups.forEach(e=>e.error(t)),super.error(t)}},eI=ge(Om,"groupBy"),Pm=class extends me{constructor(){super(...arguments),this.start=new Date}next(t){this.sink.next({value:t,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},tI=ge(Pm,"timeInterval"),xm=class extends me{constructor(t,e){super(t),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(t){this.buffer.push(t)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},rI=ge(xm,"bufferTime"),km=class extends me{constructor(t,e){super(t),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(t){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:r,data:o}=e;super.next(o),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(r))}},t)}next(t){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:t})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},iI=ge(km,"delay"),Lm=class extends me{constructor(t,e){super(t),this.selector=e}error(t){this.dispose(),this.selector(t)(this.sink)}},Vm=ge(Lm,"catchError");var oI=()=>i=>new Promise((t,e)=>{let r;new Jo(i,o=>r=o,e,()=>t(r))}),sI=()=>i=>{let t;return new ReadableStream({start(e){t=new Jo(i,e.enqueue.bind(e),e.error.bind(e),e.close.bind(e))},cancel(){t.dispose()}})},ke=(i=Be,t=Be,e=Be)=>r=>new Jo(r,i,t,e),Fm=class extends me{constructor(t,e){super(t),e instanceof Function?this.next=r=>{e(r),t.next(r)}:(e.next&&(this.next=r=>{e.next(r),t.next(r)}),e.complete&&(this.complete=()=>{e.complete(),t.complete()}),e.error&&(this.error=r=>{e.error(r),t.error(r)}))}},Ia=ge(Fm,"tap"),$m=class extends me{constructor(t,e){super(t),this.timeout=e,this.id=setTimeout(()=>this.error(new ga(this.timeout)),this.timeout)}next(t){super.next(t),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},Bm=ge($m,"timeout"),nI=(i=1/0)=>t=>{if(t instanceof cr){let e=Oe(r=>{let o=i,s=new me(r);s.error=n=>{o-- >0?s.subscribe(t):r.error(n)},s.sourceId=e.id,s.subscribe(t)},"retry",[i]);return e.source=t,at.pipe(e),e}else return e=>{let r=i,o=new me(e);o.error=s=>{r-- >0?t(o):e.error(s)},t(o)}};var Gr=class Gr extends Bo{constructor(e,r,o){super({userId:r.userId,sdkAppId:e.sdkAppId,mediaType:o,room:e});this.room=e;this.user=r;u(this,"tinyId");u(this,"isRemote",!0);u(this,"jitterBufferDelay",0);u(this,"availableState");u(this,"remotePublishState");u(this,"_triggerCheckDecodeSubject",It(Ce(this,Gr.STATE_SUBSCRIBE)));this.tinyId=r.tinyId,this.availableState=new oe(`${r.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new oe(`${r.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),ye(cm(Ce(this,oe.STATECHANGED),Ce(this.remotePublishState,oe.STATECHANGED)),Ki(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),ke(m=>{this.availableState.state!==(m?oe.ON:oe.OFF)&&(this.availableState.state=m?oe.ON:oe.OFF),this.updatePlayingState(m)}));let s=ye(Ce(this.player,Ze.ERROR),or(m=>m.code===MediaError.MEDIA_ERR_DECODE)),n=ye(_a(5e3),or(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived?!1:this.player.isPlaying||(this.kind===N.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)?(this.reportDecodeResult(!0),!1):!0)),d=ye(dm(s,n),Xe(Ce(this,oe.INIT)));ye(this._triggerCheckDecodeSubject,or(()=>!this.ignoreDecodeError),gi(d),ke(m=>{this.reportDecodeResult(!1,m)}))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get ignoreDecodeError(){var r,o;return(((o=(r=this.room)==null?void 0:r.networkQuality)==null?void 0:o.downlinkNetworkQuality)||0)>3||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===Gr.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===oe.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.player.setTrack(null),this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(e,r){let o=this.kind===N.AUDIO;X[e?"addSuccessEvent":"addFailedEvent"]({key:o?504700:514702}),e||(X.addEnum({key:o?504701:514703,value:jn()}),je.uploadEvent({log:`stat-decode-failed-${this.kind}-${Gn()||Po()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===N.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:r}))}updatePlayingState(e){if(this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack)){this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isRemotePublished} hasTrack: ${!!this.outMediaTrack} `);return}super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?oe.ON:oe.OFF}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};u(Gr,"STATE_SUBSCRIBE","subscribe"),J([If(5,1)],Gr.prototype,"waitHasMediaTrack",1),J([Je(oe.INIT,Gr.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),L.emit(U.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),hd(521716,!1)],Gr.prototype,"subscribe",1),J([Je(Gr.STATE_SUBSCRIBE,oe.INIT,{sync:!0,success(){this.log.info("unsubscribed"),L.emit(U.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],Gr.prototype,"unsubscribe",1);var zs=Gr;var qo=class extends zs{constructor(e,r){super(e,r,1);u(this,"volume",0);u(this,"mediaType",1);u(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.audioManager}get dbVolume(){return nd.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 r=e;for(let o of this.manager.decodePipeline)if(o&&(r=o({frame:r,track:this}),!r))return;return r}getAudioLevel(){let e=this.volume||super.getAudioLevel();return e>1?1:e}get isRemotePublished(){return this.user.muteState.audioAvailable}};var cI=[-1,-1,1,-1,-1,1,1,1],dI=[0,0,1,0,0,1,1,1];var Gt=class extends oe{constructor(e,r){super();this.context=e;u(this,"name");u(this,"input");u(this,"output");u(this,"texture");u(this,"ctx2d",null);u(this,"fbo");u(this,"width",0);u(this,"height",0);u(this,"x",0);u(this,"y",0);u(this,"program");u(this,"vertexShader");u(this,"fragmentShader");u(this,"totalFrames",0);u(this,"dropFrames",0);u(this,"matchInputSize",!0);u(this,"texCoordBuffer");u(this,"positionBuffer");u(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0});u(this,"cost",0);u(this,"_canvas",null);u(this,"_image");u(this,"log");if(this.context.on("disconnect",this.close,this),this.name=r.name,this.log=r.logger,this.matchInputSize=r.matchInputSize!==!1,this.width=r.width||e.width,this.height=r.height||e.height,this._image=r.image,e instanceof Vt){e.ctx&&r.create2d&&(typeof OffscreenCanvas=="function"&&er!==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 o=e.ctx;this.texCoordBuffer=this.createBuffer(dI),this.positionBuffer=this.createBuffer(cI),r.createTexture!==!1&&(this.texture=o.createTexture(),this.useTexture(),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.pixelStorei(o.PACK_ALIGNMENT,1),o.pixelStorei(o.UNPACK_ALIGNMENT,1)),r.useFbo&&(this.fbo=o.createFramebuffer(),this.useBufferFrame(),this.useTexture(),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,this.width,this.height,0,o.RGBA,o.UNSIGNED_BYTE,null),o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,this.texture,0)),r.useDefaultProgram?this.program=e.defaultProgam:(r.vertexShaderSource||r.fragmentShaderSource)&&(this.vertexShader=r.vertexShaderSource?e.createShader(o.VERTEX_SHADER,r.vertexShaderSource):e.defaultVShader,this.fragmentShader=r.fragmentShaderSource?e.createShader(o.FRAGMENT_SHADER,r.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(o){this.context.destroy(new ae({code:q.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${o.message||o}`}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let r=this.context.ctx,o=r.createFramebuffer();return r.bindFramebuffer(r.FRAMEBUFFER,o),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e,0),o}connect(e,...r){return e.addInput(this,...r),this.output=e,e}addInput(e,...r){this.input=e,this.matchInputSize&&e.width&&e.height&&this.resize(e.width,e.height)}requestFrame(e){let r=Date.now();if(this.context instanceof Et&&this.render(e)||this.context instanceof Vt&&this.render2d(e))this.totalFrames++;else return!1;return this.cost=Date.now()-r,!0}render2d(e){var r;return(r=this.input)!=null&&r.requestFrame(e)?this.draw2d(this.input.image,0,0,this.width,this.height):!1}update(e=0){var r;(r=this.output)==null||r.update(e)}disconnect(...e){var r;(r=this.output)==null||r.removeInput(this,...e),delete this.output}removeInput(e,...r){delete this.input}close(){var e,r;if(this.context.off("disconnect",this.close,this),(e=this.output)==null||e.removeInput(this),delete this.output,(r=this.input)==null||r.disconnect(),this.context instanceof Et){let o=this.context.ctx;o.deleteBuffer(this.texCoordBuffer),o.deleteBuffer(this.positionBuffer),this.fbo&&o.deleteFramebuffer(this.fbo),this.texture&&o.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&o.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&o.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&o.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 r=this.context.ctx;e.forEach((o,s)=>{o&&(r.activeTexture(r.TEXTURE0+s),r.bindTexture(r.TEXTURE_2D,o))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let r=this.context.ctx,o=r.createBuffer();return r.bindBuffer(r.ARRAY_BUFFER,o),r.bufferData(r.ARRAY_BUFFER,new Float32Array(e),r.STATIC_DRAW),o}setTexBuffer(e){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,this.texCoordBuffer),r.bufferData(r.ARRAY_BUFFER,new Float32Array(e),r.STATIC_DRAW)}setPosBuffer(e){let r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,this.positionBuffer),r.bufferData(r.ARRAY_BUFFER,new Float32Array(e),r.STATIC_DRAW)}changeBufferData(e,r){let o=this.context.ctx;o.bindBuffer(o.ARRAY_BUFFER,e),o.bufferData(o.ARRAY_BUFFER,new Float32Array(r),o.STATIC_DRAW)}setAttributes(...e){let r=this.context.ctx;e.forEach((o,s)=>{r.enableVertexAttribArray(s),r.bindBuffer(r.ARRAY_BUFFER,o),r.vertexAttribPointer(s,2,r.FLOAT,!1,0,0)})}getVertexPoint(e,r){return[e/this.width*2-1,r/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,r){if(!(this.width===e&&this.height===r)){if(this.width=e,this.height=r,this._canvas&&(this._canvas.width=e,this._canvas.height=r),this.texture&&this.fbo){this.useTexture();let o=this.context.ctx;o.texImage2D(o.TEXTURE_2D,0,o.RGBA,e,r,0,o.RGBA,o.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,r)}}draw(e,r){this.setAttributes(e||this.positionBuffer,r||this.texCoordBuffer);let o=this.context.ctx;o.drawArrays(o.TRIANGLE_STRIP,0,4)}draw2d(e,r,o,s,n){return this.ctx2d&&e?(e instanceof ImageData?this.ctx2d.putImageData(e,r,o):(this.ctx2d.drawImage(e,r,o,s,n),typeof VideoFrame!="undefined"&&e instanceof VideoFrame&&e.close()),!0):!1}getInfo(){var _;let{totalFrames:e,x:r,y:o,width:s,height:n,name:d,cost:m}=this,l=Date.now(),g=(e-this.lastInfo.totalFrames)/((l-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:r,y:o,width:s,height:n,timestamp:l,fps:g,name:d,cost:m},Z({parent:(_=this.input)==null?void 0:_.getInfo()},this.lastInfo)}createTexture(e){let r=this.context.ctx,o=r.createTexture();return this.useTextures(o),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),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,e),o}};J([Je(oe.INIT,"connected",{sync:!0})],Gt.prototype,"connect",1),J([Je("connected",oe.INIT,{ignoreError:!0,sync:!0})],Gt.prototype,"disconnect",1),J([Je([],"closed",{sync:!0})],Gt.prototype,"close",1);var wf=ye(um(250),Ki(()=>performance.now()),fi()),Mf=i=>t=>{let e=0,r=performance.now();ye(wf,Ki(o=>(o-r)/i>>0),or(o=>o!=e?(e=o,!0):!1))(t)},wd=i=>t=>{let e=performance.now();ye(wf,yd(r=>r-e<i),Rr(1))(t)};var lI=[0,1,1,1,0,0,1,0],Qo=class extends Gt{constructor(e,r){super(e,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},r));u(this,"_intervalId",0);u(this,"_sequence",0);u(this,"checkGLError",!1);u(this,"checkVisibilityChange");e instanceof Vt?this.ctx2d=e.ctx||null:e.available&&(r!=null&&r.mirrorUpAndDown)&&this.setTexBuffer(lI)}start(e){this.log.info(`${this.name} start render ${e} fps`),bt.clearTask(this._intervalId),this._intervalId=bt.run("intervalInWorker",()=>{if(e!==this.context.frameRate&&(bt.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof Et){let o=this.context.ctx.getError();o&&this.context.destroy(new ae({code:q.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${o}`}))}},{fps:this.context.frameRate})}render(e){var r;return(r=this.input)!=null&&r.requestFrame(e)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}addInput(e,...r){super.addInput(e,...r),this.start(this.context.frameRate)}update(e=0){if(this._intervalId&&(bt.clearTask(this._intervalId),this._intervalId=0,e===1)){this.log.info(`${this.name} use requestVideoFrameCallback`);let r=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",r))};document.addEventListener("visibilitychange",r)}this.requestFrame(this._sequence++)}removeInput(e){super.removeInput(e),bt.clearTask(this._intervalId)}resize(e,r){super.resize(e,r),this.context.setSize(e,r)}close(){super.close(),bt.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},Js=class extends Qo{constructor(e,r){super(e,r);u(this,"_videoTrack");u(this,"_muteOb");u(this,"_closedOb",Ce(this,"closed"));u(this,"_subscription");u(this,"_canvasContainer");Number(si)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e._canvas.captureStream().getVideoTracks(),this._muteOb=Ce(this._videoTrack,"mute"),ye(Ce(this._videoTrack,"ended"),Xe(this._closedOb),ke(()=>{this.context.destroy(new ae({code:q.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=ye(this._muteOb,Xe(this._closedOb),gi(wd(5e3)),or(()=>{var e;return!!((e=this._videoTrack)!=null&&e.muted)&&!document.hidden}),ke(()=>{this.context.destroy(new ae({code:q.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,r;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack,(r=this._canvasContainer)==null||r.remove()}},Md=class extends Js{render(t){var e;return!!((e=this.input)!=null&&e.requestFrame(t))}};var Od=class extends Js{constructor(e,r,o){super(e,{name:"smallDestination",logger:o});this.resolution=r}resize(e,r){let o,s=e*r,n=this.resolution.width*this.resolution.height;this.log.info(`big res: ${e}*${r} small res: ${this.resolution.width}*${this.resolution.height} `),s>n?o=s/n:(this.log.warn(`Small stream resolution is not smaller than big stream, which is invalid. big: ${e} * ${r} small: ${this.resolution.width} * ${this.resolution.height}`),o=s/(160*120)),super.resize(e/Math.sqrt(o),r/Math.sqrt(o))}};var Sa=class extends Gt{constructor(e,r){super(e,Z({name:"imageSource"},r));u(this,"_lastImage");u(this,"_totalFrames",0);u(this,"_autoResize",!1);u(this,"_canvasRendered");u(this,"_videoCallbackId",0);u(this,"waitingFirstFrame",!0);this._autoResize=(r==null?void 0:r.autoResize)!==!1,er===16&&(this._canvasRendered=It(),ye(this._canvasRendered,Ea(this._image),eo(o=>o instanceof HTMLCanvasElement?Ce(o,"rendered"):Ta()),Xe(Ce(this,"closed")),ke(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){let e=this.image;this._videoCallbackId&&e.cancelVideoFrameCallback(this._videoCallbackId),li()&&!document.hidden&&(this._videoCallbackId=e.requestVideoFrameCallback((r,o)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=o.presentedFrames,this.update(1))}))}_render(e,r){var d;let{width:o,height:s}=this,{image:n}=this;if(n instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:o,videoHeight:s}=n,!o||!s)return!1;n.width=o,n.height=s}else if(n instanceof HTMLImageElement||n instanceof ImageData||n instanceof ImageBitmap){if({width:o,height:s}=n,n!==this._lastImage)this._lastImage=n;else if(o===this.width&&s===this.height)return!1}else n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas?({width:o,height:s}=n,this._lastImage=n):typeof VideoFrame!="undefined"&&n instanceof VideoFrame&&({displayWidth:o,displayHeight:s}=n,(d=this._lastImage)==null||d.close(),this._lastImage=n);if(!this._autoResize)return!0;if(this.width===o&&this.height===s&&this.totalFrames){if(r){this.useTexture();let m=this.context.ctx;m.texSubImage2D(m.TEXTURE_2D,0,0,0,m.RGBA,m.UNSIGNED_BYTE,n)}}else{if(r){this.useTexture();let m=this.context.ctx;m.texImage2D(m.TEXTURE_2D,0,m.RGBA,m.RGBA,m.UNSIGNED_BYTE,n)}this.resize(o,s)}return!0}get image(){return this._image}set image(e){var r;(r=this._canvasRendered)==null||r.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},ya=class extends Sa{constructor(e,r,o){super(e,o);this._player=r;this.name="videoPlayerSource",ye(Ce(this._player,Ze.PLAYER_STATE_CHANGED),Xe(Ce(this,"closed")),or(({state:s})=>s==="PLAYING"),ke(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},Ei=class extends ya{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(t,e,r){super(t,new tr({id:r.name,track:e,muted:!0,container:null,objectFit:"contain",log:r.logger}),r),this.name="videoTrackSource",this._player.play()}replaceTrack(t){this.waitingFirstFrame=!0,this._player.setTrack(t),this._player.play()}close(){super.close(),this._player.stop()}};var pI=`
|
|
34
32
|
// \u9876\u70B9\u7740\u8272\u5668
|
|
35
33
|
attribute vec4 a_position;
|
|
36
34
|
attribute vec2 a_texCoord;
|
|
@@ -40,7 +38,7 @@ void main() {
|
|
|
40
38
|
gl_Position = a_position;
|
|
41
39
|
v_texCoord = a_texCoord;
|
|
42
40
|
}
|
|
43
|
-
`,
|
|
41
|
+
`,hI=`
|
|
44
42
|
// \u7247\u5143\u7740\u8272\u5668
|
|
45
43
|
precision mediump float;
|
|
46
44
|
varying vec2 v_texCoord;
|
|
@@ -48,32 +46,66 @@ uniform sampler2D u_texture;
|
|
|
48
46
|
|
|
49
47
|
void main() {
|
|
50
48
|
gl_FragColor = texture2D(u_texture, v_texCoord);
|
|
51
|
-
} `;var Pr=class extends F{constructor(e){super();c(this,"frameRate");c(this,"_canvas");c(this,"log");c(this,"hasAlpha",!1);c(this,"name");c(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 Ui(this,e,{logger:this.log,name:t})}createVideoTrackDestination(e){return new Cs(this,e)}createVideoImageSource(e,t){return new Go(this,t?Object.assign(t,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,t){return new Wo(this,e,t?Object.assign(t,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};c(Pr,"_ids",0);var sT={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},Rs=class Rs extends Pr{constructor(){super(...arguments);c(this,"defaultProgam");c(this,"defaultVShader");c(this,"defaultFShader");c(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Pr._ids++}`),this.ctx=this._canvas.getContext("webgl2",sT),!this.ctx)throw new b({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,iT),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,rT),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new b({code:I.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}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}};c(Rs,"UNAVAILABLE","unavailable"),y([pe(F.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),N.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),N.addSuccessEvent({key:512700})}})],Rs.prototype,"create",1),y([pe("created",F.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(Rs.UNAVAILABLE,e),this.removeAllListeners()}})],Rs.prototype,"destroy",1);var De=Rs,Je=class extends Pr{constructor(){super(...arguments);c(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Pr._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new b({code:I.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",()=>{this.log.error("2d context lost")}),this._canvas.addEventListener("contextrestored",()=>{this.log.warn("2d context restored")})}destroy(e){let t="";e&&(t=e.message,this.error=e,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([pe(F.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),N.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),N.addSuccessEvent({key:512701})}})],Je.prototype,"create",1),y([pe("created",F.INIT,{ignoreError:!0,sync:!0})],Je.prototype,"destroy",1);function oT(s){return[15,30,45,60].reduce((e,t)=>Math.abs(t-s)<Math.abs(e-s)?t:e)}var di=class extends As{constructor(e,t,r=4){super(e,t,r);c(this,"mediaType",4);c(this,"source");c(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(_e(t==null?void 0:t.canvasRender)?t.canvasRender:ut===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 Je({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let t=new Lr(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(t),this.player.setCanvas(e._canvas),Cr()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let t=this.decodeFPS,r=oT(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 isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},ys=class extends di{constructor(e,t){super(e,t,2);c(this,"mediaType",2);c(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var bs=new Map;S.on(E.JOIN_SUCCESS,({room:s})=>{ge(s.userId,{eventId:32788})});S.on(E.LEAVE_START,({room:s})=>{ge(s.userId,{eventId:32789})});S.on(E.LOCAL_TRACK_PUBLISHED,({track:s})=>{if(s.room){let i=32769;s.mediaType===4?i=32768:s.mediaType===2&&(i=32805),ge(s.room.userId,{eventId:i})}});S.on(E.LOCAL_TRACK_UNPUBLISHED,({track:s})=>{if(s.room){let i=32771;s.mediaType===4?i=32770:s.mediaType===2&&(i=32806),ge(s.room.userId,{eventId:i})}});S.on(E.TRACK_MUTED,({track:s})=>{s.room&&(s.kind===m.AUDIO?ge(s.room.userId,{eventId:s.isRemote?32785:32772,remoteUserId:s.isRemote?s.userId:void 0}):ge(s.room.userId,{eventId:s.isRemote?32784:32773,remoteUserId:s.isRemote?s.userId:void 0}))});S.on(E.TRACK_UNMUTED,({track:s})=>{s.room&&(s.kind===m.AUDIO?ge(s.room.userId,{eventId:s.isRemote?32787:32774,remoteUserId:s.isRemote?s.userId:void 0}):ge(s.room.userId,{eventId:s.isRemote?32786:32775,remoteUserId:s.isRemote?s.userId:void 0}))});S.on(E.REMOTE_TRACK_SUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&ge(s.room.userId,{eventId:32777,remoteUserId:s.userId}),s.mediaType===4&&ge(s.room.userId,{eventId:32776,remoteUserId:s.userId}),s.mediaType===8&&ge(s.room.userId,{eventId:32803,remoteUserId:s.userId}))});S.on(E.REMOTE_TRACK_UNSUBSCRIBED,({track:s})=>{s.room&&(s.mediaType===1&&ge(s.room.userId,{eventId:32779,remoteUserId:s.userId}),s.mediaType===4&&ge(s.room.userId,{eventId:32778,remoteUserId:s.userId}),s.mediaType===8&&ge(s.room.userId,{eventId:32804,remoteUserId:s.userId}))});S.on(E.SWITCH_DEVICE_SUCCESS,({track:s})=>{s.room&&ge(s.room.userId,{eventId:s.kind===m.VIDEO?32780:32781})});S.on(E.LOCAL_TRACK_REPLACED,({track:s})=>{s.room&&ge(s.room.userId,{eventId:s.kind===m.VIDEO?32782:32783})});S.on(E.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&&ge(s.userId,{eventId:t})});S.on(E.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&&ge(s.userId,{eventId:o,remoteUserId:t})});S.on(E.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 d=t==="h264"?0:2,l={eventId:4004,param1:a,param2:d,streamType:n||2};e&&(l.remoteUserId=e,l.eventId=4005),ge(i,l),N.addEnum({key:e?514701:513701,value:a}),N.addEnum({key:e?514700:513700,value:d})});S.on(E.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)),ge(s.userId,e)}});function ge(s,i){let e=L(v({},i),{timestamp:Hs()});bs.has(s)?bs.get(s).push(e):bs.set(s,[e])}function Tm(s){if(bs.has(s)){let i=bs.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 bs.delete(s),i}return[]}var Em=Be(ze(),1);var Ha=class extends Em.EventEmitter{constructor(e,t,r="userId"){super();this.mySelfId=e;this._log=t;this.key=r;c(this,"userMap",new Map);c(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}]`;T(t)||(o+=`:${wc[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 u;let r=t[this.key];if(r===this.mySelfId)return;let{flag:o,userId:n,tinyId:a}=t,d=Ti(o,n),l=(u=this.remotePublishedUserMap.get(r))==null?void 0:u.muteState;if(l){let h=this.remotePublishedUserMap.get(r);h&&h.flag!==o&&(h.flag=o,this._log.info(`remote publish updated: ${JSON.stringify(h.muteState)}`),this.emit("6",{prevMuteState:l,muteState:d,flag:o}))}else this._log.info(`remote publish. state: ${JSON.stringify(d)}`),this.addUser({userId:n,tinyId:a,role:20}),this.emit("3",t),this.emit("6",{prevMuteState:Ti(0,n),muteState:d,flag:o})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}};function Ul({timesInSecond:s,maxSizeInSecond:i,getSize:e}){return z((t,r)=>{let o=new WeakMap;return S.on(E.ROOM_DESTROY,({room:n})=>o.delete(n)),function(...n){let a=o.get(this);if(a||(a={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},o.set(this,a)),a.timestamp===0?a.timestamp=Date.now():Date.now()-a.timestamp>1e3&&(a.timestamp=Date.now(),a.callCountInSecond=0,a.totalSizeInSecond=0),e&&(a.totalSizeInSecond+=e(...n)),a.timestamp!==0&&Date.now()-a.timestamp<1e3&&(a.callCountInSecond>=s||a.totalSizeInSecond>i))throw new b({code:I.INVALID_OPERATION,message:V({key:U.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 nT="2025-05-22 10:42:40",Sm=!0,Im=function(){var s;if(Sm){Sm=!1,C.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Ht}/en/index.html`),console.info(`* Changelog: ${Ht}/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:",Oe),Mt||C.debug("Build Time:",nT);let i=`UA: ${navigator.userAgent}
|
|
52
|
-
CPU core: ${navigator.hardwareConcurrency}, GPU: ${sd()}`,e=navigator.deviceMemory;e&&(i+=`, minRAM: ${e}GB`),C.info(i),C.info(`URL: ${location.href}${((s=self.frameElement)==null?void 0:s.tagName)==="IFRAME"?" in iframe":""}`),po().then(t=>{t&&C.info(vt)})}};var At={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 B={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},xt=(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))(xt||{});function Cm({code:s,params:i,enableDocLink:e=!1}){let t="",r,o=xt[s];try{r=Am[o]}catch(n){r=Am.UNKNOWN_ERROR}return ce(r)?t=r(i):Z(r)&&(t=r),i.fnName&&!t.includes(i.fnName)&&(t[t.length-1]!=="."&&(t+="."),t+=` thrown from ${i.fnName}()`),e&&(t+=" doc:"),t}var Am=L(v({},Pe),{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: ${ye(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: ${ye(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=wr(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=wr(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=wr(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=wr(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=wr(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=wr(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=wr(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 wr(s){if(!s)return"camera";let i=s.toLowerCase();return i.includes("screen")?"screen share":i.includes("audio")?"microphone":"camera"}var Vl=class s extends Error{constructor({code:e,extraCode:t,message:r="",messageParams:o,fnName:n="",originError:a}){var l;let d;r?d=r:d=Cm({code:e===B.SERVER_ERROR?e:t||e,params:v({fnName:n,error:a},o)});super(d);c(this,"name","RtcError");c(this,"code");c(this,"extraCode");c(this,"functionName");c(this,"message");c(this,"handler");c(this,"originError");this.name=xt[e],this.code=e,this.extraCode=t,this.functionName=n,this.originError=a,this.message=d,this.extraCode===5302&&((l=this.originError)!=null&&l.message.includes("system"))&&(this.handler=()=>{let u={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},h={startLocalVideo:"webcam",startLocalAudio:"microphone"},f=document.createElement("a");fr?f.href=`ms-settings:privacy-${h[this.functionName]}`:kt&&(f.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${u[this.functionName]}`),f.href.length>0&&f.click()})}static convertFrom(e,t,r){let o=e;if(e instanceof b){let{stack:n}=e,a={code:B.UNKNOWN_ERROR,fnName:t,originError:e};switch(e.getCode()){case I.INVALID_PARAMETER:a.code=B.INVALID_PARAMETER,a.message=e.message;break;case I.INVALID_OPERATION:a.code=B.INVALID_OPERATION;break;case I.NOT_SUPPORTED:case I.NOT_SUPPORTED_H264:a.code=B.ENV_NOT_SUPPORTED,e.getCode()===I.NOT_SUPPORTED_H264&&(a.extraCode=e.message.includes(Pe.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case I.JOIN_ROOM_FAILED:a.messageParams={fnParams:r};case I.SERVER_TIMEOUT:case I.SWITCH_ROLE_FAILED:a.code=B.SERVER_ERROR,a.extraCode=e.getExtraCode();break;case I.API_CALL_ABORTED:a.code=B.OPERATION_ABORT;break;case I.DEVICE_NOT_FOUND:case I.DEVICE_AUTO_RECOVER_FAILED:case I.INITIALIZE_FAILED:a.code=5300,e.name&&(a.extraCode=aT(e.name));break;case I.UNKNOWN:break;default:a.code=B.OPERATION_FAILED}o=new s(a),n&&(o.stack+=n.substr(n.indexOf(`
|
|
53
|
-
`)))}else{if(e instanceof s)return e;o=new s({code:B.UNKNOWN_ERROR,fnName:t,originError:e})}return o}};function aT(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 x=Vl;var Rm={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}}},ym={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}}},Ns={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(s,i,e){if(Z(s)&&!document.getElementById(s))throw new x({code:B.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:i}})}},bm={name:"userId",required:!0,type:"string"},Nm={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[At.AUDIO_PROFILE_STANDARD,At.AUDIO_PROFILE_STANDARD_STEREO,At.AUDIO_PROFILE_HIGH,At.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function Jo(s,i){if(!s)throw new x({code:B.INVALID_OPERATION,extraCode:5101,fnName:i})}function vm(s,i,e){if(!s)throw new x({code:B.INVALID_OPERATION,extraCode:5102,fnName:i,messageParams:{value:e}})}var zD={type:"number",notLessThanZero:!0},cT={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 x({code:B.INVALID_OPERATION,extraCode:5104,fnName:e});if(s.roomId){if(Z(s.roomId))throw new x({code:B.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:i}});if(!(/^[1-9]\d*$/.test(String(s.roomId))&&s.roomId<4294967295))throw new x({code:B.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 x({code:B.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:i}})}else throw new x({code:B.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"},playoutDelay:{type:"object",properties:{min:{type:"number",min:0,max:1e3},max:{type:"number",min:0,max:1e4}}}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:Ns,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:Rm},validate(s){var i;if(!((i=s==null?void 0:s.option)!=null&&i.videoTrack)&&vi())throw new x({code:B.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:L(v({},Ns),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:Rm}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:Nm},validate(s){var i;if(!((i=s==null?void 0:s.option)!=null&&i.audioTrack)&&vi())throw new x({code:B.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:Nm}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:Ns,publish:{type:"boolean"},option:ym},validate(s,i,e,t,r){var o;if(!((o=s==null?void 0:s.option)!=null&&o.videoTrack)){if(vi())throw new x({code:B.ENV_NOT_SUPPORTED,extraCode:5201});if(!Io())throw new x({code:B.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:Ns,publish:{type:"boolean"},option:ym}},muteRemoteAudio:[bm,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[bm,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:Ns,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){Jo(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(s.userId);if(vm(!!t,e,s),t&&(s.streamType==="main"&&!t.muteState.videoAvailable||s.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new x({code:B.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:s}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:L(v({},Ns),{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){Jo(this._room.isJoined,e);let t=this._room.remotePublishedUserMap.get(s.userId);if(vm(!!t,e,s),t&&(s.streamType==="main"&&!t.muteState.videoAvailable||s.streamType==="sub"&&!t.muteState.hasAuxiliary))throw new x({code:B.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!=="*"&&T(s.streamType))throw new x({code:B.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(s,i,e){Jo(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(!yo)throw new x({code:B.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new x({code:B.INVALID_OPERATION,fnName:e,extraCode:5108});if(s.byteLength>1e3)throw new x({code:B.INVALID_PARAMETER,extraCode:5018,fnName:e});if(s.byteLength===0)throw new x({code:B.INVALID_PARAMETER,extraCode:5017,messageParams:{key:i},fnName:e});Jo(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 x({code:B.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 x({code:B.INVALID_PARAMETER,extraCode:5018,fnName:e});if(s.byteLength===0)throw new x({code:B.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:i}})}}},validate(s,i,e){if(Jo(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new x({code:B.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:i}})}}},xe={TRTC:cT};var je=class extends Error{};function dT(s,i){let e=ur(s);for(let t=0;t<i.length;t++)Wt(e[t],i[t]);return e}function lT(s){this._resolve=Promise.resolve(s)}function uT(s){this._reject=Promise.reject(s)}var tr=class tr{constructor(i,e){this.instance=i;this.group=e;c(this,"started",!1);c(this,"ops",[]);c(this,"startSame",()=>!0);c(this,"mergeUpdate",dT);let t=tr.instances.get(i);t?t.set(e,this):tr.instances.set(i,new Map([[e,this]]))}static get(i,e){if(!e)return;let t=tr.instances.get(i);return t&&t.get(e)||new tr(i,e)}static gets(i,e){let t=tr.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 d;return i===0?this.started=!0:i===3&&(this.started=!1),this.ops.shift(),(d=this.currentOp)==null||d.action(),a},o=a=>{var d,l;throw this.ops.shift(),i===0&&((d=this.currentOp)==null?void 0:d.type)===2&&this.ops.shift().reject(new je("start failed")),(l=this.currentOp)==null||l.action(),a},n={type:i,action:()=>e(...n.args).then(r,o),args:t,resolve:lT,reject:uT};try{switch(this.state){case 1:if(i===0)throw new je("already started");break;case 4:if(i===2)throw new je("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 je("already start");break;case 3:switch(i.type){case 2:throw new je("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new je("unknown state")}else switch(i.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let t=new je("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 je("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new je("start not allowed after update");case 0:throw new je("duplicate start");case 3:if(this.startSame(this.currentOp.args,i.args))throw this.ops.pop().reject(new je("keep start")),new je("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}};c(tr,"instances",new WeakMap);var Vi=tr;var $a=new WeakMap,Ga=(s,i)=>{if(i instanceof je){let{stack:e}=i;i=new x({code:B.OPERATION_ABORT,message:`${s} abort: ${i.message}`,fnName:s}),e&&(i.stack+=e.substr(e.indexOf(`
|
|
54
|
-
|
|
55
|
-
|
|
49
|
+
} `;var Yo=class extends oe{constructor(e){super();u(this,"frameRate");u(this,"_canvas");u(this,"log");u(this,"hasAlpha",!1);u(this,"name");u(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,r){this._canvas&&(this._canvas.width=e,this._canvas.height=r)}createVideoTrackSource(e,r){return new Ei(this,e,{logger:this.log,name:r})}createVideoTrackDestination(e){return new Js(this,e)}createVideoImageSource(e,r){return new Sa(this,r?Object.assign(r,{logger:this.log,image:e}):{logger:this.log,image:e})}createVideoPlayerSource(e,r){return new ya(this,e,r?Object.assign(r,{logger:this.log}):{logger:this.log})}get available(){return this.state==="created"}disconnect(){this.emit("disconnect")}};u(Yo,"_ids",0);var fI={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},Xs=class Xs extends Yo{constructor(){super(...arguments);u(this,"defaultProgam");u(this,"defaultVShader");u(this,"defaultFShader");u(this,"ctx")}create(){if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Yo._ids++}`),this.ctx=this._canvas.getContext("webgl2",fI),!this.ctx)throw new ae({code:q.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,pI),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,hI),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new ae({code:q.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let r="";return e&&(r=e.message,this.error=e,X.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info(`video context destroy${r}`?`: ${r}`:""),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 r;(r=this.ctx)==null||r.viewport(0,0,e,this.height),super.width=e}set height(e){var r;(r=this.ctx)==null||r.viewport(0,0,this.width,e),super.height=e}setSize(e,r){var o;(o=this.ctx)==null||o.viewport(0,0,e,r),super.setSize(e,r)}createShader(e,r){let o=this.ctx,s=o.createShader(e);return o.shaderSource(s,r),o.compileShader(s),s}createProgram(e,r){let o=this.ctx,s=o.createProgram();return o.attachShader(s,e),o.attachShader(s,r),o.linkProgram(s),o.getProgramParameter(s,o.LINK_STATUS)||this.log.error(o.getProgramInfoLog(s)),s}};u(Xs,"UNAVAILABLE","unavailable"),J([Je(oe.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),X.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),X.addSuccessEvent({key:512700})}})],Xs.prototype,"create",1),J([Je("created",oe.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(Xs.UNAVAILABLE,e),this.removeAllListeners()}})],Xs.prototype,"destroy",1);var Et=Xs,Vt=class extends Yo{constructor(){super(...arguments);u(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${Yo._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha}),!this.ctx)throw new ae({code:q.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",()=>{this.log.error("2d context lost")}),this._canvas.addEventListener("contextrestored",()=>{this.log.warn("2d context restored")})}destroy(e){let r="";e&&(r=e.message,this.error=e,X.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info(`video context destroy ${r?`: ${r}`:""}`),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),X.addSuccessEvent({key:512703})}};J([Je(oe.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),X.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),X.addSuccessEvent({key:512701})}})],Vt.prototype,"create",1),J([Je("created",oe.INIT,{ignoreError:!0,sync:!0})],Vt.prototype,"destroy",1);function gI(i){return[15,30,45,60].reduce((e,r)=>Math.abs(r-i)<Math.abs(e-i)?r:e)}var to=class extends zs{constructor(e,r,o=4){super(e,r,o);u(this,"mediaType",4);u(this,"source");u(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0});this.manager=e.videoManager,this.once("first-video-frame",s=>{this.room.emit("first-video-frame",s)})}play(e,r){return(dt(r==null?void 0:r.canvasRender)?r.canvasRender:er===17)&&!this.source&&this.useCanvasPlayer(),super.play(e,r).then(()=>{this.player.calculateStat()})}useCanvasPlayer(){if(this.log.info(`useCanvasPlayer(), has element:${!!this.player.element}`),!this.player.element)return;let e=new Vt({frameRate:15,logger:this.log,name:this.userId});e.create({alpha:!1});let r=new Qo(e,{name:"remotePlayer",logger:this.log});this.source=e.createVideoPlayerSource(this.player),this.source.connect(r),this.player.setCanvas(e._canvas),li()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(e){let r=this.decodeFPS,o=gI(r);if(!We(r)||r<=0){this.log.debug(`updateCanvasPlayerFPS() ignore decoder: ${r} `);return}if(o===e.frameRate){this.log.debug(`updateCanvasPlayerFPS() ignore ClosestFPS ${o} == ${e.frameRate}`);return}this.log.info(`updateCanvasPlayerFPS() decoder: ${r}, closest: ${o}, current: ${e.frameRate}`),e.frameRate=o}get decodeFPS(){var n;let{msg_video_status:e}=((n=this.room.heartbeatReport)==null?void 0:n.msg_down_stream_info.find(d=>d.msg_user_info.str_identifier===this.userId))||{},r=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let o=e.find(d=>d.uint32_video_stream_type===r);return(o==null?void 0:o.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 r of this.manager.decodePipeline)if(r&&(e=r({frame:e,track:this}),!e))return;return e}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(e){this.room.changeType(e,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(e){e==="publish"||e==="both"||super.setMirror(e)}onDecodeDowngradeStateChanged(e){this.emit("decode-downgrade-state-changed",e)}},Pd=class extends to{constructor(e,r){super(e,r,2);u(this,"mediaType",2);u(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}};var Qs=new Map;L.on(U.JOIN_SUCCESS,({room:i})=>{ot(i.userId,{eventId:32788})});L.on(U.LEAVE_START,({room:i})=>{ot(i.userId,{eventId:32789})});L.on(U.LOCAL_TRACK_PUBLISHED,({track:i})=>{if(i.room){let t=32769;i.mediaType===4?t=32768:i.mediaType===2&&(t=32805),ot(i.room.userId,{eventId:t})}});L.on(U.LOCAL_TRACK_UNPUBLISHED,({track:i})=>{if(i.room){let t=32771;i.mediaType===4?t=32770:i.mediaType===2&&(t=32806),ot(i.room.userId,{eventId:t})}});L.on(U.TRACK_MUTED,({track:i})=>{i.room&&(i.kind===N.AUDIO?ot(i.room.userId,{eventId:i.isRemote?32785:32772,remoteUserId:i.isRemote?i.userId:void 0}):ot(i.room.userId,{eventId:i.isRemote?32784:32773,remoteUserId:i.isRemote?i.userId:void 0}))});L.on(U.TRACK_UNMUTED,({track:i})=>{i.room&&(i.kind===N.AUDIO?ot(i.room.userId,{eventId:i.isRemote?32787:32774,remoteUserId:i.isRemote?i.userId:void 0}):ot(i.room.userId,{eventId:i.isRemote?32786:32775,remoteUserId:i.isRemote?i.userId:void 0}))});L.on(U.REMOTE_TRACK_SUBSCRIBED,({track:i})=>{i.room&&(i.mediaType===1&&ot(i.room.userId,{eventId:32777,remoteUserId:i.userId}),i.mediaType===4&&ot(i.room.userId,{eventId:32776,remoteUserId:i.userId}),i.mediaType===8&&ot(i.room.userId,{eventId:32803,remoteUserId:i.userId}))});L.on(U.REMOTE_TRACK_UNSUBSCRIBED,({track:i})=>{i.room&&(i.mediaType===1&&ot(i.room.userId,{eventId:32779,remoteUserId:i.userId}),i.mediaType===4&&ot(i.room.userId,{eventId:32778,remoteUserId:i.userId}),i.mediaType===8&&ot(i.room.userId,{eventId:32804,remoteUserId:i.userId}))});L.on(U.SWITCH_DEVICE_SUCCESS,({track:i})=>{i.room&&ot(i.room.userId,{eventId:i.kind===N.VIDEO?32780:32781})});L.on(U.LOCAL_TRACK_REPLACED,({track:i})=>{i.room&&ot(i.room.userId,{eventId:i.kind===N.VIDEO?32782:32783})});L.on(U.SIGNAL_CONNECTION_STATE_CHANGED,({room:i,prevState:t,state:e})=>{let r;switch(e){case"CONNECTED":t==="RECONNECTING"?r=32795:r=32791;break;case"DISCONNECTED":t==="RECONNECTING"?r=32796:r=32790;break;case"RECONNECTING":r=32794;break}r&&ot(i.userId,{eventId:r})});L.on(U.PEER_CONNECTION_STATE_CHANGED,({room:i,prevState:t,state:e,remoteUserId:r})=>{let o=!!r,s;switch(e){case"CONNECTED":t==="RECONNECTING"?s=o?32801:32798:s=o?32793:32792;break;case"DISCONNECTED":t==="RECONNECTING"&&(s=o?32802:32799);break;case"RECONNECTING":s=o?32800:32797;break}s&&ot(i.userId,{eventId:s,remoteUserId:r})});L.on(U.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:i,userId:t,remoteUserId:e,codec:r,isHWCodec:o,prevImplementation:s,streamType:n})=>{let d=o?1:0;s||(d=o?3:2);let m=r==="h264"?0:2,l={eventId:4004,param1:d,param2:m,streamType:n||2};e&&(l.remoteUserId=e,l.eventId=4005),ot(t,l),X.addEnum({key:e?514701:513701,value:d}),X.addEnum({key:e?514700:513700,value:m})});L.on(U.LOCAL_TRACK_RECAPTURE,({track:i,error:t})=>{if(i.userId){let e={eventId:2003,param1:0};i.kind===N.AUDIO?(e.streamType=1,t&&(e.param1=2)):(e.streamType=i.streamType==="auxiliary"?7:2,t&&(e.param1=8)),ot(i.userId,e)}});function ot(i,t){let e=Ee(Z({},t),{timestamp:_n()});Qs.has(i)?Qs.get(i).push(e):Qs.set(i,[e])}function Of(i){if(Qs.has(i)){let t=Qs.get(i).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 Qs.delete(i),t}return[]}function Pf(...i){return Me((t,e)=>function(...r){return EI.call(this,i,r,e,this._name),t.apply(this,r)})}function EI(i,t,e,r){try{if(it(i))for(let o=0;o<i.length;o++)xd.call(this,{rule:i[o],value:t[o],key:i[o].name,fnName:e,className:r});else xd.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}catch(o){throw F.error(o),o}}function xd({rule:i,value:t,key:e,fnName:r,className:o}){if(V(t)){if(i.required)throw new ae({code:q.INVALID_PARAMETER,message:$e({key:Fe.INVALID_PARAMETER_REQUIRED,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})});if(V(i.defaultValue))return;t=i.defaultValue}if(Array.isArray(i.type)){let d=!1;for(let m=0;m<i.type.length;m++)i.type[m]===null&&t===null&&(d=!0),He(i.type[m])&&t instanceof i.type[m]&&(d=!0),ve(i.type[m])&&nt(t)===i.type[m].toLowerCase()&&(d=!0);if(!d)throw new ae({code:q.INVALID_PARAMETER,message:$e({key:Fe.INVALID_PARAMETER_TYPE,data:{key:e,rule:{type:i.type.map(m=>wo(m)?Ts(m):ve(m)?m:nt(m))},fnName:r,value:t},link:{className:o,fnName:r}})})}else if(!V(i.type)&&nt(t)!==i.type)throw new ae({code:q.INVALID_PARAMETER,message:$e({key:Fe.INVALID_PARAMETER_TYPE,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})});if(i.allowEmpty===!1){let d=We(t)&&(t===0||Number.isNaN(t)),m=ve(t)&&t.trim()==="";if(d||m)throw new ae({code:q.INVALID_PARAMETER,message:$e({key:Fe.INVALID_PARAMETER_EMPTY,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})})}if(i.notLessThanZero&&We(t)&&t<0)throw new ae({code:q.INVALID_PARAMETER,message:$e({key:Fe.CANNOT_LESS_THAN_ZERO,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})});if(!V(i.min)&&We(t)&&t<i.min)throw new ae({code:q.INVALID_PARAMETER,message:$e({key:Fe.INVALID_PARAMETER_MIN,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})});if(!V(i.max)&&We(t)&&t>i.max)throw new ae({code:q.INVALID_PARAMETER,message:$e({key:Fe.INVALID_PARAMETER_MAX,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})});if(ve(i.instanceOf)){if(!t||t._name!==i.instanceOf)throw new ae({code:q.INVALID_PARAMETER,message:$e({key:Fe.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})})}else if(He(i.instanceOf)&&!(t instanceof i.instanceOf))throw new ae({code:q.INVALID_PARAMETER,message:$e({key:Fe.INVALID_PARAMETER_INSTANCE,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})});if(i.values&&!i.values.includes(t))throw new ae({code:q.INVALID_PARAMETER,message:$e({key:Fe.INVALID_PARAMETER_RANGE,data:{key:e,rule:i,fnName:r,value:t},link:{className:o,fnName:r}})});let{properties:s}=i;xt(s)&&Er(t)&&Object.keys(s).forEach(d=>{xd.call(this,{rule:s[d],value:t&&t[d],key:`${e}.${d}`,fnName:r,className:o})});let{arrayItem:n}=i;xt(n)&&it(t)&&t.forEach((d,m)=>{xd.call(this,{rule:n,value:d,key:`${e}[${m}]`,fnName:r,className:o})}),He(i.validate)&&i.validate.call(this,t,e,r,o,this)}var _I=ki(Wi(),1);var TI=Object.create,Fd=Object.defineProperty,II=Object.defineProperties,Uf=Object.getOwnPropertyDescriptor,SI=Object.getOwnPropertyDescriptors,Vf=Object.getOwnPropertyNames,xf=Object.getOwnPropertySymbols,yI=Object.getPrototypeOf,Ff=Object.prototype.hasOwnProperty,AI=Object.prototype.propertyIsEnumerable,jm=(i,t,e)=>t in i?Fd(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,Ld=(i,t)=>{for(var e in t||(t={}))Ff.call(t,e)&&jm(i,e,t[e]);if(xf)for(var e of xf(t))AI.call(t,e)&&jm(i,e,t[e]);return i},Ud=(i,t)=>II(i,SI(t)),bI=(i,t)=>function(){return t||(0,i[Vf(i)[0]])((t={exports:{}}).exports,t),t.exports},RI=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Vf(t))Ff.call(i,o)||o===e||Fd(i,o,{get:()=>t[o],enumerable:!(r=Uf(t,o))||r.enumerable});return i},vI=(i,t,e)=>(e=i!=null?TI(yI(i)):{},RI(!t&&i&&i.__esModule?e:Fd(e,"default",{value:i,enumerable:!0}),i)),_i=(i,t,e,r)=>{for(var o,s=r>1?void 0:r?Uf(t,e):t,n=i.length-1;n>=0;n--)(o=i[n])&&(s=(r?o(t,e,s):o(s))||s);return r&&s&&Fd(t,e,s),s},vr=(i,t,e)=>jm(i,typeof t!="symbol"?t+"":t,e),CI=bI({"../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(i,t){"use strict";var e=Object.prototype.hasOwnProperty,r="~";function o(){}function s(l,g,_){this.fn=l,this.context=g,this.once=_||!1}function n(l,g,_,S,v){if(typeof _!="function")throw new TypeError("The listener must be a function");var x=new s(_,S||l,v),P=r?r+g:g;return l._events[P]?l._events[P].fn?l._events[P]=[l._events[P],x]:l._events[P].push(x):(l._events[P]=x,l._eventsCount++),l}function d(l,g){--l._eventsCount==0?l._events=new o:delete l._events[g]}function m(){this._events=new o,this._eventsCount=0}Object.create&&(o.prototype=Object.create(null),new o().__proto__||(r=!1)),m.prototype.eventNames=function(){var l,g,_=[];if(this._eventsCount===0)return _;for(g in l=this._events)e.call(l,g)&&_.push(r?g.slice(1):g);return Object.getOwnPropertySymbols?_.concat(Object.getOwnPropertySymbols(l)):_},m.prototype.listeners=function(l){var g=r?r+l:l,_=this._events[g];if(!_)return[];if(_.fn)return[_.fn];for(var S=0,v=_.length,x=new Array(v);S<v;S++)x[S]=_[S].fn;return x},m.prototype.listenerCount=function(l){var g=r?r+l:l,_=this._events[g];return _?_.fn?1:_.length:0},m.prototype.emit=function(l,g,_,S,v,x){var P=r?r+l:l;if(!this._events[P])return!1;var M,G,se=this._events[P],ne=arguments.length;if(se.fn){switch(se.once&&this.removeListener(l,se.fn,void 0,!0),ne){case 1:return se.fn.call(se.context),!0;case 2:return se.fn.call(se.context,g),!0;case 3:return se.fn.call(se.context,g,_),!0;case 4:return se.fn.call(se.context,g,_,S),!0;case 5:return se.fn.call(se.context,g,_,S,v),!0;case 6:return se.fn.call(se.context,g,_,S,v,x),!0}for(G=1,M=new Array(ne-1);G<ne;G++)M[G-1]=arguments[G];se.fn.apply(se.context,M)}else{var Ae,ie=se.length;for(G=0;G<ie;G++)switch(se[G].once&&this.removeListener(l,se[G].fn,void 0,!0),ne){case 1:se[G].fn.call(se[G].context);break;case 2:se[G].fn.call(se[G].context,g);break;case 3:se[G].fn.call(se[G].context,g,_);break;case 4:se[G].fn.call(se[G].context,g,_,S);break;default:if(!M)for(Ae=1,M=new Array(ne-1);Ae<ne;Ae++)M[Ae-1]=arguments[Ae];se[G].fn.apply(se[G].context,M)}}return!0},m.prototype.on=function(l,g,_){return n(this,l,g,_,!1)},m.prototype.once=function(l,g,_){return n(this,l,g,_,!0)},m.prototype.removeListener=function(l,g,_,S){var v=r?r+l:l;if(!this._events[v])return this;if(!g)return d(this,v),this;var x=this._events[v];if(x.fn)x.fn!==g||S&&!x.once||_&&x.context!==_||d(this,v);else{for(var P=0,M=[],G=x.length;P<G;P++)(x[P].fn!==g||S&&!x[P].once||_&&x[P].context!==_)&&M.push(x[P]);M.length?this._events[v]=M.length===1?M[0]:M:d(this,v)}return this},m.prototype.removeAllListeners=function(l){var g;return l?(g=r?r+l:l,this._events[g]&&d(this,g)):(this._events=new o,this._eventsCount=0),this},m.prototype.off=m.prototype.removeListener,m.prototype.addListener=m.prototype.on,m.prefixed=r,m.EventEmitter=m,t!==void 0&&(t.exports=m)}}),DI=vI(CI(),1),kf=Symbol("instance"),LM=Symbol("abortCtrl"),kd=Symbol("cacheResult"),Gm=class{constructor(i,t,e){this.oldState=i,this.newState=t,this.action=e,this.aborted=!1}abort(i){this.aborted=!0,Ra.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},Vd=class extends Error{constructor(i,t,e){super(t),this.state=i,this.message=t,this.cause=e}};function NI(i){return typeof i=="object"&&i&&"then"in i}var ba=new Map;function ro(i,t,e={}){return(r,o,s)=>{let n=e.action||o;if(!e.context){let m=ba.get(r)||[];ba.has(r)||ba.set(r,m),m.push({from:i,to:t,action:n})}let d=s.value;s.value=function(...m){let l=this;if(e.context&&(l=jt.get(typeof e.context=="function"?e.context.call(this,...m):e.context)),l.state===t)return e.sync?l[kd]:Promise.resolve(l[kd]);l.state instanceof Gm&&l.state.action==e.abortAction&&l.state.abort(l);let g=null;Array.isArray(i)?i.length==0?l.state instanceof Gm&&l.state.abort(l):typeof l.state=="string"&&i.includes(l.state)||(g=new Vd(l._state,`${l.name} ${n} to ${t} failed: current state ${l._state} not from ${i.join("|")}`)):i!==l.state&&(g=new Vd(l._state,`${l.name} ${n} to ${t} failed: current state ${l._state} not from ${i}`));let _=M=>{if(e.fail&&e.fail.call(this,M),e.sync){if(e.ignoreError)return M;throw M}return e.ignoreError?Promise.resolve(M):Promise.reject(M)};if(g)return _(g);let S=l.state,v=new Gm(S,t,n);Ra.call(l,v);let x=M=>{var G;return l[kd]=M,v.aborted||(Ra.call(l,t),(G=e.success)===null||G===void 0||G.call(this,l[kd])),M},P=M=>(Ra.call(l,S,M),_(M));try{let M=d.apply(this,m);return NI(M)?M.then(x).catch(P):e.sync?x(M):Promise.resolve(x(M))}catch(M){return P(new Vd(l._state,`${l.name} ${n} from ${i} to ${t} failed: ${M}`,M instanceof Error?M:new Error(String(M))))}}}}function wI(...i){return(t,e,r)=>{let o=r.value,s=e;r.value=function(...n){if(!i.includes(this.state.toString()))throw new Vd(this.state,`${this.name} ${s} failed: current state ${this.state} not in ${i}`);return o.apply(this,n)}}}var MI=typeof window!="undefined"&&window.__AFSM__?(e,r)=>{window.dispatchEvent(new CustomEvent(e,{detail:r}))}:typeof importScripts!="undefined"?(e,r)=>{postMessage({type:e,payload:r})}:()=>{};function Ra(i,t){let e=this._state;this._state=i;let r=i.toString();i&&this.emit(r,e),this.emit(jt.STATECHANGED,i,e,t),this.updateDevTools({value:i,old:e,err:t instanceof Error?t.message:String(t)})}var jt=class dr extends DI.default{constructor(t,e,r){super(),this.name=t,this.groupName=e,this._state=dr.INIT,t||(t=Date.now().toString(36)),r?Object.setPrototypeOf(this,r):r=Object.getPrototypeOf(this),e||(this.groupName=this.constructor.name);let o=r[kf];o?this.name=o.name+"-"+o.count++:r[kf]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let t=Object.getPrototypeOf(this),e=ba.get(t)||[],r=new Set,o=[],s=[],n=new Set,d=Object.getPrototypeOf(t);ba.has(d)&&(d.stateDiagram.forEach(l=>r.add(l)),d.allStates.forEach(l=>n.add(l))),e.forEach(({from:l,to:g,action:_})=>{typeof l=="string"?o.push({from:l,to:g,action:_}):l.length?l.forEach(S=>{o.push({from:S,to:g,action:_})}):s.push({to:g,action:_})}),o.forEach(({from:l,to:g,action:_})=>{n.add(l),n.add(g),n.add(_+"ing"),r.add(`${l} --> ${_}ing : ${_}`),r.add(`${_}ing --> ${g} : ${_} \u{1F7E2}`),r.add(`${_}ing --> ${l} : ${_} \u{1F534}`)}),s.forEach(({to:l,action:g})=>{r.add(`${g}ing --> ${l} : ${g} \u{1F7E2}`),n.forEach(_=>{_!==l&&r.add(`${_} --> ${g}ing : ${g}`)})});let m=[...r];return Object.defineProperties(t,{stateDiagram:{value:m},allStates:{value:n}}),m}static get(t){let e;return typeof t=="string"?(e=dr.instances.get(t),e||dr.instances.set(t,e=new dr(t,void 0,Object.create(dr.prototype)))):(e=dr.instances2.get(t),e||dr.instances2.set(t,e=new dr(t.constructor.name,void 0,Object.create(dr.prototype)))),e}static getState(t){var e;return(e=dr.get(t))===null||e===void 0?void 0:e.state}updateDevTools(t={}){MI(dr.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(t){Ra.call(this,t)}};jt.STATECHANGED="stateChanged",jt.UPDATEAFSM="updateAFSM",jt.INIT="[*]",jt.ON="on",jt.OFF="off",jt.instances=new Map,jt.instances2=new WeakMap;var Ys=class extends jt{constructor(){super(...arguments),vr(this,"decoder"),vr(this,"config")}initialize(){return A(this,null,function*(){this.decoder=new VideoDecoder({output:i=>{this.emit("videoFrame",i)},error:i=>{this.close(),this.emit("error",i)}})})}configure(i){this.config=i,this.decoder.configure(Ud(Ld({},i),{codec:this.getCodec(i)}))}getCodec(i){switch(i.codec){case"hevc":return"hvc1.1.6.L0.12.34.56.78.9A.BC";case"av1":return"av01.0.05M.08";case"avc":return"avc1.420028";default:return i.codec}}decode(i){this.decoder.state==="configured"&&this.decoder.decode(new EncodedVideoChunk(i))}flush(){this.decoder.flush()}reset(){this.decoder.reset()}close(){this.decoder.state!=="closed"&&this.decoder.close()}};function OI(){var i;self.onmessage=t=>{if(t.data.type==="init"){let{canvas:e,wasmScript:r,wasmBinary:o}=t.data,s=e==null?void 0:e.getContext("2d"),n=0,d=0,m={wasmBinary:o,postRun:()=>{i=new m.VideoDecoder({videoInfo(l,g){n=l,d=g,console.log("video info",l,g)},yuvData(l,g){let _=n*d,S=_>>2,v=m.HEAPU32[l>>2],x=m.HEAPU32[1+(l>>2)],P=m.HEAPU32[2+(l>>2)],M=m.HEAPU8.subarray(v,v+_),G=m.HEAPU8.subarray(x,x+S),se=m.HEAPU8.subarray(P,P+S),ne=new Uint8Array(_+S+S);ne.set(M),ne.set(G,_),ne.set(se,_+S);let Ae=new VideoFrame(ne,{codedWidth:n,codedHeight:d,format:"I420",timestamp:g});e?(s==null||s.drawImage(Ae,0,0,e.width,e.height),s==null||s.commit()):self.postMessage({type:"yuvData",videoFrame:Ae},[Ae])}}),self.postMessage({type:"ready"})}};Function("var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;return "+r)()(m)}else if(t.data.type==="decode"){let{packet:e}=t.data;i==null||i.decode(e.data,e.type=="key",e.timestamp)}else if(t.data.type==="setCodec"){let{codec:e,format:r,description:o}=t.data;i==null||i.setCodec(e,r,o!=null?o:"")}}}_i([ro([jt.INIT,"closed"],"initialized")],Ys.prototype,"initialize",1),_i([ro("initialized","configured",{sync:!0})],Ys.prototype,"configure",1),_i([wI("configured")],Ys.prototype,"decode",1),_i([ro([],jt.INIT,{sync:!0})],Ys.prototype,"reset",1),_i([ro([],"closed",{ignoreError:!0,sync:!0})],Ys.prototype,"close",1);var Aa=class extends jt{constructor(i,t,e=!1,r,o=!1){super(),this.createModule=i,this.wasmBinary=t,this.workerMode=e,this.canvas=r,this.yuvMode=o,vr(this,"worker"),vr(this,"decoder"),vr(this,"config"),vr(this,"module",{}),vr(this,"width",0),vr(this,"height",0)}initialize(i){return A(this,null,function*(){var t;if(this.workerMode){let r=new RegExp("\\{(.+)\\}","s").exec(OI.toString())[1];this.worker=new Worker(URL.createObjectURL(new Blob([r],{type:"text/javascript"})));let o=(t=this.canvas)==null?void 0:t.transferControlToOffscreen(),s=yield this.wasmBinary;return console.warn("worker mode",s),this.worker.postMessage({type:"init",canvas:o,wasmScript:this.createModule.toString(),wasmBinary:s},o?[o,s]:[s]),new Promise(n=>{this.worker.onmessage=d=>{if(d.data.type==="ready")delete this.wasmBinary,n(),console.warn("worker mode initialize success");else if(d.data.type==="yuvData"){let{videoFrame:m}=d.data;this.emit("videoFrame",m)}}})}let e=this.module;return this.wasmBinary&&(e.wasmBinary=yield this.wasmBinary),e.print=r=>console.log(r),e.printErr=r=>console.log(`[JS] ERROR: ${r}`),e.onAbort=()=>console.log("[JS] FATAL: WASM ABORTED"),new Promise(r=>{e.postRun=o=>{this.decoder=new this.module.VideoDecoder(this),console.log("video soft decoder initialize success"),r()},i&&Object.assign(e,i),this.createModule(e)})})}configure(i){var t,e,r;this.config=i;let o=this.config.codec.startsWith("avc")?"avc":"hevc",s=this.config.description?o=="avc"?"avcc":"hvcc":"annexb";(e=this.decoder)==null||e.setCodec(o,s,(t=this.config.description)!=null?t:""),(r=this.worker)==null||r.postMessage({type:"setCodec",codec:o,format:s,description:this.config.description})}decode(i){var t,e;(t=this.decoder)==null||t.decode(i.data,i.type=="key",i.timestamp),this.state==="configured"&&((e=this.worker)==null||e.postMessage({type:"decode",packet:i}))}flush(){}reset(){this.config=void 0,this.decoder&&this.decoder.clear()}close(){this.removeAllListeners(),this.decoder&&(this.decoder.clear(),this.decoder.delete())}videoInfo(i,t){this.width=i,this.height=t;let e={width:i,height:t};this.emit("videoCodecInfo",e)}yuvData(i,t){if(!this.module)return;let e=this.width*this.height,r=e>>2,o=this.module.HEAPU32[i>>2],s=this.module.HEAPU32[1+(i>>2)],n=this.module.HEAPU32[2+(i>>2)],d=this.module.HEAPU8.subarray(o,o+e),m=this.module.HEAPU8.subarray(s,s+r),l=this.module.HEAPU8.subarray(n,n+r);if(this.yuvMode)return void this.emit("videoFrame",{y:d,u:m,v:l,timestamp:t});let g=new Uint8Array(e+r+r);g.set(d),g.set(m,e),g.set(l,e+r),this.emit("videoFrame",new VideoFrame(g,{codedWidth:this.width,codedHeight:this.height,format:"I420",timestamp:t}))}errorInfo(i){let t={errMsg:i};this.emit("error",t)}};_i([ro([jt.INIT,"closed"],"initialized")],Aa.prototype,"initialize",1),_i([ro("initialized","configured",{sync:!0})],Aa.prototype,"configure",1),_i([ro([],jt.INIT,{sync:!0})],Aa.prototype,"reset",1),_i([ro([],"closed",{sync:!0})],Aa.prototype,"close",1);var PI=(()=>{var i=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return function(t={}){var e,r,o=t;o.ready=new Promise((a,c)=>{e=a,r=c});var s,n,d,m=Object.assign({},o),l="./this.program",g=typeof window=="object",_=typeof importScripts=="function",S=(typeof process=="object"&&typeof process.versions=="object"&&process.versions.node,"");(g||_)&&(_?S=self.location.href:typeof document!="undefined"&&document.currentScript&&(S=document.currentScript.src),i&&(S=i),S=S.indexOf("blob:")!==0?S.substr(0,S.replace(/[?#].*/,"").lastIndexOf("/")+1):"",s=a=>{var c=new XMLHttpRequest;return c.open("GET",a,!1),c.send(null),c.responseText},_&&(d=a=>{var c=new XMLHttpRequest;return c.open("GET",a,!1),c.responseType="arraybuffer",c.send(null),new Uint8Array(c.response)}),n=(a,c,p)=>{var f=new XMLHttpRequest;f.open("GET",a,!0),f.responseType="arraybuffer",f.onload=()=>{f.status==200||f.status==0&&f.response?c(f.response):p()},f.onerror=p,f.send(null)});var v,x=o.print||console.log.bind(console),P=o.printErr||console.error.bind(console);Object.assign(o,m),m=null,o.arguments&&o.arguments,o.thisProgram&&(l=o.thisProgram),o.quit&&o.quit,o.wasmBinary&&(v=o.wasmBinary);var M,G;o.noExitRuntime,typeof WebAssembly!="object"&&Nr("no native wasm support detected");var se,ne,Ae,ie,Pe,Le,po,on,sn,nn=!1,Dr=[],os=[],Si=[],Y=0,qr=null,zr=null;function ss(a){Y++,o.monitorRunDependencies&&o.monitorRunDependencies(Y)}function ho(a){if(Y--,o.monitorRunDependencies&&o.monitorRunDependencies(Y),Y==0&&(qr!==null&&(clearInterval(qr),qr=null),zr)){var c=zr;zr=null,c()}}function Nr(a){o.onAbort&&o.onAbort(a),P(a="Aborted("+a+")"),nn=!0,a+=". Build with -sASSERTIONS for more info.";var c=new WebAssembly.RuntimeError(a);throw r(c),c}var Jr,an,fe,Qe;function wt(a){return a.startsWith("data:application/octet-stream;base64,")}function W(a){if(a==Jr&&v)return new Uint8Array(v);if(d)return d(a);throw"both async and sync fetching of the wasm failed"}function wr(a,c,p){return function(f){return v||!g&&!_||typeof fetch!="function"?Promise.resolve().then(()=>W(f)):fetch(f,{credentials:"same-origin"}).then(T=>{if(!T.ok)throw"failed to load wasm binary file at '"+f+"'";return T.arrayBuffer()}).catch(()=>W(f))}(a).then(f=>WebAssembly.instantiate(f,c)).then(f=>f).then(p,f=>{P("failed to asynchronously prepare wasm: "+f),Nr(f)})}wt(Jr="videodec.wasm")||(an=Jr,Jr=o.locateFile?o.locateFile(an,S):S+an);var yi=a=>{for(;a.length>0;)a.shift()(o)};function Ai(a){this.excPtr=a,this.ptr=a-24,this.set_type=function(c){Le[this.ptr+4>>2]=c},this.get_type=function(){return Le[this.ptr+4>>2]},this.set_destructor=function(c){Le[this.ptr+8>>2]=c},this.get_destructor=function(){return Le[this.ptr+8>>2]},this.set_caught=function(c){c=c?1:0,se[this.ptr+12|0]=c},this.get_caught=function(){return se[this.ptr+12|0]!=0},this.set_rethrown=function(c){c=c?1:0,se[this.ptr+13|0]=c},this.get_rethrown=function(){return se[this.ptr+13|0]!=0},this.init=function(c,p){this.set_adjusted_ptr(0),this.set_type(c),this.set_destructor(p)},this.set_adjusted_ptr=function(c){Le[this.ptr+16>>2]=c},this.get_adjusted_ptr=function(){return Le[this.ptr+16>>2]},this.get_exception_ptr=function(){if(hn(this.get_type()))return Le[this.excPtr>>2];var c=this.get_adjusted_ptr();return c!==0?c:this.excPtr}}var ce={isAbs:a=>a.charAt(0)==="/",splitPath:a=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(a).slice(1),normalizeArray:(a,c)=>{for(var p=0,f=a.length-1;f>=0;f--){var T=a[f];T==="."?a.splice(f,1):T===".."?(a.splice(f,1),p++):p&&(a.splice(f,1),p--)}if(c)for(;p;p--)a.unshift("..");return a},normalize:a=>{var c=ce.isAbs(a),p=a.substr(-1)==="/";return(a=ce.normalizeArray(a.split("/").filter(f=>!!f),!c).join("/"))||c||(a="."),a&&p&&(a+="/"),(c?"/":"")+a},dirname:a=>{var c=ce.splitPath(a),p=c[0],f=c[1];return p||f?(f&&(f=f.substr(0,f.length-1)),p+f):"."},basename:a=>{if(a==="/")return"/";var c=(a=(a=ce.normalize(a)).replace(/\/$/,"")).lastIndexOf("/");return c===-1?a:a.substr(c+1)},join:function(){var a=Array.prototype.slice.call(arguments);return ce.normalize(a.join("/"))},join2:(a,c)=>ce.normalize(a+"/"+c)},cn=a=>(cn=(()=>{if(typeof crypto=="object"&&typeof crypto.getRandomValues=="function")return c=>crypto.getRandomValues(c);Nr("initRandomDevice")})())(a),qt={resolve:function(){for(var a="",c=!1,p=arguments.length-1;p>=-1&&!c;p--){var f=p>=0?arguments[p]:h.cwd();if(typeof f!="string")throw new TypeError("Arguments to path.resolve must be strings");if(!f)return"";a=f+"/"+a,c=ce.isAbs(f)}return(c?"/":"")+(a=ce.normalizeArray(a.split("/").filter(T=>!!T),!c).join("/"))||"."},relative:(a,c)=>{function p(w){for(var z=0;z<w.length&&w[z]==="";z++);for(var te=w.length-1;te>=0&&w[te]==="";te--);return z>te?[]:w.slice(z,te-z+1)}a=qt.resolve(a).substr(1),c=qt.resolve(c).substr(1);for(var f=p(a.split("/")),T=p(c.split("/")),y=Math.min(f.length,T.length),b=y,R=0;R<y;R++)if(f[R]!==T[R]){b=R;break}var O=[];for(R=b;R<f.length;R++)O.push("..");return(O=O.concat(T.slice(b))).join("/")}},bi=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0,Mt=(a,c,p)=>{for(var f=c+p,T=c;a[T]&&!(T>=f);)++T;if(T-c>16&&a.buffer&&bi)return bi.decode(a.subarray(c,T));for(var y="";c<T;){var b=a[c++];if(128&b){var R=63&a[c++];if((224&b)!=192){var O=63&a[c++];if((b=(240&b)==224?(15&b)<<12|R<<6|O:(7&b)<<18|R<<12|O<<6|63&a[c++])<65536)y+=String.fromCharCode(b);else{var w=b-65536;y+=String.fromCharCode(55296|w>>10,56320|1023&w)}}else y+=String.fromCharCode((31&b)<<6|R)}else y+=String.fromCharCode(b)}return y},le=[],fo=a=>{for(var c=0,p=0;p<a.length;++p){var f=a.charCodeAt(p);f<=127?c++:f<=2047?c+=2:f>=55296&&f<=57343?(c+=4,++p):c+=3}return c},go=(a,c,p,f)=>{if(!(f>0))return 0;for(var T=p,y=p+f-1,b=0;b<a.length;++b){var R=a.charCodeAt(b);if(R>=55296&&R<=57343&&(R=65536+((1023&R)<<10)|1023&a.charCodeAt(++b)),R<=127){if(p>=y)break;c[p++]=R}else if(R<=2047){if(p+1>=y)break;c[p++]=192|R>>6,c[p++]=128|63&R}else if(R<=65535){if(p+2>=y)break;c[p++]=224|R>>12,c[p++]=128|R>>6&63,c[p++]=128|63&R}else{if(p+3>=y)break;c[p++]=240|R>>18,c[p++]=128|R>>12&63,c[p++]=128|R>>6&63,c[p++]=128|63&R}}return c[p]=0,p-T};function ns(a,c,p){var f=p>0?p:fo(a)+1,T=new Array(f),y=go(a,T,0,T.length);return c&&(T.length=y),T}var lr={ttys:[],init:function(){},shutdown:function(){},register:function(a,c){lr.ttys[a]={input:[],output:[],ops:c},h.registerDevice(a,lr.stream_ops)},stream_ops:{open:function(a){var c=lr.ttys[a.node.rdev];if(!c)throw new h.ErrnoError(43);a.tty=c,a.seekable=!1},close:function(a){a.tty.ops.fsync(a.tty)},fsync:function(a){a.tty.ops.fsync(a.tty)},read:function(a,c,p,f,T){if(!a.tty||!a.tty.ops.get_char)throw new h.ErrnoError(60);for(var y=0,b=0;b<f;b++){var R;try{R=a.tty.ops.get_char(a.tty)}catch(O){throw new h.ErrnoError(29)}if(R===void 0&&y===0)throw new h.ErrnoError(6);if(R==null)break;y++,c[p+b]=R}return y&&(a.node.timestamp=Date.now()),y},write:function(a,c,p,f,T){if(!a.tty||!a.tty.ops.put_char)throw new h.ErrnoError(60);try{for(var y=0;y<f;y++)a.tty.ops.put_char(a.tty,c[p+y])}catch(b){throw new h.ErrnoError(29)}return f&&(a.node.timestamp=Date.now()),y}},default_tty_ops:{get_char:function(a){return(()=>{if(!le.length){var c=null;if(typeof window!="undefined"&&typeof window.prompt=="function"?(c=window.prompt("Input: "))!==null&&(c+=`
|
|
50
|
+
`):typeof readline=="function"&&(c=readline())!==null&&(c+=`
|
|
51
|
+
`),!c)return null;le=ns(c,!0)}return le.shift()})()},put_char:function(a,c){c===null||c===10?(x(Mt(a.output,0)),a.output=[]):c!=0&&a.output.push(c)},fsync:function(a){a.output&&a.output.length>0&&(x(Mt(a.output,0)),a.output=[])},ioctl_tcgets:function(a){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets:function(a,c,p){return 0},ioctl_tiocgwinsz:function(a){return[24,80]}},default_tty1_ops:{put_char:function(a,c){c===null||c===10?(P(Mt(a.output,0)),a.output=[]):c!=0&&a.output.push(c)},fsync:function(a){a.output&&a.output.length>0&&(P(Mt(a.output,0)),a.output=[])}}},dn=a=>{Nr()},Se={ops_table:null,mount:a=>Se.createNode(null,"/",16895,0),createNode(a,c,p,f){if(h.isBlkdev(p)||h.isFIFO(p))throw new h.ErrnoError(63);Se.ops_table||(Se.ops_table={dir:{node:{getattr:Se.node_ops.getattr,setattr:Se.node_ops.setattr,lookup:Se.node_ops.lookup,mknod:Se.node_ops.mknod,rename:Se.node_ops.rename,unlink:Se.node_ops.unlink,rmdir:Se.node_ops.rmdir,readdir:Se.node_ops.readdir,symlink:Se.node_ops.symlink},stream:{llseek:Se.stream_ops.llseek}},file:{node:{getattr:Se.node_ops.getattr,setattr:Se.node_ops.setattr},stream:{llseek:Se.stream_ops.llseek,read:Se.stream_ops.read,write:Se.stream_ops.write,allocate:Se.stream_ops.allocate,mmap:Se.stream_ops.mmap,msync:Se.stream_ops.msync}},link:{node:{getattr:Se.node_ops.getattr,setattr:Se.node_ops.setattr,readlink:Se.node_ops.readlink},stream:{}},chrdev:{node:{getattr:Se.node_ops.getattr,setattr:Se.node_ops.setattr},stream:h.chrdev_stream_ops}});var T=h.createNode(a,c,p,f);return h.isDir(T.mode)?(T.node_ops=Se.ops_table.dir.node,T.stream_ops=Se.ops_table.dir.stream,T.contents={}):h.isFile(T.mode)?(T.node_ops=Se.ops_table.file.node,T.stream_ops=Se.ops_table.file.stream,T.usedBytes=0,T.contents=null):h.isLink(T.mode)?(T.node_ops=Se.ops_table.link.node,T.stream_ops=Se.ops_table.link.stream):h.isChrdev(T.mode)&&(T.node_ops=Se.ops_table.chrdev.node,T.stream_ops=Se.ops_table.chrdev.stream),T.timestamp=Date.now(),a&&(a.contents[c]=T,a.timestamp=T.timestamp),T},getFileDataAsTypedArray:a=>a.contents?a.contents.subarray?a.contents.subarray(0,a.usedBytes):new Uint8Array(a.contents):new Uint8Array(0),expandFileStorage(a,c){var p=a.contents?a.contents.length:0;if(!(p>=c)){c=Math.max(c,p*(p<1048576?2:1.125)>>>0),p!=0&&(c=Math.max(c,256));var f=a.contents;a.contents=new Uint8Array(c),a.usedBytes>0&&a.contents.set(f.subarray(0,a.usedBytes),0)}},resizeFileStorage(a,c){if(a.usedBytes!=c)if(c==0)a.contents=null,a.usedBytes=0;else{var p=a.contents;a.contents=new Uint8Array(c),p&&a.contents.set(p.subarray(0,Math.min(c,a.usedBytes))),a.usedBytes=c}},node_ops:{getattr(a){var c={};return c.dev=h.isChrdev(a.mode)?a.id:1,c.ino=a.id,c.mode=a.mode,c.nlink=1,c.uid=0,c.gid=0,c.rdev=a.rdev,h.isDir(a.mode)?c.size=4096:h.isFile(a.mode)?c.size=a.usedBytes:h.isLink(a.mode)?c.size=a.link.length:c.size=0,c.atime=new Date(a.timestamp),c.mtime=new Date(a.timestamp),c.ctime=new Date(a.timestamp),c.blksize=4096,c.blocks=Math.ceil(c.size/c.blksize),c},setattr(a,c){c.mode!==void 0&&(a.mode=c.mode),c.timestamp!==void 0&&(a.timestamp=c.timestamp),c.size!==void 0&&Se.resizeFileStorage(a,c.size)},lookup(a,c){throw h.genericErrors[44]},mknod:(a,c,p,f)=>Se.createNode(a,c,p,f),rename(a,c,p){if(h.isDir(a.mode)){var f;try{f=h.lookupNode(c,p)}catch(y){}if(f)for(var T in f.contents)throw new h.ErrnoError(55)}delete a.parent.contents[a.name],a.parent.timestamp=Date.now(),a.name=p,c.contents[p]=a,c.timestamp=a.parent.timestamp,a.parent=c},unlink(a,c){delete a.contents[c],a.timestamp=Date.now()},rmdir(a,c){var p=h.lookupNode(a,c);for(var f in p.contents)throw new h.ErrnoError(55);delete a.contents[c],a.timestamp=Date.now()},readdir(a){var c=[".",".."];for(var p in a.contents)a.contents.hasOwnProperty(p)&&c.push(p);return c},symlink(a,c,p){var f=Se.createNode(a,c,41471,0);return f.link=p,f},readlink(a){if(!h.isLink(a.mode))throw new h.ErrnoError(28);return a.link}},stream_ops:{read(a,c,p,f,T){var y=a.node.contents;if(T>=a.node.usedBytes)return 0;var b=Math.min(a.node.usedBytes-T,f);if(b>8&&y.subarray)c.set(y.subarray(T,T+b),p);else for(var R=0;R<b;R++)c[p+R]=y[T+R];return b},write(a,c,p,f,T,y){if(!f)return 0;var b=a.node;if(b.timestamp=Date.now(),c.subarray&&(!b.contents||b.contents.subarray)){if(y)return b.contents=c.subarray(p,p+f),b.usedBytes=f,f;if(b.usedBytes===0&&T===0)return b.contents=c.slice(p,p+f),b.usedBytes=f,f;if(T+f<=b.usedBytes)return b.contents.set(c.subarray(p,p+f),T),f}if(Se.expandFileStorage(b,T+f),b.contents.subarray&&c.subarray)b.contents.set(c.subarray(p,p+f),T);else for(var R=0;R<f;R++)b.contents[T+R]=c[p+R];return b.usedBytes=Math.max(b.usedBytes,T+f),f},llseek(a,c,p){var f=c;if(p===1?f+=a.position:p===2&&h.isFile(a.node.mode)&&(f+=a.node.usedBytes),f<0)throw new h.ErrnoError(28);return f},allocate(a,c,p){Se.expandFileStorage(a.node,c+p),a.node.usedBytes=Math.max(a.node.usedBytes,c+p)},mmap(a,c,p,f,T){if(!h.isFile(a.node.mode))throw new h.ErrnoError(43);var y,b,R=a.node.contents;if(2&T||R.buffer!==se.buffer){if((p>0||p+c<R.length)&&(R=R.subarray?R.subarray(p,p+c):Array.prototype.slice.call(R,p,p+c)),b=!0,!(y=dn()))throw new h.ErrnoError(48);se.set(R,y)}else b=!1,y=R.byteOffset;return{ptr:y,allocated:b}},msync:(a,c,p,f,T)=>(Se.stream_ops.write(a,c,0,f,p,!1),0)}},Su=(a,c,p,f)=>{var T=f?"":`al ${a}`;n(a,y=>{var b;b=`Loading data file "${a}" failed (no arrayBuffer).`,y||Nr(b),c(new Uint8Array(y)),T&&ho()},y=>{if(!p)throw`Loading data file "${a}" failed.`;p()}),T&&ss()},yu=o.preloadPlugins||[];function Xr(a,c){var p=0;return a&&(p|=365),c&&(p|=146),p}var h={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,lookupPath:(a,c={})=>{if(!(a=qt.resolve(a)))return{path:"",node:null};if((c=Object.assign({follow_mount:!0,recurse_count:0},c)).recurse_count>8)throw new h.ErrnoError(32);for(var p=a.split("/").filter(w=>!!w),f=h.root,T="/",y=0;y<p.length;y++){var b=y===p.length-1;if(b&&c.parent)break;if(f=h.lookupNode(f,p[y]),T=ce.join2(T,p[y]),h.isMountpoint(f)&&(!b||b&&c.follow_mount)&&(f=f.mounted.root),!b||c.follow)for(var R=0;h.isLink(f.mode);){var O=h.readlink(T);if(T=qt.resolve(ce.dirname(T),O),f=h.lookupPath(T,{recurse_count:c.recurse_count+1}).node,R++>40)throw new h.ErrnoError(32)}}return{path:T,node:f}},getPath:a=>{for(var c;;){if(h.isRoot(a)){var p=a.mount.mountpoint;return c?p[p.length-1]!=="/"?`${p}/${c}`:p+c:p}c=c?`${a.name}/${c}`:a.name,a=a.parent}},hashName:(a,c)=>{for(var p=0,f=0;f<c.length;f++)p=(p<<5)-p+c.charCodeAt(f)|0;return(a+p>>>0)%h.nameTable.length},hashAddNode:a=>{var c=h.hashName(a.parent.id,a.name);a.name_next=h.nameTable[c],h.nameTable[c]=a},hashRemoveNode:a=>{var c=h.hashName(a.parent.id,a.name);if(h.nameTable[c]===a)h.nameTable[c]=a.name_next;else for(var p=h.nameTable[c];p;){if(p.name_next===a){p.name_next=a.name_next;break}p=p.name_next}},lookupNode:(a,c)=>{var p=h.mayLookup(a);if(p)throw new h.ErrnoError(p,a);for(var f=h.hashName(a.id,c),T=h.nameTable[f];T;T=T.name_next){var y=T.name;if(T.parent.id===a.id&&y===c)return T}return h.lookup(a,c)},createNode:(a,c,p,f)=>{var T=new h.FSNode(a,c,p,f);return h.hashAddNode(T),T},destroyNode:a=>{h.hashRemoveNode(a)},isRoot:a=>a===a.parent,isMountpoint:a=>!!a.mounted,isFile:a=>(61440&a)==32768,isDir:a=>(61440&a)==16384,isLink:a=>(61440&a)==40960,isChrdev:a=>(61440&a)==8192,isBlkdev:a=>(61440&a)==24576,isFIFO:a=>(61440&a)==4096,isSocket:a=>!(49152&~a),flagsToPermissionString:a=>{var c=["r","w","rw"][3&a];return 512&a&&(c+="w"),c},nodePermissions:(a,c)=>h.ignorePermissions||(!c.includes("r")||292&a.mode)&&(!c.includes("w")||146&a.mode)&&(!c.includes("x")||73&a.mode)?0:2,mayLookup:a=>{var c=h.nodePermissions(a,"x");return c||(a.node_ops.lookup?0:2)},mayCreate:(a,c)=>{try{return h.lookupNode(a,c),20}catch(p){}return h.nodePermissions(a,"wx")},mayDelete:(a,c,p)=>{var f;try{f=h.lookupNode(a,c)}catch(y){return y.errno}var T=h.nodePermissions(a,"wx");if(T)return T;if(p){if(!h.isDir(f.mode))return 54;if(h.isRoot(f)||h.getPath(f)===h.cwd())return 10}else if(h.isDir(f.mode))return 31;return 0},mayOpen:(a,c)=>a?h.isLink(a.mode)?32:h.isDir(a.mode)&&(h.flagsToPermissionString(c)!=="r"||512&c)?31:h.nodePermissions(a,h.flagsToPermissionString(c)):44,MAX_OPEN_FDS:4096,nextfd:()=>{for(var a=0;a<=h.MAX_OPEN_FDS;a++)if(!h.streams[a])return a;throw new h.ErrnoError(33)},getStreamChecked:a=>{var c=h.getStream(a);if(!c)throw new h.ErrnoError(8);return c},getStream:a=>h.streams[a],createStream:(a,c=-1)=>(h.FSStream||(h.FSStream=function(){this.shared={}},h.FSStream.prototype={},Object.defineProperties(h.FSStream.prototype,{object:{get(){return this.node},set(p){this.node=p}},isRead:{get(){return(2097155&this.flags)!=1}},isWrite:{get(){return!!(2097155&this.flags)}},isAppend:{get(){return 1024&this.flags}},flags:{get(){return this.shared.flags},set(p){this.shared.flags=p}},position:{get(){return this.shared.position},set(p){this.shared.position=p}}})),a=Object.assign(new h.FSStream,a),c==-1&&(c=h.nextfd()),a.fd=c,h.streams[c]=a,a),closeStream:a=>{h.streams[a]=null},chrdev_stream_ops:{open:a=>{var c=h.getDevice(a.node.rdev);a.stream_ops=c.stream_ops,a.stream_ops.open&&a.stream_ops.open(a)},llseek:()=>{throw new h.ErrnoError(70)}},major:a=>a>>8,minor:a=>255&a,makedev:(a,c)=>a<<8|c,registerDevice:(a,c)=>{h.devices[a]={stream_ops:c}},getDevice:a=>h.devices[a],getMounts:a=>{for(var c=[],p=[a];p.length;){var f=p.pop();c.push(f),p.push.apply(p,f.mounts)}return c},syncfs:(a,c)=>{typeof a=="function"&&(c=a,a=!1),h.syncFSRequests++,h.syncFSRequests>1&&P(`warning: ${h.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var p=h.getMounts(h.root.mount),f=0;function T(b){return h.syncFSRequests--,c(b)}function y(b){if(b)return y.errored?void 0:(y.errored=!0,T(b));++f>=p.length&&T(null)}p.forEach(b=>{if(!b.type.syncfs)return y(null);b.type.syncfs(b,a,y)})},mount:(a,c,p)=>{var f,T=p==="/",y=!p;if(T&&h.root)throw new h.ErrnoError(10);if(!T&&!y){var b=h.lookupPath(p,{follow_mount:!1});if(p=b.path,f=b.node,h.isMountpoint(f))throw new h.ErrnoError(10);if(!h.isDir(f.mode))throw new h.ErrnoError(54)}var R={type:a,opts:c,mountpoint:p,mounts:[]},O=a.mount(R);return O.mount=R,R.root=O,T?h.root=O:f&&(f.mounted=R,f.mount&&f.mount.mounts.push(R)),O},unmount:a=>{var c=h.lookupPath(a,{follow_mount:!1});if(!h.isMountpoint(c.node))throw new h.ErrnoError(28);var p=c.node,f=p.mounted,T=h.getMounts(f);Object.keys(h.nameTable).forEach(b=>{for(var R=h.nameTable[b];R;){var O=R.name_next;T.includes(R.mount)&&h.destroyNode(R),R=O}}),p.mounted=null;var y=p.mount.mounts.indexOf(f);p.mount.mounts.splice(y,1)},lookup:(a,c)=>a.node_ops.lookup(a,c),mknod:(a,c,p)=>{var f=h.lookupPath(a,{parent:!0}).node,T=ce.basename(a);if(!T||T==="."||T==="..")throw new h.ErrnoError(28);var y=h.mayCreate(f,T);if(y)throw new h.ErrnoError(y);if(!f.node_ops.mknod)throw new h.ErrnoError(63);return f.node_ops.mknod(f,T,c,p)},create:(a,c)=>(c=c!==void 0?c:438,c&=4095,c|=32768,h.mknod(a,c,0)),mkdir:(a,c)=>(c=c!==void 0?c:511,c&=1023,c|=16384,h.mknod(a,c,0)),mkdirTree:(a,c)=>{for(var p=a.split("/"),f="",T=0;T<p.length;++T)if(p[T]){f+="/"+p[T];try{h.mkdir(f,c)}catch(y){if(y.errno!=20)throw y}}},mkdev:(a,c,p)=>(p===void 0&&(p=c,c=438),c|=8192,h.mknod(a,c,p)),symlink:(a,c)=>{if(!qt.resolve(a))throw new h.ErrnoError(44);var p=h.lookupPath(c,{parent:!0}).node;if(!p)throw new h.ErrnoError(44);var f=ce.basename(c),T=h.mayCreate(p,f);if(T)throw new h.ErrnoError(T);if(!p.node_ops.symlink)throw new h.ErrnoError(63);return p.node_ops.symlink(p,f,a)},rename:(a,c)=>{var p,f,T=ce.dirname(a),y=ce.dirname(c),b=ce.basename(a),R=ce.basename(c);if(p=h.lookupPath(a,{parent:!0}).node,f=h.lookupPath(c,{parent:!0}).node,!p||!f)throw new h.ErrnoError(44);if(p.mount!==f.mount)throw new h.ErrnoError(75);var O,w=h.lookupNode(p,b),z=qt.relative(a,y);if(z.charAt(0)!==".")throw new h.ErrnoError(28);if((z=qt.relative(c,T)).charAt(0)!==".")throw new h.ErrnoError(55);try{O=h.lookupNode(f,R)}catch(ee){}if(w!==O){var te=h.isDir(w.mode),re=h.mayDelete(p,b,te);if(re)throw new h.ErrnoError(re);if(re=O?h.mayDelete(f,R,te):h.mayCreate(f,R))throw new h.ErrnoError(re);if(!p.node_ops.rename)throw new h.ErrnoError(63);if(h.isMountpoint(w)||O&&h.isMountpoint(O))throw new h.ErrnoError(10);if(f!==p&&(re=h.nodePermissions(p,"w")))throw new h.ErrnoError(re);h.hashRemoveNode(w);try{p.node_ops.rename(w,f,R)}catch(ee){throw ee}finally{h.hashAddNode(w)}}},rmdir:a=>{var c=h.lookupPath(a,{parent:!0}).node,p=ce.basename(a),f=h.lookupNode(c,p),T=h.mayDelete(c,p,!0);if(T)throw new h.ErrnoError(T);if(!c.node_ops.rmdir)throw new h.ErrnoError(63);if(h.isMountpoint(f))throw new h.ErrnoError(10);c.node_ops.rmdir(c,p),h.destroyNode(f)},readdir:a=>{var c=h.lookupPath(a,{follow:!0}).node;if(!c.node_ops.readdir)throw new h.ErrnoError(54);return c.node_ops.readdir(c)},unlink:a=>{var c=h.lookupPath(a,{parent:!0}).node;if(!c)throw new h.ErrnoError(44);var p=ce.basename(a),f=h.lookupNode(c,p),T=h.mayDelete(c,p,!1);if(T)throw new h.ErrnoError(T);if(!c.node_ops.unlink)throw new h.ErrnoError(63);if(h.isMountpoint(f))throw new h.ErrnoError(10);c.node_ops.unlink(c,p),h.destroyNode(f)},readlink:a=>{var c=h.lookupPath(a).node;if(!c)throw new h.ErrnoError(44);if(!c.node_ops.readlink)throw new h.ErrnoError(28);return qt.resolve(h.getPath(c.parent),c.node_ops.readlink(c))},stat:(a,c)=>{var p=h.lookupPath(a,{follow:!c}).node;if(!p)throw new h.ErrnoError(44);if(!p.node_ops.getattr)throw new h.ErrnoError(63);return p.node_ops.getattr(p)},lstat:a=>h.stat(a,!0),chmod:(a,c,p)=>{var f;if(typeof a=="string"?f=h.lookupPath(a,{follow:!p}).node:f=a,!f.node_ops.setattr)throw new h.ErrnoError(63);f.node_ops.setattr(f,{mode:4095&c|-4096&f.mode,timestamp:Date.now()})},lchmod:(a,c)=>{h.chmod(a,c,!0)},fchmod:(a,c)=>{var p=h.getStreamChecked(a);h.chmod(p.node,c)},chown:(a,c,p,f)=>{var T;if(typeof a=="string"?T=h.lookupPath(a,{follow:!f}).node:T=a,!T.node_ops.setattr)throw new h.ErrnoError(63);T.node_ops.setattr(T,{timestamp:Date.now()})},lchown:(a,c,p)=>{h.chown(a,c,p,!0)},fchown:(a,c,p)=>{var f=h.getStreamChecked(a);h.chown(f.node,c,p)},truncate:(a,c)=>{if(c<0)throw new h.ErrnoError(28);var p;if(typeof a=="string"?p=h.lookupPath(a,{follow:!0}).node:p=a,!p.node_ops.setattr)throw new h.ErrnoError(63);if(h.isDir(p.mode))throw new h.ErrnoError(31);if(!h.isFile(p.mode))throw new h.ErrnoError(28);var f=h.nodePermissions(p,"w");if(f)throw new h.ErrnoError(f);p.node_ops.setattr(p,{size:c,timestamp:Date.now()})},ftruncate:(a,c)=>{var p=h.getStreamChecked(a);if(!(2097155&p.flags))throw new h.ErrnoError(28);h.truncate(p.node,c)},utime:(a,c,p)=>{var f=h.lookupPath(a,{follow:!0}).node;f.node_ops.setattr(f,{timestamp:Math.max(c,p)})},open:(a,c,p)=>{if(a==="")throw new h.ErrnoError(44);var f;if(p=p===void 0?438:p,p=64&(c=typeof c=="string"?function(R){var O={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[R];if(O===void 0)throw new Error(`Unknown file open mode: ${R}`);return O}(c):c)?4095&p|32768:0,typeof a=="object")f=a;else{a=ce.normalize(a);try{f=h.lookupPath(a,{follow:!(131072&c)}).node}catch(R){}}var T=!1;if(64&c)if(f){if(128&c)throw new h.ErrnoError(20)}else f=h.mknod(a,p,0),T=!0;if(!f)throw new h.ErrnoError(44);if(h.isChrdev(f.mode)&&(c&=-513),65536&c&&!h.isDir(f.mode))throw new h.ErrnoError(54);if(!T){var y=h.mayOpen(f,c);if(y)throw new h.ErrnoError(y)}512&c&&!T&&h.truncate(f,0),c&=-131713;var b=h.createStream({node:f,path:h.getPath(f),flags:c,seekable:!0,position:0,stream_ops:f.stream_ops,ungotten:[],error:!1});return b.stream_ops.open&&b.stream_ops.open(b),!o.logReadFiles||1&c||(h.readFiles||(h.readFiles={}),a in h.readFiles||(h.readFiles[a]=1)),b},close:a=>{if(h.isClosed(a))throw new h.ErrnoError(8);a.getdents&&(a.getdents=null);try{a.stream_ops.close&&a.stream_ops.close(a)}catch(c){throw c}finally{h.closeStream(a.fd)}a.fd=null},isClosed:a=>a.fd===null,llseek:(a,c,p)=>{if(h.isClosed(a))throw new h.ErrnoError(8);if(!a.seekable||!a.stream_ops.llseek)throw new h.ErrnoError(70);if(p!=0&&p!=1&&p!=2)throw new h.ErrnoError(28);return a.position=a.stream_ops.llseek(a,c,p),a.ungotten=[],a.position},read:(a,c,p,f,T)=>{if(f<0||T<0)throw new h.ErrnoError(28);if(h.isClosed(a))throw new h.ErrnoError(8);if((2097155&a.flags)==1)throw new h.ErrnoError(8);if(h.isDir(a.node.mode))throw new h.ErrnoError(31);if(!a.stream_ops.read)throw new h.ErrnoError(28);var y=T!==void 0;if(y){if(!a.seekable)throw new h.ErrnoError(70)}else T=a.position;var b=a.stream_ops.read(a,c,p,f,T);return y||(a.position+=b),b},write:(a,c,p,f,T,y)=>{if(f<0||T<0)throw new h.ErrnoError(28);if(h.isClosed(a))throw new h.ErrnoError(8);if(!(2097155&a.flags))throw new h.ErrnoError(8);if(h.isDir(a.node.mode))throw new h.ErrnoError(31);if(!a.stream_ops.write)throw new h.ErrnoError(28);a.seekable&&1024&a.flags&&h.llseek(a,0,2);var b=T!==void 0;if(b){if(!a.seekable)throw new h.ErrnoError(70)}else T=a.position;var R=a.stream_ops.write(a,c,p,f,T,y);return b||(a.position+=R),R},allocate:(a,c,p)=>{if(h.isClosed(a))throw new h.ErrnoError(8);if(c<0||p<=0)throw new h.ErrnoError(28);if(!(2097155&a.flags))throw new h.ErrnoError(8);if(!h.isFile(a.node.mode)&&!h.isDir(a.node.mode))throw new h.ErrnoError(43);if(!a.stream_ops.allocate)throw new h.ErrnoError(138);a.stream_ops.allocate(a,c,p)},mmap:(a,c,p,f,T)=>{if(2&f&&!(2&T)&&(2097155&a.flags)!=2)throw new h.ErrnoError(2);if((2097155&a.flags)==1)throw new h.ErrnoError(2);if(!a.stream_ops.mmap)throw new h.ErrnoError(43);return a.stream_ops.mmap(a,c,p,f,T)},msync:(a,c,p,f,T)=>a.stream_ops.msync?a.stream_ops.msync(a,c,p,f,T):0,munmap:a=>0,ioctl:(a,c,p)=>{if(!a.stream_ops.ioctl)throw new h.ErrnoError(59);return a.stream_ops.ioctl(a,c,p)},readFile:(a,c={})=>{if(c.flags=c.flags||0,c.encoding=c.encoding||"binary",c.encoding!=="utf8"&&c.encoding!=="binary")throw new Error(`Invalid encoding type "${c.encoding}"`);var p,f=h.open(a,c.flags),T=h.stat(a).size,y=new Uint8Array(T);return h.read(f,y,0,T,0),c.encoding==="utf8"?p=Mt(y,0):c.encoding==="binary"&&(p=y),h.close(f),p},writeFile:(a,c,p={})=>{p.flags=p.flags||577;var f=h.open(a,p.flags,p.mode);if(typeof c=="string"){var T=new Uint8Array(fo(c)+1),y=go(c,T,0,T.length);h.write(f,T,0,y,void 0,p.canOwn)}else{if(!ArrayBuffer.isView(c))throw new Error("Unsupported data type");h.write(f,c,0,c.byteLength,void 0,p.canOwn)}h.close(f)},cwd:()=>h.currentPath,chdir:a=>{var c=h.lookupPath(a,{follow:!0});if(c.node===null)throw new h.ErrnoError(44);if(!h.isDir(c.node.mode))throw new h.ErrnoError(54);var p=h.nodePermissions(c.node,"x");if(p)throw new h.ErrnoError(p);h.currentPath=c.path},createDefaultDirectories:()=>{h.mkdir("/tmp"),h.mkdir("/home"),h.mkdir("/home/web_user")},createDefaultDevices:()=>{h.mkdir("/dev"),h.registerDevice(h.makedev(1,3),{read:()=>0,write:(f,T,y,b,R)=>b}),h.mkdev("/dev/null",h.makedev(1,3)),lr.register(h.makedev(5,0),lr.default_tty_ops),lr.register(h.makedev(6,0),lr.default_tty1_ops),h.mkdev("/dev/tty",h.makedev(5,0)),h.mkdev("/dev/tty1",h.makedev(6,0));var a=new Uint8Array(1024),c=0,p=()=>(c===0&&(c=cn(a).byteLength),a[--c]);h.createDevice("/dev","random",p),h.createDevice("/dev","urandom",p),h.mkdir("/dev/shm"),h.mkdir("/dev/shm/tmp")},createSpecialDirectories:()=>{h.mkdir("/proc");var a=h.mkdir("/proc/self");h.mkdir("/proc/self/fd"),h.mount({mount:()=>{var c=h.createNode(a,"fd",16895,73);return c.node_ops={lookup:(p,f)=>{var T=+f,y=h.getStreamChecked(T),b={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>y.path}};return b.parent=b,b}},c}},{},"/proc/self/fd")},createStandardStreams:()=>{o.stdin?h.createDevice("/dev","stdin",o.stdin):h.symlink("/dev/tty","/dev/stdin"),o.stdout?h.createDevice("/dev","stdout",null,o.stdout):h.symlink("/dev/tty","/dev/stdout"),o.stderr?h.createDevice("/dev","stderr",null,o.stderr):h.symlink("/dev/tty1","/dev/stderr"),h.open("/dev/stdin",0),h.open("/dev/stdout",1),h.open("/dev/stderr",1)},ensureErrnoError:()=>{h.ErrnoError||(h.ErrnoError=function(a,c){this.name="ErrnoError",this.node=c,this.setErrno=function(p){this.errno=p},this.setErrno(a),this.message="FS error"},h.ErrnoError.prototype=new Error,h.ErrnoError.prototype.constructor=h.ErrnoError,[44].forEach(a=>{h.genericErrors[a]=new h.ErrnoError(a),h.genericErrors[a].stack="<generic error, no stack>"}))},staticInit:()=>{h.ensureErrnoError(),h.nameTable=new Array(4096),h.mount(Se,{},"/"),h.createDefaultDirectories(),h.createDefaultDevices(),h.createSpecialDirectories(),h.filesystems={MEMFS:Se}},init:(a,c,p)=>{h.init.initialized=!0,h.ensureErrnoError(),o.stdin=a||o.stdin,o.stdout=c||o.stdout,o.stderr=p||o.stderr,h.createStandardStreams()},quit:()=>{h.init.initialized=!1;for(var a=0;a<h.streams.length;a++){var c=h.streams[a];c&&h.close(c)}},findObject:(a,c)=>{var p=h.analyzePath(a,c);return p.exists?p.object:null},analyzePath:(a,c)=>{try{a=(f=h.lookupPath(a,{follow:!c})).path}catch(T){}var p={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var f=h.lookupPath(a,{parent:!0});p.parentExists=!0,p.parentPath=f.path,p.parentObject=f.node,p.name=ce.basename(a),f=h.lookupPath(a,{follow:!c}),p.exists=!0,p.path=f.path,p.object=f.node,p.name=f.node.name,p.isRoot=f.path==="/"}catch(T){p.error=T.errno}return p},createPath:(a,c,p,f)=>{a=typeof a=="string"?a:h.getPath(a);for(var T=c.split("/").reverse();T.length;){var y=T.pop();if(y){var b=ce.join2(a,y);try{h.mkdir(b)}catch(R){}a=b}}return b},createFile:(a,c,p,f,T)=>{var y=ce.join2(typeof a=="string"?a:h.getPath(a),c),b=Xr(f,T);return h.create(y,b)},createDataFile:(a,c,p,f,T,y)=>{var b=c;a&&(a=typeof a=="string"?a:h.getPath(a),b=c?ce.join2(a,c):a);var R=Xr(f,T),O=h.create(b,R);if(p){if(typeof p=="string"){for(var w=new Array(p.length),z=0,te=p.length;z<te;++z)w[z]=p.charCodeAt(z);p=w}h.chmod(O,146|R);var re=h.open(O,577);h.write(re,p,0,p.length,0,y),h.close(re),h.chmod(O,R)}return O},createDevice:(a,c,p,f)=>{var T=ce.join2(typeof a=="string"?a:h.getPath(a),c),y=Xr(!!p,!!f);h.createDevice.major||(h.createDevice.major=64);var b=h.makedev(h.createDevice.major++,0);return h.registerDevice(b,{open:R=>{R.seekable=!1},close:R=>{f&&f.buffer&&f.buffer.length&&f(10)},read:(R,O,w,z,te)=>{for(var re=0,ee=0;ee<z;ee++){var Re;try{Re=p()}catch(Ve){throw new h.ErrnoError(29)}if(Re===void 0&&re===0)throw new h.ErrnoError(6);if(Re==null)break;re++,O[w+ee]=Re}return re&&(R.node.timestamp=Date.now()),re},write:(R,O,w,z,te)=>{for(var re=0;re<z;re++)try{f(O[w+re])}catch(ee){throw new h.ErrnoError(29)}return z&&(R.node.timestamp=Date.now()),re}}),h.mkdev(T,y,b)},forceLoadFile:a=>{if(a.isDevice||a.isFolder||a.link||a.contents)return!0;if(typeof XMLHttpRequest!="undefined")throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");if(!s)throw new Error("Cannot load without read() or XMLHttpRequest.");try{a.contents=ns(s(a.url),!0),a.usedBytes=a.contents.length}catch(c){throw new h.ErrnoError(29)}},createLazyFile:(a,c,p,f,T)=>{function y(){this.lengthKnown=!1,this.chunks=[]}if(y.prototype.get=function(te){if(!(te>this.length-1||te<0)){var re=te%this.chunkSize,ee=te/this.chunkSize|0;return this.getter(ee)[re]}},y.prototype.setDataGetter=function(te){this.getter=te},y.prototype.cacheLength=function(){var te=new XMLHttpRequest;if(te.open("HEAD",p,!1),te.send(null),!(te.status>=200&&te.status<300||te.status===304))throw new Error("Couldn't load "+p+". Status: "+te.status);var re,ee=Number(te.getResponseHeader("Content-length")),Re=(re=te.getResponseHeader("Accept-Ranges"))&&re==="bytes",Ve=(re=te.getResponseHeader("Content-Encoding"))&&re==="gzip",we=1048576;Re||(we=ee);var rt=this;rt.setDataGetter(Ye=>{var ht=Ye*we,xi=(Ye+1)*we-1;if(xi=Math.min(xi,ee-1),rt.chunks[Ye]===void 0&&(rt.chunks[Ye]=((nr,bo)=>{if(nr>bo)throw new Error("invalid range ("+nr+", "+bo+") or no bytes requested!");if(bo>ee-1)throw new Error("only "+ee+" bytes available! programmer error!");var ct=new XMLHttpRequest;if(ct.open("GET",p,!1),ee!==we&&ct.setRequestHeader("Range","bytes="+nr+"-"+bo),ct.responseType="arraybuffer",ct.overrideMimeType&&ct.overrideMimeType("text/plain; charset=x-user-defined"),ct.send(null),!(ct.status>=200&&ct.status<300||ct.status===304))throw new Error("Couldn't load "+p+". Status: "+ct.status);return ct.response!==void 0?new Uint8Array(ct.response||[]):ns(ct.responseText||"",!0)})(ht,xi)),rt.chunks[Ye]===void 0)throw new Error("doXHR failed!");return rt.chunks[Ye]}),!Ve&&ee||(we=ee=1,ee=this.getter(0).length,we=ee,x("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=ee,this._chunkSize=we,this.lengthKnown=!0},typeof XMLHttpRequest!="undefined"){if(!_)throw"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";var b=new y;Object.defineProperties(b,{length:{get:function(){return this.lengthKnown||this.cacheLength(),this._length}},chunkSize:{get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}});var R={isDevice:!1,contents:b}}else R={isDevice:!1,url:p};var O=h.createFile(a,c,R,f,T);R.contents?O.contents=R.contents:R.url&&(O.contents=null,O.url=R.url),Object.defineProperties(O,{usedBytes:{get:function(){return this.contents.length}}});var w={};function z(te,re,ee,Re,Ve){var we=te.node.contents;if(Ve>=we.length)return 0;var rt=Math.min(we.length-Ve,Re);if(we.slice)for(var Ye=0;Ye<rt;Ye++)re[ee+Ye]=we[Ve+Ye];else for(Ye=0;Ye<rt;Ye++)re[ee+Ye]=we.get(Ve+Ye);return rt}return Object.keys(O.stream_ops).forEach(te=>{var re=O.stream_ops[te];w[te]=function(){return h.forceLoadFile(O),re.apply(null,arguments)}}),w.read=(te,re,ee,Re,Ve)=>(h.forceLoadFile(O),z(te,re,ee,Re,Ve)),w.mmap=(te,re,ee,Re,Ve)=>{h.forceLoadFile(O);var we=dn();if(!we)throw new h.ErrnoError(48);return z(te,se,we,re,ee),{ptr:we,allocated:!0}},O.stream_ops=w,O}},Ri=(a,c)=>a?Mt(ne,a,c):"",_t={DEFAULT_POLLMASK:5,calculateAt:function(a,c,p){if(ce.isAbs(c))return c;var f;if(a===-100?f=h.cwd():f=_t.getStreamFromFD(a).path,c.length==0){if(!p)throw new h.ErrnoError(44);return f}return ce.join2(f,c)},doStat:function(a,c,p){try{var f=a(c)}catch(R){if(R&&R.node&&ce.normalize(c)!==ce.normalize(h.getPath(R.node)))return-54;throw R}Pe[p>>2]=f.dev,Pe[p+4>>2]=f.mode,Le[p+8>>2]=f.nlink,Pe[p+12>>2]=f.uid,Pe[p+16>>2]=f.gid,Pe[p+20>>2]=f.rdev,Qe=[f.size>>>0,(fe=f.size,+Math.abs(fe)>=1?fe>0?+Math.floor(fe/4294967296)>>>0:~~+Math.ceil((fe-+(~~fe>>>0))/4294967296)>>>0:0)],Pe[p+24>>2]=Qe[0],Pe[p+28>>2]=Qe[1],Pe[p+32>>2]=4096,Pe[p+36>>2]=f.blocks;var T=f.atime.getTime(),y=f.mtime.getTime(),b=f.ctime.getTime();return Qe=[Math.floor(T/1e3)>>>0,(fe=Math.floor(T/1e3),+Math.abs(fe)>=1?fe>0?+Math.floor(fe/4294967296)>>>0:~~+Math.ceil((fe-+(~~fe>>>0))/4294967296)>>>0:0)],Pe[p+40>>2]=Qe[0],Pe[p+44>>2]=Qe[1],Le[p+48>>2]=T%1e3*1e3,Qe=[Math.floor(y/1e3)>>>0,(fe=Math.floor(y/1e3),+Math.abs(fe)>=1?fe>0?+Math.floor(fe/4294967296)>>>0:~~+Math.ceil((fe-+(~~fe>>>0))/4294967296)>>>0:0)],Pe[p+56>>2]=Qe[0],Pe[p+60>>2]=Qe[1],Le[p+64>>2]=y%1e3*1e3,Qe=[Math.floor(b/1e3)>>>0,(fe=Math.floor(b/1e3),+Math.abs(fe)>=1?fe>0?+Math.floor(fe/4294967296)>>>0:~~+Math.ceil((fe-+(~~fe>>>0))/4294967296)>>>0:0)],Pe[p+72>>2]=Qe[0],Pe[p+76>>2]=Qe[1],Le[p+80>>2]=b%1e3*1e3,Qe=[f.ino>>>0,(fe=f.ino,+Math.abs(fe)>=1?fe>0?+Math.floor(fe/4294967296)>>>0:~~+Math.ceil((fe-+(~~fe>>>0))/4294967296)>>>0:0)],Pe[p+88>>2]=Qe[0],Pe[p+92>>2]=Qe[1],0},doMsync:function(a,c,p,f,T){if(!h.isFile(c.node.mode))throw new h.ErrnoError(43);if(2&f)return 0;var y=ne.slice(a,a+p);h.msync(c,y,T,p,f)},varargs:void 0,get:()=>(_t.varargs+=4,Pe[_t.varargs-4>>2]),getStr:a=>Ri(a),getStreamFromFD:function(a){return h.getStreamChecked(a)}};function Qr(a){switch(a){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError(`Unknown type size: ${a}`)}}var La=void 0;function St(a){for(var c="",p=a;ne[p];)c+=La[ne[p++]];return c}var vi={},sr={},as={},Ci=void 0;function Ue(a){throw new Ci(a)}var Ua=void 0;function Qt(a){throw new Ua(a)}function Mr(a,c,p){function f(R){var O=p(R);O.length!==a.length&&Qt("Mismatched type converter count");for(var w=0;w<a.length;++w)Yt(a[w],O[w])}a.forEach(function(R){as[R]=c});var T=new Array(c.length),y=[],b=0;c.forEach((R,O)=>{sr.hasOwnProperty(R)?T[O]=sr[R]:(y.push(R),vi.hasOwnProperty(R)||(vi[R]=[]),vi[R].push(()=>{T[O]=sr[R],++b===y.length&&f(T)}))}),y.length===0&&f(T)}function Yt(a,c,p={}){if(!("argPackAdvance"in c))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(f,T,y={}){var b=T.name;if(f||Ue(`type "${b}" must have a positive integer typeid pointer`),sr.hasOwnProperty(f)){if(y.ignoreDuplicateRegistrations)return;Ue(`Cannot register type '${b}' twice`)}if(sr[f]=T,delete as[f],vi.hasOwnProperty(f)){var R=vi[f];delete vi[f],R.forEach(O=>O())}}(a,c,p)}function Va(a){if(!(this instanceof mr)||!(a instanceof mr))return!1;for(var c=this.$$.ptrType.registeredClass,p=this.$$.ptr,f=a.$$.ptrType.registeredClass,T=a.$$.ptr;c.baseClass;)p=c.upcast(p),c=c.baseClass;for(;f.baseClass;)T=f.upcast(T),f=f.baseClass;return c===f&&p===T}function un(a){Ue(a.$$.ptrType.registeredClass.name+" instance already deleted")}var Eo=!1;function Fa(a){}function $a(a){a.count.value-=1,a.count.value===0&&function(c){c.smartPtr?c.smartPtrType.rawDestructor(c.smartPtr):c.ptrType.registeredClass.rawDestructor(c.ptr)}(a)}function Ba(a,c,p){if(c===p)return a;if(p.baseClass===void 0)return null;var f=Ba(a,c,p.baseClass);return f===null?null:p.downcast(f)}var _o={};function Au(){return Object.keys(Io).length}function bu(){var a=[];for(var c in Io)Io.hasOwnProperty(c)&&a.push(Io[c]);return a}var To=[];function Zt(){for(;To.length;){var a=To.pop();a.$$.deleteScheduled=!1,a.delete()}}var Or=void 0;function Ha(a){Or=a,To.length&&Or&&Or(Zt)}var Io={};function Di(a,c){return c=function(p,f){for(f===void 0&&Ue("ptr should not be undefined");p.baseClass;)f=p.upcast(f),p=p.baseClass;return f}(a,c),Io[c]}function So(a,c){return c.ptrType&&c.ptr||Qt("makeClassHandle requires ptr and ptrType"),!!c.smartPtrType!=!!c.smartPtr&&Qt("Both smartPtrType and smartPtr must be specified"),c.count={value:1},Ni(Object.create(a,{$$:{value:c}}))}function Wa(a){var c=this.getPointee(a);if(!c)return this.destructor(a),null;var p=Di(this.registeredClass,c);if(p!==void 0){if(p.$$.count.value===0)return p.$$.ptr=c,p.$$.smartPtr=a,p.clone();var f=p.clone();return this.destructor(a),f}function T(){return this.isSmartPointer?So(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:c,smartPtrType:this,smartPtr:a}):So(this.registeredClass.instancePrototype,{ptrType:this,ptr:a})}var y,b=this.registeredClass.getActualType(c),R=_o[b];if(!R)return T.call(this);y=this.isConst?R.constPointerType:R.pointerType;var O=Ba(c,this.registeredClass,y.registeredClass);return O===null?T.call(this):this.isSmartPointer?So(y.registeredClass.instancePrototype,{ptrType:y,ptr:O,smartPtrType:this,smartPtr:a}):So(y.registeredClass.instancePrototype,{ptrType:y,ptr:O})}var Ni=function(a){return typeof FinalizationRegistry=="undefined"?(Ni=c=>c,a):(Eo=new FinalizationRegistry(c=>{$a(c.$$)}),Fa=c=>Eo.unregister(c),(Ni=c=>{var p=c.$$;if(p.smartPtr){var f={$$:p};Eo.register(c,f,c)}return c})(a))};function Ga(){if(this.$$.ptr||un(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var a,c=Ni(Object.create(Object.getPrototypeOf(this),{$$:{value:(a=this.$$,{count:a.count,deleteScheduled:a.deleteScheduled,preservePointerOnDelete:a.preservePointerOnDelete,ptr:a.ptr,ptrType:a.ptrType,smartPtr:a.smartPtr,smartPtrType:a.smartPtrType})}}));return c.$$.count.value+=1,c.$$.deleteScheduled=!1,c}function Ru(){this.$$.ptr||un(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Ue("Object already scheduled for deletion"),Fa(this),$a(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function ja(){return!this.$$.ptr}function qa(){return this.$$.ptr||un(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Ue("Object already scheduled for deletion"),To.push(this),To.length===1&&Or&&Or(Zt),this.$$.deleteScheduled=!0,this}function mr(){}function Ot(a){if(a===void 0)return"_unknown";var c=(a=a.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return c>=48&&c<=57?`_${a}`:a}function cs(a,c){return a=Ot(a),{[a]:function(){return c.apply(this,arguments)}}[a]}function za(a,c,p){if(a[c].overloadTable===void 0){var f=a[c];a[c]=function(){return a[c].overloadTable.hasOwnProperty(arguments.length)||Ue(`Function '${p}' called with an invalid number of arguments (${arguments.length}) - expects one of (${a[c].overloadTable})!`),a[c].overloadTable[arguments.length].apply(this,arguments)},a[c].overloadTable=[],a[c].overloadTable[f.argCount]=f}}function ds(a,c,p,f,T,y,b,R){this.name=a,this.constructor=c,this.instancePrototype=p,this.rawDestructor=f,this.baseClass=T,this.getActualType=y,this.upcast=b,this.downcast=R,this.pureVirtualFunctions=[]}function yo(a,c,p){for(;c!==p;)c.upcast||Ue(`Expected null or instance of ${p.name}, got an instance of ${c.name}`),a=c.upcast(a),c=c.baseClass;return a}function vu(a,c){if(c===null)return this.isReference&&Ue(`null is not a valid ${this.name}`),0;c.$$||Ue(`Cannot pass "${ps(c)}" as a ${this.name}`),c.$$.ptr||Ue(`Cannot pass deleted object as a pointer of type ${this.name}`);var p=c.$$.ptrType.registeredClass;return yo(c.$$.ptr,p,this.registeredClass)}function Cu(a,c){var p;if(c===null)return this.isReference&&Ue(`null is not a valid ${this.name}`),this.isSmartPointer?(p=this.rawConstructor(),a!==null&&a.push(this.rawDestructor,p),p):0;c.$$||Ue(`Cannot pass "${ps(c)}" as a ${this.name}`),c.$$.ptr||Ue(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&c.$$.ptrType.isConst&&Ue(`Cannot convert argument of type ${c.$$.smartPtrType?c.$$.smartPtrType.name:c.$$.ptrType.name} to parameter type ${this.name}`);var f=c.$$.ptrType.registeredClass;if(p=yo(c.$$.ptr,f,this.registeredClass),this.isSmartPointer)switch(c.$$.smartPtr===void 0&&Ue("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:c.$$.smartPtrType===this?p=c.$$.smartPtr:Ue(`Cannot convert argument of type ${c.$$.smartPtrType?c.$$.smartPtrType.name:c.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:p=c.$$.smartPtr;break;case 2:if(c.$$.smartPtrType===this)p=c.$$.smartPtr;else{var T=c.clone();p=this.rawShare(p,Oi.toHandle(function(){T.delete()})),a!==null&&a.push(this.rawDestructor,p)}break;default:Ue("Unsupporting sharing policy")}return p}function Ja(a,c){if(c===null)return this.isReference&&Ue(`null is not a valid ${this.name}`),0;c.$$||Ue(`Cannot pass "${ps(c)}" as a ${this.name}`),c.$$.ptr||Ue(`Cannot pass deleted object as a pointer of type ${this.name}`),c.$$.ptrType.isConst&&Ue(`Cannot convert argument of type ${c.$$.ptrType.name} to parameter type ${this.name}`);var p=c.$$.ptrType.registeredClass;return yo(c.$$.ptr,p,this.registeredClass)}function Ao(a){return this.fromWireType(Pe[a>>2])}function Du(a){return this.rawGetPointee&&(a=this.rawGetPointee(a)),a}function Xa(a){this.rawDestructor&&this.rawDestructor(a)}function Nu(a){a!==null&&a.delete()}function pr(a,c,p,f,T,y,b,R,O,w,z){this.name=a,this.registeredClass=c,this.isReference=p,this.isConst=f,this.isSmartPointer=T,this.pointeeType=y,this.sharingPolicy=b,this.rawGetPointee=R,this.rawConstructor=O,this.rawShare=w,this.rawDestructor=z,T||c.baseClass!==void 0?this.toWireType=Cu:f?(this.toWireType=vu,this.destructorFunction=null):(this.toWireType=Ja,this.destructorFunction=null)}var us=[],Qa=a=>{var c=us[a];return c||(a>=us.length&&(us.length=a+1),us[a]=c=sn.get(a)),c},wu=(a,c,p)=>a.includes("j")?((f,T,y)=>{var b=o["dynCall_"+f];return y&&y.length?b.apply(null,[T].concat(y)):b.call(null,T)})(a,c,p):Qa(c).apply(null,p);function wi(a,c){var p,f,T,y=(a=St(a)).includes("j")?(p=a,f=c,T=[],function(){return T.length=0,Object.assign(T,arguments),wu(p,f,T)}):Qa(c);return typeof y!="function"&&Ue(`unknown function pointer with signature ${a}: ${c}`),y}var Ya=void 0;function ls(a){var c=fr(a),p=St(c);return yt(c),p}function ms(a,c){var p=[],f={};throw c.forEach(function T(y){f[y]||sr[y]||(as[y]?as[y].forEach(T):(p.push(y),f[y]=!0))}),new Ya(`${a}: `+p.map(ls).join([", "]))}function ln(a,c){for(var p=[],f=0;f<a;f++)p.push(Le[c+4*f>>2]);return p}function Za(a){for(;a.length;){var c=a.pop();a.pop()(c)}}function mn(a,c){if(!(a instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof a} which is not a function`);var p=cs(a.name||"unknownFunctionName",function(){});p.prototype=a.prototype;var f=new p,T=a.apply(f,c);return T instanceof Object?T:f}function Mi(a,c,p,f,T,y){var b=c.length;b<2&&Ue("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var R=c[1]!==null&&p!==null,O=!1,w=1;w<c.length;++w)if(c[w]!==null&&c[w].destructorFunction===void 0){O=!0;break}var z=c[0].name!=="void",te="",re="";for(w=0;w<b-2;++w)te+=(w!==0?", ":"")+"arg"+w,re+=(w!==0?", ":"")+"arg"+w+"Wired";var ee=`
|
|
52
|
+
return function ${Ot(a)}(${te}) {
|
|
53
|
+
if (arguments.length !== ${b-2}) {
|
|
54
|
+
throwBindingError('function ${a} called with ${arguments.length} arguments, expected ${b-2} args!');
|
|
55
|
+
}`;O&&(ee+=`var destructors = [];
|
|
56
|
+
`);var Re=O?"destructors":"null",Ve=["throwBindingError","invoker","fn","runDestructors","retType","classParam"],we=[Ue,f,T,Za,c[0],c[1]];for(R&&(ee+="var thisWired = classParam.toWireType("+Re+`, this);
|
|
57
|
+
`),w=0;w<b-2;++w)ee+="var arg"+w+"Wired = argType"+w+".toWireType("+Re+", arg"+w+"); // "+c[w+2].name+`
|
|
58
|
+
`,Ve.push("argType"+w),we.push(c[w+2]);if(R&&(re="thisWired"+(re.length>0?", ":"")+re),ee+=(z||y?"var rv = ":"")+"invoker(fn"+(re.length>0?", ":"")+re+`);
|
|
59
|
+
`,O)ee+=`runDestructors(destructors);
|
|
60
|
+
`;else for(w=R?1:2;w<c.length;++w){var rt=w===1?"thisWired":"arg"+(w-2)+"Wired";c[w].destructorFunction!==null&&(ee+=rt+"_dtor("+rt+"); // "+c[w].name+`
|
|
61
|
+
`,Ve.push(rt+"_dtor"),we.push(c[w].destructorFunction))}return z&&(ee+=`var ret = retType.fromWireType(rv);
|
|
62
|
+
return ret;
|
|
63
|
+
`),ee+=`}
|
|
64
|
+
`,Ve.push(ee),mn(Function,Ve).apply(null,we)}function Ka(){this.allocated=[void 0],this.freelist=[]}var Pt=new Ka;function ec(a){a>=Pt.reserved&&--Pt.get(a).refcount==0&&Pt.free(a)}function hr(){for(var a=0,c=Pt.reserved;c<Pt.allocated.length;++c)Pt.allocated[c]!==void 0&&++a;return a}var Oi={toValue:a=>(a||Ue("Cannot use deleted val. handle = "+a),Pt.get(a).value),toHandle:a=>{switch(a){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return Pt.allocate({refcount:1,value:a})}}};function ps(a){if(a===null)return"null";var c=typeof a;return c==="object"||c==="array"||c==="function"?a.toString():""+a}function tc(a,c){switch(c){case 2:return function(p){return this.fromWireType(po[p>>2])};case 3:return function(p){return this.fromWireType(on[p>>3])};default:throw new TypeError("Unknown float type: "+a)}}function rc(a,c,p){switch(c){case 0:return p?function(f){return se[f]}:function(f){return ne[f]};case 1:return p?function(f){return Ae[f>>1]}:function(f){return ie[f>>1]};case 2:return p?function(f){return Pe[f>>2]}:function(f){return Le[f>>2]};default:throw new TypeError("Unknown integer type: "+a)}}var I=typeof TextDecoder!="undefined"?new TextDecoder("utf-16le"):void 0,E=(a,c)=>{for(var p=a,f=p>>1,T=f+c/2;!(f>=T)&&ie[f];)++f;if((p=f<<1)-a>32&&I)return I.decode(ne.subarray(a,p));for(var y="",b=0;!(b>=c/2);++b){var R=Ae[a+2*b>>1];if(R==0)break;y+=String.fromCharCode(R)}return y},C=(a,c,p)=>{if(p===void 0&&(p=2147483647),p<2)return 0;for(var f=c,T=(p-=2)<2*a.length?p/2:a.length,y=0;y<T;++y){var b=a.charCodeAt(y);Ae[c>>1]=b,c+=2}return Ae[c>>1]=0,c-f},D=a=>2*a.length,k=(a,c)=>{for(var p=0,f="";!(p>=c/4);){var T=Pe[a+4*p>>2];if(T==0)break;if(++p,T>=65536){var y=T-65536;f+=String.fromCharCode(55296|y>>10,56320|1023&y)}else f+=String.fromCharCode(T)}return f},$=(a,c,p)=>{if(p===void 0&&(p=2147483647),p<4)return 0;for(var f=c,T=f+p-4,y=0;y<a.length;++y){var b=a.charCodeAt(y);if(b>=55296&&b<=57343&&(b=65536+((1023&b)<<10)|1023&a.charCodeAt(++y)),Pe[c>>2]=b,(c+=4)+4>T)break}return Pe[c>>2]=0,c-f},H=a=>{for(var c=0,p=0;p<a.length;++p){var f=a.charCodeAt(p);f>=55296&&f<=57343&&++p,c+=4}return c},j={},Q=[],B=[],ue={},De=()=>{if(!De.strings){var a={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:l||"./this.program"};for(var c in ue)ue[c]===void 0?delete a[c]:a[c]=ue[c];var p=[];for(var c in a)p.push(`${c}=${a[c]}`);De.strings=p}return De.strings},be,he,Ne,tt=function(a,c,p,f){a||(a=this),this.parent=a,this.mount=a.mount,this.mounted=null,this.id=h.nextInode++,this.name=c,this.mode=p,this.node_ops={},this.stream_ops={},this.rdev=f},qe=365,lt=146;Object.defineProperties(tt.prototype,{read:{get:function(){return(this.mode&qe)===qe},set:function(a){a?this.mode|=qe:this.mode&=-366}},write:{get:function(){return(this.mode<)===lt},set:function(a){a?this.mode|=lt:this.mode&=-147}},isFolder:{get:function(){return h.isDir(this.mode)}},isDevice:{get:function(){return h.isChrdev(this.mode)}}}),h.FSNode=tt,h.createPreloadedFile=function(a,c,p,f,T,y,b,R,O,w){var z=c?qt.resolve(ce.join2(a,c)):a;function te(re){function ee(Re){w&&w(),R||h.createDataFile(a,c,Re,f,T,O),y&&y(),ho()}(function(Re,Ve,we,rt){typeof Browser!="undefined"&&Browser.init();var Ye=!1;return yu.forEach(function(ht){Ye||ht.canHandle(Ve)&&(ht.handle(Re,Ve,we,rt),Ye=!0)}),Ye})(re,z,ee,()=>{b&&b(),ho()})||ee(re)}ss(),typeof p=="string"?Su(p,re=>te(re),b):te(p)},h.staticInit(),function(){for(var a=new Array(256),c=0;c<256;++c)a[c]=String.fromCharCode(c);La=a}(),Ci=o.BindingError=class extends Error{constructor(a){super(a),this.name="BindingError"}},Ua=o.InternalError=class extends Error{constructor(a){super(a),this.name="InternalError"}},mr.prototype.isAliasOf=Va,mr.prototype.clone=Ga,mr.prototype.delete=Ru,mr.prototype.isDeleted=ja,mr.prototype.deleteLater=qa,o.getInheritedInstanceCount=Au,o.getLiveInheritedInstances=bu,o.flushPendingDeletes=Zt,o.setDelayFunction=Ha,pr.prototype.getPointee=Du,pr.prototype.destructor=Xa,pr.prototype.argPackAdvance=8,pr.prototype.readValueFromPointer=Ao,pr.prototype.deleteObject=Nu,pr.prototype.fromWireType=Wa,Ya=o.UnboundTypeError=(be=Error,(Ne=cs(he="UnboundTypeError",function(a){this.name=he,this.message=a;var c=new Error(a).stack;c!==void 0&&(this.stack=this.toString()+`
|
|
65
|
+
`+c.replace(/^Error(:[^\n]*)?\n/,""))})).prototype=Object.create(be.prototype),Ne.prototype.constructor=Ne,Ne.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},Ne),Object.assign(Ka.prototype,{get(a){return this.allocated[a]},has(a){return this.allocated[a]!==void 0},allocate(a){var c=this.freelist.pop()||this.allocated.length;return this.allocated[c]=a,c},free(a){this.allocated[a]=void 0,this.freelist.push(a)}}),Pt.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),Pt.reserved=Pt.allocated.length,o.count_emval_handles=hr;var ze,Ct={p:function(a,c,p){throw new Ai(a).init(c,p),a},C:function(a,c,p){_t.varargs=p;try{var f=_t.getStreamFromFD(a);switch(c){case 0:return(T=_t.get())<0?-28:h.createStream(f,T).fd;case 1:case 2:case 6:case 7:return 0;case 3:return f.flags;case 4:var T=_t.get();return f.flags|=T,0;case 5:return T=_t.get(),Ae[T+0>>1]=2,0;case 16:case 8:default:return-28;case 9:return y=28,Pe[pn()>>2]=y,-1}}catch(b){if(h===void 0||b.name!=="ErrnoError")throw b;return-b.errno}var y},w:function(a,c,p,f){_t.varargs=f;try{c=_t.getStr(c),c=_t.calculateAt(a,c);var T=f?_t.get():0;return h.open(c,p,T).fd}catch(y){if(h===void 0||y.name!=="ErrnoError")throw y;return-y.errno}},t:function(a,c,p,f,T){},n:function(a,c,p,f,T){var y=Qr(p);Yt(a,{name:c=St(c),fromWireType:function(b){return!!b},toWireType:function(b,R){return R?f:T},argPackAdvance:8,readValueFromPointer:function(b){var R;if(p===1)R=se;else if(p===2)R=Ae;else{if(p!==4)throw new TypeError("Unknown boolean type size: "+c);R=Pe}return this.fromWireType(R[b>>y])},destructorFunction:null})},r:function(a,c,p,f,T,y,b,R,O,w,z,te,re){z=St(z),y=wi(T,y),R&&(R=wi(b,R)),w&&(w=wi(O,w)),re=wi(te,re);var ee=Ot(z);(function(Re,Ve,we){o.hasOwnProperty(Re)?((we===void 0||o[Re].overloadTable!==void 0&&o[Re].overloadTable[we]!==void 0)&&Ue(`Cannot register public name '${Re}' twice`),za(o,Re,Re),o.hasOwnProperty(we)&&Ue(`Cannot register multiple overloads of a function with the same number of arguments (${we})!`),o[Re].overloadTable[we]=Ve):(o[Re]=Ve,we!==void 0&&(o[Re].numArguments=we))})(ee,function(){ms(`Cannot construct ${z} due to unbound types`,[f])}),Mr([a,c,p],f?[f]:[],function(Re){var Ve,we;Re=Re[0],we=f?(Ve=Re.registeredClass).instancePrototype:mr.prototype;var rt=cs(ee,function(){if(Object.getPrototypeOf(this)!==Ye)throw new Ci("Use 'new' to construct "+z);if(ht.constructor_body===void 0)throw new Ci(z+" has no accessible constructor");var ct=ht.constructor_body[arguments.length];if(ct===void 0)throw new Ci(`Tried to invoke ctor of ${z} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(ht.constructor_body).toString()}) parameters instead!`);return ct.apply(this,arguments)}),Ye=Object.create(we,{constructor:{value:rt}});rt.prototype=Ye;var ht=new ds(z,rt,Ye,re,Ve,y,R,w);ht.baseClass&&(ht.baseClass.__derivedClasses===void 0&&(ht.baseClass.__derivedClasses=[]),ht.baseClass.__derivedClasses.push(ht));var xi=new pr(z,ht,!0,!1,!1),nr=new pr(z+"*",ht,!1,!1,!1),bo=new pr(z+" const*",ht,!1,!0,!1);return _o[a]={pointerType:nr,constPointerType:bo},function(ct,vp,Mu){o.hasOwnProperty(ct)||Qt("Replacing nonexistant public symbol"),o[ct].overloadTable!==void 0&&Mu!==void 0?o[ct].overloadTable[Mu]=vp:(o[ct]=vp,o[ct].argCount=Mu)}(ee,rt),[xi,nr,bo]})},q:function(a,c,p,f,T,y){var b=ln(c,p);T=wi(f,T),Mr([],[a],function(R){var O=`constructor ${(R=R[0]).name}`;if(R.registeredClass.constructor_body===void 0&&(R.registeredClass.constructor_body=[]),R.registeredClass.constructor_body[c-1]!==void 0)throw new Ci(`Cannot register multiple constructors with identical number of parameters (${c-1}) for class '${R.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return R.registeredClass.constructor_body[c-1]=()=>{ms(`Cannot construct ${R.name} due to unbound types`,b)},Mr([],b,function(w){return w.splice(1,0,null),R.registeredClass.constructor_body[c-1]=Mi(O,w,null,T,y),[]}),[]})},d:function(a,c,p,f,T,y,b,R,O){var w=ln(p,f);c=St(c),y=wi(T,y),Mr([],[a],function(z){var te=`${(z=z[0]).name}.${c}`;function re(){ms(`Cannot call ${te} due to unbound types`,w)}c.startsWith("@@")&&(c=Symbol[c.substring(2)]),R&&z.registeredClass.pureVirtualFunctions.push(c);var ee=z.registeredClass.instancePrototype,Re=ee[c];return Re===void 0||Re.overloadTable===void 0&&Re.className!==z.name&&Re.argCount===p-2?(re.argCount=p-2,re.className=z.name,ee[c]=re):(za(ee,c,te),ee[c].overloadTable[p-2]=re),Mr([],w,function(Ve){var we=Mi(te,Ve,z,y,b,O);return ee[c].overloadTable===void 0?(we.argCount=p-2,ee[c]=we):ee[c].overloadTable[p-2]=we,[]}),[]})},D:function(a,c){Yt(a,{name:c=St(c),fromWireType:function(p){var f=Oi.toValue(p);return ec(p),f},toWireType:function(p,f){return Oi.toHandle(f)},argPackAdvance:8,readValueFromPointer:Ao,destructorFunction:null})},k:function(a,c,p){var f=Qr(p);Yt(a,{name:c=St(c),fromWireType:function(T){return T},toWireType:function(T,y){return y},argPackAdvance:8,readValueFromPointer:tc(c,f),destructorFunction:null})},c:function(a,c,p,f,T){c=St(c),T===-1&&(T=4294967295);var y=Qr(p),b=w=>w;if(f===0){var R=32-8*p;b=w=>w<<R>>>R}var O=c.includes("unsigned");Yt(a,{name:c,fromWireType:b,toWireType:O?function(w,z){return this.name,z>>>0}:function(w,z){return this.name,z},argPackAdvance:8,readValueFromPointer:rc(c,y,f!==0),destructorFunction:null})},b:function(a,c,p){var f=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][c];function T(y){var b=Le,R=b[y>>=2],O=b[y+1];return new f(b.buffer,O,R)}Yt(a,{name:p=St(p),fromWireType:T,argPackAdvance:8,readValueFromPointer:T},{ignoreDuplicateRegistrations:!0})},j:function(a,c){var p=(c=St(c))==="std::string";Yt(a,{name:c,fromWireType:function(f){var T,y=Le[f>>2],b=f+4;if(p)for(var R=b,O=0;O<=y;++O){var w=b+O;if(O==y||ne[w]==0){var z=Ri(R,w-R);T===void 0?T=z:(T+="\0",T+=z),R=w+1}}else{var te=new Array(y);for(O=0;O<y;++O)te[O]=String.fromCharCode(ne[b+O]);T=te.join("")}return yt(f),T},toWireType:function(f,T){var y;T instanceof ArrayBuffer&&(T=new Uint8Array(T));var b=typeof T=="string";b||T instanceof Uint8Array||T instanceof Uint8ClampedArray||T instanceof Int8Array||Ue("Cannot pass non-string to std::string"),y=p&&b?fo(T):T.length;var R=Pi(4+y+1),O=R+4;if(Le[R>>2]=y,p&&b)go(T,ne,O,y+1);else if(b)for(var w=0;w<y;++w){var z=T.charCodeAt(w);z>255&&(yt(O),Ue("String has UTF-16 code units that do not fit in 8 bits")),ne[O+w]=z}else for(w=0;w<y;++w)ne[O+w]=T[w];return f!==null&&f.push(yt,R),R},argPackAdvance:8,readValueFromPointer:Ao,destructorFunction:function(f){yt(f)}})},f:function(a,c,p){var f,T,y,b,R;p=St(p),c===2?(f=E,T=C,b=D,y=()=>ie,R=1):c===4&&(f=k,T=$,b=H,y=()=>Le,R=2),Yt(a,{name:p,fromWireType:function(O){for(var w,z=Le[O>>2],te=y(),re=O+4,ee=0;ee<=z;++ee){var Re=O+4+ee*c;if(ee==z||te[Re>>R]==0){var Ve=f(re,Re-re);w===void 0?w=Ve:(w+="\0",w+=Ve),re=Re+c}}return yt(O),w},toWireType:function(O,w){typeof w!="string"&&Ue(`Cannot pass non-string to C++ string type ${p}`);var z=b(w),te=Pi(4+z+c);return Le[te>>2]=z>>R,T(w,te+4,z+c),O!==null&&O.push(yt,te),te},argPackAdvance:8,readValueFromPointer:Ao,destructorFunction:function(O){yt(O)}})},o:function(a,c){Yt(a,{isVoid:!0,name:c=St(c),argPackAdvance:0,fromWireType:function(){},toWireType:function(p,f){}})},g:function(a,c,p,f){var T,y;(a=Q[a])(c=Oi.toValue(c),p=(y=j[T=p])===void 0?St(T):y,null,f)},m:ec,l:function(a,c){var p=function(Ve,we){for(var rt,Ye,ht,xi=new Array(Ve),nr=0;nr<Ve;++nr)xi[nr]=(rt=Le[we+4*nr>>2],Ye="parameter "+nr,ht=void 0,(ht=sr[rt])===void 0&&Ue(Ye+" has unknown type "+ls(rt)),ht);return xi}(a,c),f=p[0],T=f.name+"_$"+p.slice(1).map(function(Ve){return Ve.name}).join("_")+"$",y=B[T];if(y!==void 0)return y;for(var b=["retType"],R=[f],O="",w=0;w<a-1;++w)O+=(w!==0?", ":"")+"arg"+w,b.push("argType"+w),R.push(p[1+w]);var z="return function "+Ot("methodCaller_"+T)+`(handle, name, destructors, args) {
|
|
66
|
+
`,te=0;for(w=0;w<a-1;++w)z+=" var arg"+w+" = argType"+w+".readValueFromPointer(args"+(te?"+"+te:"")+`);
|
|
67
|
+
`,te+=p[w+1].argPackAdvance;for(z+=" var rv = handle[name]("+O+`);
|
|
68
|
+
`,w=0;w<a-1;++w)p[w+1].deleteObject&&(z+=" argType"+w+".deleteObject(arg"+w+`);
|
|
69
|
+
`);f.isVoid||(z+=` return retType.toWireType(destructors, rv);
|
|
70
|
+
`),z+=`};
|
|
71
|
+
`,b.push(z);var re,ee,Re=mn(Function,b).apply(null,R);return re=Re,ee=Q.length,Q.push(re),y=ee,B[T]=y,y},a:()=>{Nr("")},e:function(){return Date.now()},v:()=>ne.length,A:(a,c,p)=>ne.copyWithin(a,c,c+p),u:a=>{ne.length,Nr("OOM")},y:(a,c)=>{var p=0;return De().forEach(function(f,T){var y=c+p;Le[a+4*T>>2]=y,((b,R)=>{for(var O=0;O<b.length;++O)se[0|R++]=b.charCodeAt(O);se[0|R]=0})(f,y),p+=f.length+1}),0},z:(a,c)=>{var p=De();Le[a>>2]=p.length;var f=0;return p.forEach(function(T){f+=T.length+1}),Le[c>>2]=f,0},i:function(a){try{var c=_t.getStreamFromFD(a);return h.close(c),0}catch(p){if(h===void 0||p.name!=="ErrnoError")throw p;return p.errno}},x:function(a,c){try{var p=_t.getStreamFromFD(a),f=p.tty?2:h.isDir(p.mode)?3:h.isLink(p.mode)?7:4;return se[c|0]=f,Ae[c+2>>1]=0,Qe=[0,(fe=0,+Math.abs(fe)>=1?fe>0?+Math.floor(fe/4294967296)>>>0:~~+Math.ceil((fe-+(~~fe>>>0))/4294967296)>>>0:0)],Pe[c+8>>2]=Qe[0],Pe[c+12>>2]=Qe[1],Qe=[0,(fe=0,+Math.abs(fe)>=1?fe>0?+Math.floor(fe/4294967296)>>>0:~~+Math.ceil((fe-+(~~fe>>>0))/4294967296)>>>0:0)],Pe[c+16>>2]=Qe[0],Pe[c+20>>2]=Qe[1],0}catch(T){if(h===void 0||T.name!=="ErrnoError")throw T;return T.errno}},B:function(a,c,p,f){try{var T=((y,b,R,O)=>{for(var w=0,z=0;z<R;z++){var te=Le[b>>2],re=Le[b+4>>2];b+=8;var ee=h.read(y,se,te,re,O);if(ee<0)return-1;if(w+=ee,ee<re)break;O!==void 0&&(O+=ee)}return w})(_t.getStreamFromFD(a),c,p);return Le[f>>2]=T,0}catch(y){if(h===void 0||y.name!=="ErrnoError")throw y;return y.errno}},s:function(a,c,p,f,T){var y,b,R=(b=p)+2097152>>>0<4194305-!!(y=c)?(y>>>0)+4294967296*b:NaN;try{if(isNaN(R))return 61;var O=_t.getStreamFromFD(a);return h.llseek(O,R,f),Qe=[O.position>>>0,(fe=O.position,+Math.abs(fe)>=1?fe>0?+Math.floor(fe/4294967296)>>>0:~~+Math.ceil((fe-+(~~fe>>>0))/4294967296)>>>0:0)],Pe[T>>2]=Qe[0],Pe[T+4>>2]=Qe[1],O.getdents&&R===0&&f===0&&(O.getdents=null),0}catch(w){if(h===void 0||w.name!=="ErrnoError")throw w;return w.errno}},h:function(a,c,p,f){try{var T=((y,b,R,O)=>{for(var w=0,z=0;z<R;z++){var te=Le[b>>2],re=Le[b+4>>2];b+=8;var ee=h.write(y,se,te,re,O);if(ee<0)return-1;w+=ee,O!==void 0&&(O+=ee)}return w})(_t.getStreamFromFD(a),c,p);return Le[f>>2]=T,0}catch(y){if(h===void 0||y.name!=="ErrnoError")throw y;return y.errno}}},Pi=(function(){var a,c,p,f,T={a:Ct};function y(b,R){var O,w,z=b.exports;return M=(G=z).E,O=M.buffer,o.HEAP8=se=new Int8Array(O),o.HEAP16=Ae=new Int16Array(O),o.HEAP32=Pe=new Int32Array(O),o.HEAPU8=ne=new Uint8Array(O),o.HEAPU16=ie=new Uint16Array(O),o.HEAPU32=Le=new Uint32Array(O),o.HEAPF32=po=new Float32Array(O),o.HEAPF64=on=new Float64Array(O),sn=G.H,w=G.F,os.unshift(w),ho(),z}if(ss(),o.instantiateWasm)try{return o.instantiateWasm(T,y)}catch(b){P("Module.instantiateWasm callback failed with error: "+b),r(b)}(a=v,c=Jr,p=T,f=function(b){y(b.instance)},a||typeof WebAssembly.instantiateStreaming!="function"||wt(c)||typeof fetch!="function"?wr(c,p,f):fetch(c,{credentials:"same-origin"}).then(b=>WebAssembly.instantiateStreaming(b,p).then(f,function(R){return P("wasm streaming compile failed: "+R),P("falling back to ArrayBuffer instantiation"),wr(c,p,f)}))).catch(r)}(),a=>(Pi=G.G)(a)),yt=a=>(yt=G.I)(a),pn=()=>(pn=G.J)(),fr=a=>(fr=G.K)(a),hn=(o.__embind_initialize_bindings=()=>(o.__embind_initialize_bindings=G.L)(),a=>(hn=G.M)(a));o.dynCall_jiji=(a,c,p,f,T)=>(o.dynCall_jiji=G.N)(a,c,p,f,T),o._ff_h264_cabac_tables=67061;function hs(){function a(){ze||(ze=!0,o.calledRun=!0,nn||(o.noFSInit||h.init.initialized||h.init(),h.ignorePermissions=!1,lr.init(),yi(os),e(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),function(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)c=o.postRun.shift(),Si.unshift(c);var c;yi(Si)}()))}Y>0||(function(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)c=o.preRun.shift(),Dr.unshift(c);var c;yi(Dr)}(),Y>0||(o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),a()},1)):a()))}if(zr=function a(){ze||hs(),ze||(zr=a)},o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return hs(),t.ready}})(),xI=PI,kI=class extends Aa{constructor(i){super(xI,i!=null&&i.wasmPath?fetch(i==null?void 0:i.wasmPath).then(t=>t.arrayBuffer()):void 0,i==null?void 0:i.workerMode,i==null?void 0:i.canvas,i==null?void 0:i.yuvMode)}},UM=(()=>{var i=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return function(t={}){var e,r,o=t;o.ready=new Promise((I,E)=>{e=I,r=E});var s,n=Object.assign({},o),d=typeof window=="object",m=typeof importScripts=="function",l=(typeof process=="object"&&typeof process.versions=="object"&&process.versions.node,"");(d||m)&&(m?l=self.location.href:typeof document!="undefined"&&document.currentScript&&(l=document.currentScript.src),i&&(l=i),l=l.indexOf("blob:")!==0?l.substr(0,l.replace(/[?#].*/,"").lastIndexOf("/")+1):"",m&&(s=I=>{var E=new XMLHttpRequest;return E.open("GET",I,!1),E.responseType="arraybuffer",E.send(null),new Uint8Array(E.response)}));var g,_=o.print||console.log.bind(console),S=o.printErr||console.error.bind(console);Object.assign(o,n),n=null,o.arguments&&o.arguments,o.thisProgram&&o.thisProgram,o.quit&&o.quit,o.wasmBinary&&(g=o.wasmBinary);var v,x;o.noExitRuntime,typeof WebAssembly!="object"&&Y("no native wasm support detected");var P,M,G,se,ne,Ae,ie,Pe,Le,po=!1,on=[],sn=[],nn=[],Dr=0,os=null,Si=null;function Y(I){o.onAbort&&o.onAbort(I),S(I="Aborted("+I+")"),po=!0,I+=". Build with -sASSERTIONS for more info.";var E=new WebAssembly.RuntimeError(I);throw r(E),E}var qr,zr;function ss(I){return I.startsWith("data:application/octet-stream;base64,")}function ho(I){if(I==qr&&g)return new Uint8Array(g);if(s)return s(I);throw"both async and sync fetching of the wasm failed"}function Nr(I,E,C){return function(D){return g||!d&&!m||typeof fetch!="function"?Promise.resolve().then(()=>ho(D)):fetch(D,{credentials:"same-origin"}).then(k=>{if(!k.ok)throw"failed to load wasm binary file at '"+D+"'";return k.arrayBuffer()}).catch(()=>ho(D))}(I).then(D=>WebAssembly.instantiate(D,E)).then(D=>D).then(C,D=>{S("failed to asynchronously prepare wasm: "+D),Y(D)})}ss(qr="videodec_simd.wasm")||(zr=qr,qr=o.locateFile?o.locateFile(zr,l):l+zr);var Jr=I=>{for(;I.length>0;)I.shift()(o)};function an(I){this.excPtr=I,this.ptr=I-24,this.set_type=function(E){Ae[this.ptr+4>>2]=E},this.get_type=function(){return Ae[this.ptr+4>>2]},this.set_destructor=function(E){Ae[this.ptr+8>>2]=E},this.get_destructor=function(){return Ae[this.ptr+8>>2]},this.set_caught=function(E){E=E?1:0,P[this.ptr+12|0]=E},this.get_caught=function(){return P[this.ptr+12|0]!=0},this.set_rethrown=function(E){E=E?1:0,P[this.ptr+13|0]=E},this.get_rethrown=function(){return P[this.ptr+13|0]!=0},this.init=function(E,C){this.set_adjusted_ptr(0),this.set_type(E),this.set_destructor(C)},this.set_adjusted_ptr=function(E){Ae[this.ptr+16>>2]=E},this.get_adjusted_ptr=function(){return Ae[this.ptr+16>>2]},this.get_exception_ptr=function(){if(tc(this.get_type()))return Ae[this.excPtr>>2];var E=this.get_adjusted_ptr();return E!==0?E:this.excPtr}}function fe(I){switch(I){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError(`Unknown type size: ${I}`)}}var Qe=void 0;function wt(I){for(var E="",C=I;M[C];)E+=Qe[M[C++]];return E}var W={},wr={},yi={},Ai=void 0;function ce(I){throw new Ai(I)}var cn=void 0;function qt(I){throw new cn(I)}function bi(I,E,C){function D(j){var Q=C(j);Q.length!==I.length&&qt("Mismatched type converter count");for(var B=0;B<I.length;++B)Mt(I[B],Q[B])}I.forEach(function(j){yi[j]=E});var k=new Array(E.length),$=[],H=0;E.forEach((j,Q)=>{wr.hasOwnProperty(j)?k[Q]=wr[j]:($.push(j),W.hasOwnProperty(j)||(W[j]=[]),W[j].push(()=>{k[Q]=wr[j],++H===$.length&&D(k)}))}),$.length===0&&D(k)}function Mt(I,E,C={}){if(!("argPackAdvance"in E))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(D,k,$={}){var H=k.name;if(D||ce(`type "${H}" must have a positive integer typeid pointer`),wr.hasOwnProperty(D)){if($.ignoreDuplicateRegistrations)return;ce(`Cannot register type '${H}' twice`)}if(wr[D]=k,delete yi[D],W.hasOwnProperty(D)){var j=W[D];delete W[D],j.forEach(Q=>Q())}}(I,E,C)}function le(I){if(!(this instanceof Qt)||!(I instanceof Qt))return!1;for(var E=this.$$.ptrType.registeredClass,C=this.$$.ptr,D=I.$$.ptrType.registeredClass,k=I.$$.ptr;E.baseClass;)C=E.upcast(C),E=E.baseClass;for(;D.baseClass;)k=D.upcast(k),D=D.baseClass;return E===D&&C===k}function fo(I){ce(I.$$.ptrType.registeredClass.name+" instance already deleted")}var go=!1;function ns(I){}function lr(I){I.count.value-=1,I.count.value===0&&function(E){E.smartPtr?E.smartPtrType.rawDestructor(E.smartPtr):E.ptrType.registeredClass.rawDestructor(E.ptr)}(I)}function dn(I,E,C){if(E===C)return I;if(C.baseClass===void 0)return null;var D=dn(I,E,C.baseClass);return D===null?null:C.downcast(D)}var Se={};function Su(){return Object.keys(Qr).length}function yu(){var I=[];for(var E in Qr)Qr.hasOwnProperty(E)&&I.push(Qr[E]);return I}var Xr=[];function h(){for(;Xr.length;){var I=Xr.pop();I.$$.deleteScheduled=!1,I.delete()}}var Ri=void 0;function _t(I){Ri=I,Xr.length&&Ri&&Ri(h)}var Qr={};function La(I,E){return E=function(C,D){for(D===void 0&&ce("ptr should not be undefined");C.baseClass;)D=C.upcast(D),C=C.baseClass;return D}(I,E),Qr[E]}function St(I,E){return E.ptrType&&E.ptr||qt("makeClassHandle requires ptr and ptrType"),!!E.smartPtrType!=!!E.smartPtr&&qt("Both smartPtrType and smartPtr must be specified"),E.count={value:1},sr(Object.create(I,{$$:{value:E}}))}function vi(I){var E=this.getPointee(I);if(!E)return this.destructor(I),null;var C=La(this.registeredClass,E);if(C!==void 0){if(C.$$.count.value===0)return C.$$.ptr=E,C.$$.smartPtr=I,C.clone();var D=C.clone();return this.destructor(I),D}function k(){return this.isSmartPointer?St(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:E,smartPtrType:this,smartPtr:I}):St(this.registeredClass.instancePrototype,{ptrType:this,ptr:I})}var $,H=this.registeredClass.getActualType(E),j=Se[H];if(!j)return k.call(this);$=this.isConst?j.constPointerType:j.pointerType;var Q=dn(E,this.registeredClass,$.registeredClass);return Q===null?k.call(this):this.isSmartPointer?St($.registeredClass.instancePrototype,{ptrType:$,ptr:Q,smartPtrType:this,smartPtr:I}):St($.registeredClass.instancePrototype,{ptrType:$,ptr:Q})}var sr=function(I){return typeof FinalizationRegistry=="undefined"?(sr=E=>E,I):(go=new FinalizationRegistry(E=>{lr(E.$$)}),ns=E=>go.unregister(E),(sr=E=>{var C=E.$$;if(C.smartPtr){var D={$$:C};go.register(E,D,E)}return E})(I))};function as(){if(this.$$.ptr||fo(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var I,E=sr(Object.create(Object.getPrototypeOf(this),{$$:{value:(I=this.$$,{count:I.count,deleteScheduled:I.deleteScheduled,preservePointerOnDelete:I.preservePointerOnDelete,ptr:I.ptr,ptrType:I.ptrType,smartPtr:I.smartPtr,smartPtrType:I.smartPtrType})}}));return E.$$.count.value+=1,E.$$.deleteScheduled=!1,E}function Ci(){this.$$.ptr||fo(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&ce("Object already scheduled for deletion"),ns(this),lr(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function Ue(){return!this.$$.ptr}function Ua(){return this.$$.ptr||fo(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&ce("Object already scheduled for deletion"),Xr.push(this),Xr.length===1&&Ri&&Ri(h),this.$$.deleteScheduled=!0,this}function Qt(){}function Mr(I){if(I===void 0)return"_unknown";var E=(I=I.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return E>=48&&E<=57?`_${I}`:I}function Yt(I,E){return I=Mr(I),{[I]:function(){return E.apply(this,arguments)}}[I]}function Va(I,E,C){if(I[E].overloadTable===void 0){var D=I[E];I[E]=function(){return I[E].overloadTable.hasOwnProperty(arguments.length)||ce(`Function '${C}' called with an invalid number of arguments (${arguments.length}) - expects one of (${I[E].overloadTable})!`),I[E].overloadTable[arguments.length].apply(this,arguments)},I[E].overloadTable=[],I[E].overloadTable[D.argCount]=D}}function un(I,E,C,D,k,$,H,j){this.name=I,this.constructor=E,this.instancePrototype=C,this.rawDestructor=D,this.baseClass=k,this.getActualType=$,this.upcast=H,this.downcast=j,this.pureVirtualFunctions=[]}function Eo(I,E,C){for(;E!==C;)E.upcast||ce(`Expected null or instance of ${C.name}, got an instance of ${E.name}`),I=E.upcast(I),E=E.baseClass;return I}function Fa(I,E){if(E===null)return this.isReference&&ce(`null is not a valid ${this.name}`),0;E.$$||ce(`Cannot pass "${yo(E)}" as a ${this.name}`),E.$$.ptr||ce(`Cannot pass deleted object as a pointer of type ${this.name}`);var C=E.$$.ptrType.registeredClass;return Eo(E.$$.ptr,C,this.registeredClass)}function $a(I,E){var C;if(E===null)return this.isReference&&ce(`null is not a valid ${this.name}`),this.isSmartPointer?(C=this.rawConstructor(),I!==null&&I.push(this.rawDestructor,C),C):0;E.$$||ce(`Cannot pass "${yo(E)}" as a ${this.name}`),E.$$.ptr||ce(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&E.$$.ptrType.isConst&&ce(`Cannot convert argument of type ${E.$$.smartPtrType?E.$$.smartPtrType.name:E.$$.ptrType.name} to parameter type ${this.name}`);var D=E.$$.ptrType.registeredClass;if(C=Eo(E.$$.ptr,D,this.registeredClass),this.isSmartPointer)switch(E.$$.smartPtr===void 0&&ce("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:E.$$.smartPtrType===this?C=E.$$.smartPtr:ce(`Cannot convert argument of type ${E.$$.smartPtrType?E.$$.smartPtrType.name:E.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:C=E.$$.smartPtr;break;case 2:if(E.$$.smartPtrType===this)C=E.$$.smartPtr;else{var k=E.clone();C=this.rawShare(C,ds.toHandle(function(){k.delete()})),I!==null&&I.push(this.rawDestructor,C)}break;default:ce("Unsupporting sharing policy")}return C}function Ba(I,E){if(E===null)return this.isReference&&ce(`null is not a valid ${this.name}`),0;E.$$||ce(`Cannot pass "${yo(E)}" as a ${this.name}`),E.$$.ptr||ce(`Cannot pass deleted object as a pointer of type ${this.name}`),E.$$.ptrType.isConst&&ce(`Cannot convert argument of type ${E.$$.ptrType.name} to parameter type ${this.name}`);var C=E.$$.ptrType.registeredClass;return Eo(E.$$.ptr,C,this.registeredClass)}function _o(I){return this.fromWireType(ne[I>>2])}function Au(I){return this.rawGetPointee&&(I=this.rawGetPointee(I)),I}function bu(I){this.rawDestructor&&this.rawDestructor(I)}function To(I){I!==null&&I.delete()}function Zt(I,E,C,D,k,$,H,j,Q,B,ue){this.name=I,this.registeredClass=E,this.isReference=C,this.isConst=D,this.isSmartPointer=k,this.pointeeType=$,this.sharingPolicy=H,this.rawGetPointee=j,this.rawConstructor=Q,this.rawShare=B,this.rawDestructor=ue,k||E.baseClass!==void 0?this.toWireType=$a:D?(this.toWireType=Fa,this.destructorFunction=null):(this.toWireType=Ba,this.destructorFunction=null)}var Or=[],Ha=I=>{var E=Or[I];return E||(I>=Or.length&&(Or.length=I+1),Or[I]=E=Le.get(I)),E},Io=(I,E,C)=>I.includes("j")?((D,k,$)=>{var H=o["dynCall_"+D];return $&&$.length?H.apply(null,[k].concat($)):H.call(null,k)})(I,E,C):Ha(E).apply(null,C);function Di(I,E){var C,D,k,$=(I=wt(I)).includes("j")?(C=I,D=E,k=[],function(){return k.length=0,Object.assign(k,arguments),Io(C,D,k)}):Ha(E);return typeof $!="function"&&ce(`unknown function pointer with signature ${I}: ${E}`),$}var So=void 0;function Wa(I){var E=ps(I),C=wt(E);return hr(E),C}function Ni(I,E){var C=[],D={};throw E.forEach(function k($){D[$]||wr[$]||(yi[$]?yi[$].forEach(k):(C.push($),D[$]=!0))}),new So(`${I}: `+C.map(Wa).join([", "]))}function Ga(I,E){for(var C=[],D=0;D<I;D++)C.push(Ae[E+4*D>>2]);return C}function Ru(I){for(;I.length;){var E=I.pop();I.pop()(E)}}function ja(I,E){if(!(I instanceof Function))throw new TypeError(`new_ called with constructor type ${typeof I} which is not a function`);var C=Yt(I.name||"unknownFunctionName",function(){});C.prototype=I.prototype;var D=new C,k=I.apply(D,E);return k instanceof Object?k:D}function qa(I,E,C,D,k,$){var H=E.length;H<2&&ce("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var j=E[1]!==null&&C!==null,Q=!1,B=1;B<E.length;++B)if(E[B]!==null&&E[B].destructorFunction===void 0){Q=!0;break}var ue=E[0].name!=="void",De="",be="";for(B=0;B<H-2;++B)De+=(B!==0?", ":"")+"arg"+B,be+=(B!==0?", ":"")+"arg"+B+"Wired";var he=`
|
|
72
|
+
return function ${Mr(I)}(${De}) {
|
|
73
|
+
if (arguments.length !== ${H-2}) {
|
|
74
|
+
throwBindingError('function ${I} called with ${arguments.length} arguments, expected ${H-2} args!');
|
|
75
|
+
}`;Q&&(he+=`var destructors = [];
|
|
76
|
+
`);var Ne=Q?"destructors":"null",tt=["throwBindingError","invoker","fn","runDestructors","retType","classParam"],qe=[ce,D,k,Ru,E[0],E[1]];for(j&&(he+="var thisWired = classParam.toWireType("+Ne+`, this);
|
|
77
|
+
`),B=0;B<H-2;++B)he+="var arg"+B+"Wired = argType"+B+".toWireType("+Ne+", arg"+B+"); // "+E[B+2].name+`
|
|
78
|
+
`,tt.push("argType"+B),qe.push(E[B+2]);if(j&&(be="thisWired"+(be.length>0?", ":"")+be),he+=(ue||$?"var rv = ":"")+"invoker(fn"+(be.length>0?", ":"")+be+`);
|
|
79
|
+
`,Q)he+=`runDestructors(destructors);
|
|
80
|
+
`;else for(B=j?1:2;B<E.length;++B){var lt=B===1?"thisWired":"arg"+(B-2)+"Wired";E[B].destructorFunction!==null&&(he+=lt+"_dtor("+lt+"); // "+E[B].name+`
|
|
81
|
+
`,tt.push(lt+"_dtor"),qe.push(E[B].destructorFunction))}return ue&&(he+=`var ret = retType.fromWireType(rv);
|
|
82
|
+
return ret;
|
|
83
|
+
`),he+=`}
|
|
84
|
+
`,tt.push(he),ja(Function,tt).apply(null,qe)}function mr(){this.allocated=[void 0],this.freelist=[]}var Ot=new mr;function cs(I){I>=Ot.reserved&&--Ot.get(I).refcount==0&&Ot.free(I)}function za(){for(var I=0,E=Ot.reserved;E<Ot.allocated.length;++E)Ot.allocated[E]!==void 0&&++I;return I}var ds={toValue:I=>(I||ce("Cannot use deleted val. handle = "+I),Ot.get(I).value),toHandle:I=>{switch(I){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return Ot.allocate({refcount:1,value:I})}}};function yo(I){if(I===null)return"null";var E=typeof I;return E==="object"||E==="array"||E==="function"?I.toString():""+I}function vu(I,E){switch(E){case 2:return function(C){return this.fromWireType(ie[C>>2])};case 3:return function(C){return this.fromWireType(Pe[C>>3])};default:throw new TypeError("Unknown float type: "+I)}}function Cu(I,E,C){switch(E){case 0:return C?function(D){return P[D]}:function(D){return M[D]};case 1:return C?function(D){return G[D>>1]}:function(D){return se[D>>1]};case 2:return C?function(D){return ne[D>>2]}:function(D){return Ae[D>>2]};default:throw new TypeError("Unknown integer type: "+I)}}var Ja=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0,Ao=(I,E,C)=>{for(var D=E+C,k=E;I[k]&&!(k>=D);)++k;if(k-E>16&&I.buffer&&Ja)return Ja.decode(I.subarray(E,k));for(var $="";E<k;){var H=I[E++];if(128&H){var j=63&I[E++];if((224&H)!=192){var Q=63&I[E++];if((H=(240&H)==224?(15&H)<<12|j<<6|Q:(7&H)<<18|j<<12|Q<<6|63&I[E++])<65536)$+=String.fromCharCode(H);else{var B=H-65536;$+=String.fromCharCode(55296|B>>10,56320|1023&B)}}else $+=String.fromCharCode((31&H)<<6|j)}else $+=String.fromCharCode(H)}return $},Du=(I,E)=>I?Ao(M,I,E):"",Xa=typeof TextDecoder!="undefined"?new TextDecoder("utf-16le"):void 0,Nu=(I,E)=>{for(var C=I,D=C>>1,k=D+E/2;!(D>=k)&&se[D];)++D;if((C=D<<1)-I>32&&Xa)return Xa.decode(M.subarray(I,C));for(var $="",H=0;!(H>=E/2);++H){var j=G[I+2*H>>1];if(j==0)break;$+=String.fromCharCode(j)}return $},pr=(I,E,C)=>{if(C===void 0&&(C=2147483647),C<2)return 0;for(var D=E,k=(C-=2)<2*I.length?C/2:I.length,$=0;$<k;++$){var H=I.charCodeAt($);G[E>>1]=H,E+=2}return G[E>>1]=0,E-D},us=I=>2*I.length,Qa=(I,E)=>{for(var C=0,D="";!(C>=E/4);){var k=ne[I+4*C>>2];if(k==0)break;if(++C,k>=65536){var $=k-65536;D+=String.fromCharCode(55296|$>>10,56320|1023&$)}else D+=String.fromCharCode(k)}return D},wu=(I,E,C)=>{if(C===void 0&&(C=2147483647),C<4)return 0;for(var D=E,k=D+C-4,$=0;$<I.length;++$){var H=I.charCodeAt($);if(H>=55296&&H<=57343&&(H=65536+((1023&H)<<10)|1023&I.charCodeAt(++$)),ne[E>>2]=H,(E+=4)+4>k)break}return ne[E>>2]=0,E-D},wi=I=>{for(var E=0,C=0;C<I.length;++C){var D=I.charCodeAt(C);D>=55296&&D<=57343&&++C,E+=4}return E},Ya={},ls=[],ms=[],ln;ln=()=>performance.now();var Za,mn,Mi,Ka=[null,[],[]];(function(){for(var I=new Array(256),E=0;E<256;++E)I[E]=String.fromCharCode(E);Qe=I})(),Ai=o.BindingError=class extends Error{constructor(I){super(I),this.name="BindingError"}},cn=o.InternalError=class extends Error{constructor(I){super(I),this.name="InternalError"}},Qt.prototype.isAliasOf=le,Qt.prototype.clone=as,Qt.prototype.delete=Ci,Qt.prototype.isDeleted=Ue,Qt.prototype.deleteLater=Ua,o.getInheritedInstanceCount=Su,o.getLiveInheritedInstances=yu,o.flushPendingDeletes=h,o.setDelayFunction=_t,Zt.prototype.getPointee=Au,Zt.prototype.destructor=bu,Zt.prototype.argPackAdvance=8,Zt.prototype.readValueFromPointer=_o,Zt.prototype.deleteObject=To,Zt.prototype.fromWireType=vi,So=o.UnboundTypeError=(Za=Error,(Mi=Yt(mn="UnboundTypeError",function(I){this.name=mn,this.message=I;var E=new Error(I).stack;E!==void 0&&(this.stack=this.toString()+`
|
|
85
|
+
`+E.replace(/^Error(:[^\n]*)?\n/,""))})).prototype=Object.create(Za.prototype),Mi.prototype.constructor=Mi,Mi.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},Mi),Object.assign(mr.prototype,{get(I){return this.allocated[I]},has(I){return this.allocated[I]!==void 0},allocate(I){var E=this.freelist.pop()||this.allocated.length;return this.allocated[E]=I,E},free(I){this.allocated[I]=void 0,this.freelist.push(I)}}),Ot.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),Ot.reserved=Ot.allocated.length,o.count_emval_handles=za;var Pt,ec={o:function(I,E,C){throw new an(I).init(E,C),I},r:function(I,E,C,D,k){},m:function(I,E,C,D,k){var $=fe(C);Mt(I,{name:E=wt(E),fromWireType:function(H){return!!H},toWireType:function(H,j){return j?D:k},argPackAdvance:8,readValueFromPointer:function(H){var j;if(C===1)j=P;else if(C===2)j=G;else{if(C!==4)throw new TypeError("Unknown boolean type size: "+E);j=ne}return this.fromWireType(j[H>>$])},destructorFunction:null})},q:function(I,E,C,D,k,$,H,j,Q,B,ue,De,be){ue=wt(ue),$=Di(k,$),j&&(j=Di(H,j)),B&&(B=Di(Q,B)),be=Di(De,be);var he=Mr(ue);(function(Ne,tt,qe){o.hasOwnProperty(Ne)?((qe===void 0||o[Ne].overloadTable!==void 0&&o[Ne].overloadTable[qe]!==void 0)&&ce(`Cannot register public name '${Ne}' twice`),Va(o,Ne,Ne),o.hasOwnProperty(qe)&&ce(`Cannot register multiple overloads of a function with the same number of arguments (${qe})!`),o[Ne].overloadTable[qe]=tt):(o[Ne]=tt,qe!==void 0&&(o[Ne].numArguments=qe))})(he,function(){Ni(`Cannot construct ${ue} due to unbound types`,[D])}),bi([I,E,C],D?[D]:[],function(Ne){var tt,qe;Ne=Ne[0],qe=D?(tt=Ne.registeredClass).instancePrototype:Qt.prototype;var lt=Yt(he,function(){if(Object.getPrototypeOf(this)!==ze)throw new Ai("Use 'new' to construct "+ue);if(Ct.constructor_body===void 0)throw new Ai(ue+" has no accessible constructor");var fr=Ct.constructor_body[arguments.length];if(fr===void 0)throw new Ai(`Tried to invoke ctor of ${ue} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(Ct.constructor_body).toString()}) parameters instead!`);return fr.apply(this,arguments)}),ze=Object.create(qe,{constructor:{value:lt}});lt.prototype=ze;var Ct=new un(ue,lt,ze,be,tt,$,j,B);Ct.baseClass&&(Ct.baseClass.__derivedClasses===void 0&&(Ct.baseClass.__derivedClasses=[]),Ct.baseClass.__derivedClasses.push(Ct));var Pi=new Zt(ue,Ct,!0,!1,!1),yt=new Zt(ue+"*",Ct,!1,!1,!1),pn=new Zt(ue+" const*",Ct,!1,!0,!1);return Se[I]={pointerType:yt,constPointerType:pn},function(fr,hn,hs){o.hasOwnProperty(fr)||qt("Replacing nonexistant public symbol"),o[fr].overloadTable!==void 0&&hs!==void 0?o[fr].overloadTable[hs]=hn:(o[fr]=hn,o[fr].argCount=hs)}(he,lt),[Pi,yt,pn]})},p:function(I,E,C,D,k,$){var H=Ga(E,C);k=Di(D,k),bi([],[I],function(j){var Q=`constructor ${(j=j[0]).name}`;if(j.registeredClass.constructor_body===void 0&&(j.registeredClass.constructor_body=[]),j.registeredClass.constructor_body[E-1]!==void 0)throw new Ai(`Cannot register multiple constructors with identical number of parameters (${E-1}) for class '${j.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return j.registeredClass.constructor_body[E-1]=()=>{Ni(`Cannot construct ${j.name} due to unbound types`,H)},bi([],H,function(B){return B.splice(1,0,null),j.registeredClass.constructor_body[E-1]=qa(Q,B,null,k,$),[]}),[]})},d:function(I,E,C,D,k,$,H,j,Q){var B=Ga(C,D);E=wt(E),$=Di(k,$),bi([],[I],function(ue){var De=`${(ue=ue[0]).name}.${E}`;function be(){Ni(`Cannot call ${De} due to unbound types`,B)}E.startsWith("@@")&&(E=Symbol[E.substring(2)]),j&&ue.registeredClass.pureVirtualFunctions.push(E);var he=ue.registeredClass.instancePrototype,Ne=he[E];return Ne===void 0||Ne.overloadTable===void 0&&Ne.className!==ue.name&&Ne.argCount===C-2?(be.argCount=C-2,be.className=ue.name,he[E]=be):(Va(he,E,De),he[E].overloadTable[C-2]=be),bi([],B,function(tt){var qe=qa(De,tt,ue,$,H,Q);return he[E].overloadTable===void 0?(qe.argCount=C-2,he[E]=qe):he[E].overloadTable[C-2]=qe,[]}),[]})},u:function(I,E){Mt(I,{name:E=wt(E),fromWireType:function(C){var D=ds.toValue(C);return cs(C),D},toWireType:function(C,D){return ds.toHandle(D)},argPackAdvance:8,readValueFromPointer:_o,destructorFunction:null})},k:function(I,E,C){var D=fe(C);Mt(I,{name:E=wt(E),fromWireType:function(k){return k},toWireType:function(k,$){return $},argPackAdvance:8,readValueFromPointer:vu(E,D),destructorFunction:null})},b:function(I,E,C,D,k){E=wt(E),k===-1&&(k=4294967295);var $=fe(C),H=B=>B;if(D===0){var j=32-8*C;H=B=>B<<j>>>j}var Q=E.includes("unsigned");Mt(I,{name:E,fromWireType:H,toWireType:Q?function(B,ue){return this.name,ue>>>0}:function(B,ue){return this.name,ue},argPackAdvance:8,readValueFromPointer:Cu(E,$,D!==0),destructorFunction:null})},a:function(I,E,C){var D=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][E];function k($){var H=Ae,j=H[$>>=2],Q=H[$+1];return new D(H.buffer,Q,j)}Mt(I,{name:C=wt(C),fromWireType:k,argPackAdvance:8,readValueFromPointer:k},{ignoreDuplicateRegistrations:!0})},j:function(I,E){var C=(E=wt(E))==="std::string";Mt(I,{name:E,fromWireType:function(D){var k,$=Ae[D>>2],H=D+4;if(C)for(var j=H,Q=0;Q<=$;++Q){var B=H+Q;if(Q==$||M[B]==0){var ue=Du(j,B-j);k===void 0?k=ue:(k+="\0",k+=ue),j=B+1}}else{var De=new Array($);for(Q=0;Q<$;++Q)De[Q]=String.fromCharCode(M[H+Q]);k=De.join("")}return hr(D),k},toWireType:function(D,k){var $;k instanceof ArrayBuffer&&(k=new Uint8Array(k));var H=typeof k=="string";H||k instanceof Uint8Array||k instanceof Uint8ClampedArray||k instanceof Int8Array||ce("Cannot pass non-string to std::string"),$=C&&H?(De=>{for(var be=0,he=0;he<De.length;++he){var Ne=De.charCodeAt(he);Ne<=127?be++:Ne<=2047?be+=2:Ne>=55296&&Ne<=57343?(be+=4,++he):be+=3}return be})(k):k.length;var j=Oi(4+$+1),Q=j+4;if(Ae[j>>2]=$,C&&H)((De,be,he,Ne)=>{if(!(Ne>0))return 0;for(var tt=he,qe=he+Ne-1,lt=0;lt<De.length;++lt){var ze=De.charCodeAt(lt);if(ze>=55296&&ze<=57343&&(ze=65536+((1023&ze)<<10)|1023&De.charCodeAt(++lt)),ze<=127){if(he>=qe)break;be[he++]=ze}else if(ze<=2047){if(he+1>=qe)break;be[he++]=192|ze>>6,be[he++]=128|63&ze}else if(ze<=65535){if(he+2>=qe)break;be[he++]=224|ze>>12,be[he++]=128|ze>>6&63,be[he++]=128|63&ze}else{if(he+3>=qe)break;be[he++]=240|ze>>18,be[he++]=128|ze>>12&63,be[he++]=128|ze>>6&63,be[he++]=128|63&ze}}be[he]=0})(k,M,Q,$+1);else if(H)for(var B=0;B<$;++B){var ue=k.charCodeAt(B);ue>255&&(hr(Q),ce("String has UTF-16 code units that do not fit in 8 bits")),M[Q+B]=ue}else for(B=0;B<$;++B)M[Q+B]=k[B];return D!==null&&D.push(hr,j),j},argPackAdvance:8,readValueFromPointer:_o,destructorFunction:function(D){hr(D)}})},g:function(I,E,C){var D,k,$,H,j;C=wt(C),E===2?(D=Nu,k=pr,H=us,$=()=>se,j=1):E===4&&(D=Qa,k=wu,H=wi,$=()=>Ae,j=2),Mt(I,{name:C,fromWireType:function(Q){for(var B,ue=Ae[Q>>2],De=$(),be=Q+4,he=0;he<=ue;++he){var Ne=Q+4+he*E;if(he==ue||De[Ne>>j]==0){var tt=D(be,Ne-be);B===void 0?B=tt:(B+="\0",B+=tt),be=Ne+E}}return hr(Q),B},toWireType:function(Q,B){typeof B!="string"&&ce(`Cannot pass non-string to C++ string type ${C}`);var ue=H(B),De=Oi(4+ue+E);return Ae[De>>2]=ue>>j,k(B,De+4,ue+E),Q!==null&&Q.push(hr,De),De},argPackAdvance:8,readValueFromPointer:_o,destructorFunction:function(Q){hr(Q)}})},n:function(I,E){Mt(I,{isVoid:!0,name:E=wt(E),argPackAdvance:0,fromWireType:function(){},toWireType:function(C,D){}})},e:function(I,E,C,D){var k,$;(I=ls[I])(E=ds.toValue(E),C=($=Ya[k=C])===void 0?wt(k):$,null,D)},l:cs,h:function(I,E){var C=function(tt,qe){for(var lt,ze,Ct,Pi=new Array(tt),yt=0;yt<tt;++yt)Pi[yt]=(lt=Ae[qe+4*yt>>2],ze="parameter "+yt,Ct=void 0,(Ct=wr[lt])===void 0&&ce(ze+" has unknown type "+Wa(lt)),Ct);return Pi}(I,E),D=C[0],k=D.name+"_$"+C.slice(1).map(function(tt){return tt.name}).join("_")+"$",$=ms[k];if($!==void 0)return $;for(var H=["retType"],j=[D],Q="",B=0;B<I-1;++B)Q+=(B!==0?", ":"")+"arg"+B,H.push("argType"+B),j.push(C[1+B]);var ue="return function "+Mr("methodCaller_"+k)+`(handle, name, destructors, args) {
|
|
86
|
+
`,De=0;for(B=0;B<I-1;++B)ue+=" var arg"+B+" = argType"+B+".readValueFromPointer(args"+(De?"+"+De:"")+`);
|
|
87
|
+
`,De+=C[B+1].argPackAdvance;for(ue+=" var rv = handle[name]("+Q+`);
|
|
88
|
+
`,B=0;B<I-1;++B)C[B+1].deleteObject&&(ue+=" argType"+B+".deleteObject(arg"+B+`);
|
|
89
|
+
`);D.isVoid||(ue+=` return retType.toWireType(destructors, rv);
|
|
90
|
+
`),ue+=`};
|
|
91
|
+
`,H.push(ue);var be,he,Ne=ja(Function,H).apply(null,j);return be=Ne,he=ls.length,ls.push(be),$=he,ms[k]=$,$},f:()=>{Y("")},c:ln,t:(I,E,C)=>M.copyWithin(I,E,E+C),s:I=>{M.length,Y("OOM")},i:(I,E,C,D)=>{for(var k,$,H,j=0,Q=0;Q<C;Q++){var B=Ae[E>>2],ue=Ae[E+4>>2];E+=8;for(var De=0;De<ue;De++)k=I,$=M[B+De],H=void 0,H=Ka[k],$===0||$===10?((k===1?_:S)(Ao(H,0)),H.length=0):H.push($);j+=ue}return Ae[D>>2]=j,0}},hr=(function(){var I,E,C,D,k={a:ec};function $(H,j){var Q,B,ue=H.exports;return v=(x=ue).v,Q=v.buffer,o.HEAP8=P=new Int8Array(Q),o.HEAP16=G=new Int16Array(Q),o.HEAP32=ne=new Int32Array(Q),o.HEAPU8=M=new Uint8Array(Q),o.HEAPU16=se=new Uint16Array(Q),o.HEAPU32=Ae=new Uint32Array(Q),o.HEAPF32=ie=new Float32Array(Q),o.HEAPF64=Pe=new Float64Array(Q),Le=x.z,B=x.w,sn.unshift(B),function(){if(Dr--,o.monitorRunDependencies&&o.monitorRunDependencies(Dr),Dr==0&&(os!==null&&(clearInterval(os),os=null),Si)){var De=Si;Si=null,De()}}(),ue}if(Dr++,o.monitorRunDependencies&&o.monitorRunDependencies(Dr),o.instantiateWasm)try{return o.instantiateWasm(k,$)}catch(H){S("Module.instantiateWasm callback failed with error: "+H),r(H)}(I=g,E=qr,C=k,D=function(H){$(H.instance)},I||typeof WebAssembly.instantiateStreaming!="function"||ss(E)||typeof fetch!="function"?Nr(E,C,D):fetch(E,{credentials:"same-origin"}).then(H=>WebAssembly.instantiateStreaming(H,C).then(D,function(j){return S("wasm streaming compile failed: "+j),S("falling back to ArrayBuffer instantiation"),Nr(E,C,D)}))).catch(r)}(),I=>(hr=x.x)(I)),Oi=I=>(Oi=x.y)(I),ps=I=>(ps=x.A)(I),tc=(o.__embind_initialize_bindings=()=>(o.__embind_initialize_bindings=x.B)(),I=>(tc=x.C)(I));o.dynCall_jiji=(I,E,C,D,k)=>(o.dynCall_jiji=x.D)(I,E,C,D,k);function rc(){function I(){Pt||(Pt=!0,o.calledRun=!0,po||(Jr(sn),e(o),o.onRuntimeInitialized&&o.onRuntimeInitialized(),function(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)E=o.postRun.shift(),nn.unshift(E);var E;Jr(nn)}()))}Dr>0||(function(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)E=o.preRun.shift(),on.unshift(E);var E;Jr(on)}(),Dr>0||(o.setStatus?(o.setStatus("Running..."),setTimeout(function(){setTimeout(function(){o.setStatus("")},1),I()},1)):I()))}if(Si=function I(){Pt||rc(),Pt||(Si=I)},o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.pop()();return rc(),t.ready}})();var LI="web.sdk.qcloud.com",UI=`https://${LI}/trtc/webrtc/v5/doc`,VM=`${UI}/zh-cn/`,$f=(i=>(i[i.TRACE=0]="TRACE",i[i.DEBUG=1]="DEBUG",i[i.INFO=2]="INFO",i[i.WARN=3]="WARN",i[i.ERROR=4]="ERROR",i[i.NONE=5]="NONE",i))($f||{});var $d={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"},FM=$d.MAIN,$M=$d.AUXILIARY,BM=$d.BIG,HM=$d.SMALL;var WM=Object.keys($f);var GM=typeof window!="undefined"&&typeof window.glog=="function"?window.glog:()=>{};function Lf(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var{toString:jM}=Object.prototype,Bf=class Hf{constructor(t){this.core=t,vr(this,"contextMap",new Map),vr(this,"decodeProcessorMap",new WeakMap),this.addKVReportBeforeExitRoom=this.addKVReportBeforeExitRoom.bind(this),this.createDecoder=this.createDecoder.bind(this),this.core.innerEmitter.on("51",this.addKVReportBeforeExitRoom)}getAlias(){return"videoDecoder"}getGroup(t){return t!=null&&t.track?`${t.track.userId}${t.track.streamType}`:"*"}getName(){return Hf.Name}getValidateRule(t){return{type:this.core.enums.BASIC_TYPE.Object}}createDecoder(t,e){switch(t){case"wasm":return new kI(Ud(Ld({},e),{wasmPath:`${this.core.assetsPath||"."}/videodec.wasm`}));case"webCodecs":return new Ys;case"mse":throw new Error("mse decoder not supported yet");default:throw new Error("Unsupported decoder type")}}start(t){this.decodeProcessorMap.set(t.track,this.decode(t)),this.core.room.videoManager.addDecodeProcessor({processor:({frame:e,track:r})=>{var o;return((o=this.decodeProcessorMap.get(r))==null?void 0:o({frame:e,track:r}))||e},type:3})}decode(t){let{pipe:e,take:r,subscribe:o}=this.core.rx;return({frame:s,track:n})=>{if(n!==t.track||s.type==="empty")return s;if(this.contextMap.has(n))return this.contextMap.get(n).decode(s);let d=this.core.room.videoManager.createDecodeContext(Ud(Ld({},t),{createDecoder:this.createDecoder}));return e(d.trackDoneOB,r(1),o(()=>{this.core.clearStarted(this,this.getGroup(t)),this.stop({track:n})})),this.contextMap.set(n,d),d.decode(s)}}stop(t){if(t!=null&&t.track){let e=this.contextMap.get(t.track);e&&(e.close("stop"),this.report(e,t.track),this.contextMap.delete(t.track))}else this.contextMap.forEach((e,r)=>{e.close("stop"),this.contextMap.delete(r)});this.contextMap.size===0&&this.core.room.videoManager.removeDecodeProcessor({type:3})}report(t,e){if(t.isReported)return;t.isReported=!0;let r=Lf()-t.startPerformanceTime,{renderFreezeTotal:o,dataFreezeTotal:s}=this.getRemoteTrackFreezeDuration(e,t);r&&this.core.kvStatManager.addNumber({key:514850,value:Math.floor(o/r*100),split:1}),r&&this.core.kvStatManager.addNumber({key:514851,value:Math.floor(s/r*100),split:1}),t.inputFrameCount&&this.core.kvStatManager.addNumber({key:514852,value:Math.floor(t.decodedFrameCount/t.inputFrameCount*100),split:1})}addKVReportBeforeExitRoom({room:t}){t===this.core.room&&this.contextMap.forEach((e,r)=>{this.report(e,r)})}update(t){let e=this.contextMap.get(t.track);e&&(t.type!=="mock"?(e.close("update"),this.contextMap.set(t.track,this.core.room.videoManager.createDecodeContext(Ud(Ld({},t),{createDecoder:this.createDecoder})))):e.mock(this.core.enums.DECODE_FAILED_ERROR_CODE.TEST))}getRemoteTrackFreezeDuration(t,e){let r=this.core.room.badCaseDetector.getRenderFreezeMap().get(`${t.userId}_${t.streamType}`),o=this.core.room.badCaseDetector.getDataFreezeMap().get(`${t.userId}_${t.streamType}`),s=0;r&&r.freezeTimeline.forEach(({startTime:d,endTime:m})=>{d>e.startPerformanceTime&&(s+=m===0?Lf()-d:m-d)});let n=0;return o&&o.durationItemList.forEach(d=>{d.startTime>e.startPerformanceTime&&(n+=d.getDuration())}),{renderFreezeTotal:s,dataFreezeTotal:n}}destroy(){this.core.innerEmitter.off("51",this.addKVReportBeforeExitRoom)}};vr(Bf,"Name","TRTCVideoDecoder");var qm=Bf;var fg=ki(Wi());function zm({timesInSecond:i,maxSizeInSecond:t,getSize:e}){return Me((r,o)=>{let s=new WeakMap;return L.on(U.ROOM_DESTROY,({room:n})=>s.delete(n)),function(...n){let d=s.get(this);if(d||(d={callCountInSecond:0,timestamp:0,totalSizeInSecond:0},s.set(this,d)),d.timestamp===0?d.timestamp=Date.now():Date.now()-d.timestamp>1e3&&(d.timestamp=Date.now(),d.callCountInSecond=0,d.totalSizeInSecond=0),e&&(d.totalSizeInSecond+=e(...n)),d.timestamp!==0&&Date.now()-d.timestamp<1e3&&(d.callCountInSecond>=i||d.totalSizeInSecond>t))throw new ae({code:q.INVALID_OPERATION,message:$e({key:Fe.CALL_FREQUENCY_LIMIT,data:{isTimes:d.callCountInSecond>=i,isSize:d.totalSizeInSecond>t,name:o,timesInSecond:i,maxSizeInSecond:t}})});d.callCountInSecond++,r.call(this,...n)}})}var VI="2025-05-23 10:48:22",Wf=!0,Gf=function(){var i;if(Wf){Wf=!1,F.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info(`* API Document: ${Pr}/en/index.html`),console.info(`* Changelog: ${Pr}/en/tutorial-01-info-changelog.html`),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),F.info("TRTC Web SDK Version:",st),yr||F.debug("Build Time:",VI);let t=`UA: ${navigator.userAgent}
|
|
92
|
+
CPU core: ${navigator.hardwareConcurrency}, GPU: ${dl()}`,e=navigator.deviceMemory;e&&(t+=`, minRAM: ${e}GB`),F.info(t),F.info(`URL: ${location.href}${((i=self.frameElement)==null?void 0:i.tagName)==="IFRAME"?" in iframe":""}`),Wn().then(r=>{r&&F.info(Tr)})}};var ur={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 pe={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},Cr=(h=>(h[h.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",h[h.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",h[h.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",h[h.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",h[h.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",h[h.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",h[h.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",h[h.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",h[h.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",h[h.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",h[h.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",h[h.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",h[h.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",h[h.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",h[h.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",h[h.INVALID_ROOM_ID_REQUIED=5015]="INVALID_ROOM_ID_REQUIED",h[h.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",h[h.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",h[h.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",h[h.INVALID_OPERATION=5100]="INVALID_OPERATION",h[h.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",h[h.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",h[h.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",h[h.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",h[h.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",h[h.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",h[h.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",h[h.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",h[h.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",h[h.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",h[h.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",h[h.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",h[h.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",h[h.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",h[h.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",h[h.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",h[h.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",h[h.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",h[h.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",h[h.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",h[h.DEVICE_ERROR=5300]="DEVICE_ERROR",h[h.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",h[h.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",h[h.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",h[h.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",h[h.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",h[h.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",h[h.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",h[h.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",h[h.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",h[h.SERVER_ERROR=5400]="SERVER_ERROR",h[h.NEED_TO_BUY=5401]="NEED_TO_BUY",h[h.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",h[h.OPERATION_FAILED=5500]="OPERATION_FAILED",h[h.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",h[h.REJOIN_FAILED=5502]="REJOIN_FAILED",h[h.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",h[h.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",h[h.VIDEO_DECODE_ERROR=5505]="VIDEO_DECODE_ERROR",h[h.OPERATION_ABORT=5998]="OPERATION_ABORT",h[h.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",h))(Cr||{});function qf({code:i,params:t,enableDocLink:e=!1}){let r="",o,s=Cr[i];try{o=jf[s]}catch(n){o=jf.UNKNOWN_ERROR}return He(o)?r=o(t):ve(o)&&(r=o),t.fnName&&!r.includes(t.fnName)&&(r[r.length-1]!=="."&&(r+="."),r+=` thrown from ${t.fnName}()`),e&&(r+=" doc:"),r}var jf=Ee(Z({},Jt),{INVALID_PARAMETER({fnName:i}){return`the parameters of the '${i}' you called does not meet the requirements, please check the API documentation.`},INVALID_PARAMETER_REQUIRED({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' is a required param when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_TYPE({key:i,rule:t,fnName:e,value:r}){let o=`${i||t.name}`,s="";return Array.isArray(t.type)?s=t.type.join("|"):s=t.type,`'${o}' must be type of ${s} when calling ${e}(), received type: ${nt(r)}.`},INVALID_PARAMETER_EMPTY({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' cannot be '${r}' when calling ${e}().`},INVALID_PARAMETER_INSTANCE({key:i,rule:t,fnName:e,value:r}){let o=`${i||t.name}`,s=`${t.instanceOf.name||t.instanceOf}`;return`'${o}' must be instanceof ${s} when calling ${e}(), received type: ${nt(r)}.`},INVALID_PARAMETER_RANGE({key:i,rule:t,fnName:e,value:r}){return`'${i||t.name}' must be one of ${t.values.join("|")} when calling ${e}(), received: ${r}.`},INVALID_PARAMETER_LESS_THAN_ZERO({key:i,rule:t,fnName:e}){return`'${i||t.name}' cannot be less than 0 when calling ${e}().`},INVALID_PARAMETER_MIN({key:i,rule:t,value:e}){return`the min value of ${i||t.name} is ${t.min}, received: ${e}.`},INVALID_PARAMETER_MAX({key:i,rule:t,value:e}){return`the max value of ${i||t.name} is ${t.max}, received: ${e}.`},INVALID_ELEMENT_ID({key:i,fnName:t}){return`'${i}' is not found in the document object when calling ${t}().`},INVALID_ELEMENT_ID_TYPE({key:i,fnName:t,type:e}){return`the element corresponding to '${i}' must be instanceof HTMLElement when calling ${t}(), received: ${e}.`},INVALID_STREAM_ID({key:i}){return`'${i}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`},INVALID_ROOM_ID_STRING({key:i}){return`'${i}' must be a valid string.`},INVALID_ROOM_ID_INTEGER({key:i}){return`'${i}' must be an integer between [1, 4294967294].`},INVALID_ROOM_ID_INTEGER_STRING({key:i}){return`'${i}' 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:i})=>`'streamType' is required when 'userId' is not '*', calling ${i}()`,INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION({fnName:i}){return`the API '${i}' you called does not meet the requirements, please check the API documentation.`},INVALID_OPERATION_NOT_JOINED({fnName:i}){return`cannot ${i} because you are not enter room yet.`},INVALID_OPERATION_REMOTE_USER_NOT_EXIST({fnName:i,value:t}){return`cannot ${i} because remote user(userId: ${t.userId}) does not publishing stream.`},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST({fnName:i,value:t}){return`cannot ${i} because remote user(userId: ${t.userId}) does not publishing ${t.streamType} video.`},INVALID_OPERATION_REPEAT_CALL({fnName:i}){return`you are already ${i}(), cannot repeated call '${i}'.`},INVALID_OPERATION_NEED_VIDEO({fnName:i}){return`cannot call '${i}' because the camera is not turned on.`},INVALID_OPERATION_NEED_AUDIO({fnName:i}){return`cannot call '${i}' because the microphone is not turned on.`},INVALID_BUFFER_EMPTY:({key:i})=>`the buffer size of paramerter '${i}' 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:i})=>`you need to call ${i}() after publish stream.`,ENV_NOT_SUPPORTED({fnName:i}){return`the current browser does not support the capability of the function '${i}' 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:i}){return`cannot call ${i} because the browser version is too low, please upgrade to the latest version`},DEVICE_ERROR({fnName:i,error:t}){return`'${i}' got device exception${t?`, error: ${t.toString()}.`:"."}`},DEVICE_NOT_FOUND_ERROR({fnName:i,deviceType:t=Zo(i),error:e}){return`NotFoundError, no ${t} detected, please check your device and the configuration on '${i}'${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_ALLOWED_ERROR({fnName:i,deviceType:t=Zo(i),error:e}){return`NotAllowedError, you have disabled ${t} access, please allow the current application to use the ${t}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_NOT_READABLE_ERROR({fnName:i,deviceType:t=Zo(i),error:e}){return`NotReadableError, the ${t} maybe in use by another APP, please check if the device is pre-occupied by another APP.`},DEVICE_OVERCONSTRAINED_ERROR({fnName:i,deviceType:t=Zo(i),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:i,deviceType:t=Zo(i),error:e}){return`InvalidStateError, after the user clicks and interacts with the page, turn on the ${t}${e?`, error: ${e.toString()}.`:"."}`},DEVICE_SECURITY_ERROR({fnName:i,deviceType:t=Zo(i),error:e}){return`SecurityError, check whether the system security policy restricts the use of the ${t}, and it is recommended to turn on the ${t} after the user interacts with the page${e?`, error: ${e.toString()}.`:"."}`},DEVICE_ABORT_ERROR({fnName:i,deviceType:t=Zo(i),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:i}){return`camera recover capture failed ${(i==null?void 0:i.name)||""}: ${(i==null?void 0:i.originMessage)||(i==null?void 0:i.message)}`},MICROPHONE_RECOVER_FAILED({error:i}){return`microphone recover capture failed ${(i==null?void 0:i.name)||""}: ${(i==null?void 0:i.originMessage)||(i==null?void 0:i.message)}`},OPERATION_FAILED({fnName:i,error:t}){return`'${i}' failed, reason: ${t==null?void 0:t.toString()}`},FIREWALL_RESTRICTION(){return"media connection failure due to firewall restrictions, please try to change your network."},EVENT_HANDLER_ERROR({eventName:i}){return`an error was caught on trtc.on('${i}', handler), please check your code on 'handler'.`},VIDEO_CONTEXT_ERROR({reason:i,error:t}){return`video context error ${i} ${(t==null?void 0:t.name)||""} ${(t==null?void 0:t.message)||""}`},SERVER_ERROR({fnName:i,error:t}){return`'${i}' got server error: ${t==null?void 0:t.toString()}, please check the SDK documentation.`},NEED_TO_BUY({value:i,url:t}){return`You need to buy packages for ${i}. Refer to: ${t}`},ACCOUNT_NO_MONEY:({fnParams:i})=>`your TRTC account run out of credit, please recharge.${i.sdkAppId?` SDKAppId: ${i.sdkAppId}`:""}`,OPERATION_ABORT({fnName:i}){return`'${i}' abort`},UNKNOWN_ERROR({fnName:i,error:t}){return`'${i}' throw unknown exception${t?`, error: ${t.toString()}.`:"."}`}});function Zo(i){if(!i)return"camera";let t=i.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var Jm=class i extends Error{constructor({code:e,extraCode:r,message:o="",messageParams:s,fnName:n="",originError:d}){var l;let m;o?m=o:m=qf({code:e===pe.SERVER_ERROR?e:r||e,params:Z({fnName:n,error:d},s)});super(m);u(this,"name","RtcError");u(this,"code");u(this,"extraCode");u(this,"functionName");u(this,"message");u(this,"handler");u(this,"originError");this.name=Cr[e],this.code=e,this.extraCode=r,this.functionName=n,this.originError=d,this.message=m,this.extraCode===5302&&((l=this.originError)!=null&&l.message.includes("system"))&&(this.handler=()=>{let g={startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"},_={startLocalVideo:"webcam",startLocalAudio:"microphone"},S=document.createElement("a");Oo?S.href=`ms-settings:privacy-${_[this.functionName]}`:Sr&&(S.href=`x-apple.systempreferences:com.apple.preference.security?Privacy_${g[this.functionName]}`),S.href.length>0&&S.click()})}static convertFrom(e,r,o){let s=e;if(e instanceof ae){let{stack:n}=e,d={code:pe.UNKNOWN_ERROR,fnName:r,originError:e};switch(e.getCode()){case q.INVALID_PARAMETER:d.code=pe.INVALID_PARAMETER,d.message=e.message;break;case q.INVALID_OPERATION:d.code=pe.INVALID_OPERATION;break;case q.NOT_SUPPORTED:case q.NOT_SUPPORTED_H264:d.code=pe.ENV_NOT_SUPPORTED,e.getCode()===q.NOT_SUPPORTED_H264&&(d.extraCode=e.message.includes(Jt.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case q.JOIN_ROOM_FAILED:d.messageParams={fnParams:o};case q.SERVER_TIMEOUT:case q.SWITCH_ROLE_FAILED:d.code=pe.SERVER_ERROR,d.extraCode=e.getExtraCode();break;case q.API_CALL_ABORTED:d.code=pe.OPERATION_ABORT;break;case q.DEVICE_NOT_FOUND:case q.DEVICE_AUTO_RECOVER_FAILED:case q.INITIALIZE_FAILED:d.code=5300,e.name&&(d.extraCode=FI(e.name));break;case q.UNKNOWN:break;default:d.code=pe.OPERATION_FAILED}s=new i(d),n&&(s.stack+=n.substr(n.indexOf(`
|
|
93
|
+
`)))}else{if(e instanceof i)return e;s=new i({code:pe.UNKNOWN_ERROR,fnName:r,originError:e})}return s}};function FI(i){let t;switch(i){case"NotFoundError":t=5301;break;case"NotAllowedError":t=5302;break;case"NotReadableError":t=5303;break;case"OverconstrainedError":t=5304;break;case"InvalidStateError":t=5305;break;case"SecurityError":t=5306;break;case"AbortError":t=5307;break;default:t=5300}return t}var de=Jm;var zf={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}}},Jf={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}}},Zs={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(i,t,e){if(ve(i)&&!document.getElementById(i))throw new de({code:pe.INVALID_PARAMETER,extraCode:5009,fnName:e,messageParams:{key:t}})}},Xf={name:"userId",required:!0,type:"string"},Qf={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{values:[ur.AUDIO_PROFILE_STANDARD,ur.AUDIO_PROFILE_STANDARD_STEREO,ur.AUDIO_PROFILE_HIGH,ur.AUDIO_PROFILE_HIGH_STEREO]},echoCancellation:{type:"boolean"},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function va(i,t){if(!i)throw new de({code:pe.INVALID_OPERATION,extraCode:5101,fnName:t})}function Yf(i,t,e){if(!i)throw new de({code:pe.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:e}})}var t0={type:"number",notLessThanZero:!0},$I={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(i,t,e){if(this._room.isJoined)throw new de({code:pe.INVALID_OPERATION,extraCode:5104,fnName:e});if(i.roomId){if(ve(i.roomId))throw new de({code:pe.INVALID_PARAMETER,extraCode:5016,fnName:e,messageParams:{key:t}});if(!(/^[1-9]\d*$/.test(String(i.roomId))&&i.roomId<4294967295))throw new de({code:pe.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:t}})}else if(i.strRoomId){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(i.strRoomId))throw new de({code:pe.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:t}})}else throw new de({code:pe.INVALID_PARAMETER,extraCode:5015,fnName:e})},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"},playoutDelay:{type:"object",properties:{min:{type:"number",min:0,max:1e3},max:{type:"number",min:0,max:1e4}}}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:Zs,mute:{type:["boolean","string"]},publish:{type:"boolean"},option:zf},validate(i){var t;if(!((t=i==null?void 0:i.option)!=null&&t.videoTrack)&&ui())throw new de({code:pe.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:Ee(Z({},Zs),{required:!1}),publish:{type:"boolean"},mute:{type:["boolean","string"]},option:zf}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},option:Qf},validate(i){var t;if(!((t=i==null?void 0:i.option)!=null&&t.audioTrack)&&ui())throw new de({code:pe.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:"boolean"},option:Qf}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:Zs,publish:{type:"boolean"},option:Jf},validate(i,t,e,r,o){var s;if(!((s=i==null?void 0:i.option)!=null&&s.videoTrack)){if(ui())throw new de({code:pe.ENV_NOT_SUPPORTED,extraCode:5201});if(!ea())throw new de({code:pe.ENV_NOT_SUPPORTED,fnName:e,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:Zs,publish:{type:"boolean"},option:Jf}},muteRemoteAudio:[Xf,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[Xf,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:Zs,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(i,t,e){va(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(Yf(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new de({code:pe.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:i}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:Ee(Z({},Zs),{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(i,t,e){va(this._room.isJoined,e);let r=this._room.remotePublishedUserMap.get(i.userId);if(Yf(!!r,e,i),r&&(i.streamType==="main"&&!r.muteState.videoAvailable||i.streamType==="sub"&&!r.muteState.hasAuxiliary))throw new de({code:pe.INVALID_OPERATION,extraCode:5103,fnName:e,messageParams:{value:i}})}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(i,t,e){if(i.userId!=="*"&&V(i.streamType))throw new de({code:pe.INVALID_PARAMETER,extraCode:5014,fnName:e})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(i,t,e){va(this._room.isJoining||this._room.isJoined,e)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(i,t,e,r){if(!oa)throw new de({code:pe.ENV_NOT_SUPPORTED,fnName:e,extraCode:5207});if(!this._room.enableSEI)throw new de({code:pe.INVALID_OPERATION,fnName:e,extraCode:5108});if(i.byteLength>1e3)throw new de({code:pe.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new de({code:pe.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:e});va(this._room.isJoined,e)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(i,t,e){if(!i&&!this._room.isMainStreamPublished||i&&!this._room.isAuxStreamPublished)throw new de({code:pe.INVALID_OPERATION,extraCode:5109,messageParams:{key:t},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(i,t,e,r){if(i.byteLength>1e3)throw new de({code:pe.INVALID_PARAMETER,extraCode:5018,fnName:e});if(i.byteLength===0)throw new de({code:pe.INVALID_PARAMETER,extraCode:5017,fnName:e,messageParams:{key:t}})}}},validate(i,t,e){if(va(this._room.isJoined,e),this._room.scene==="live"&&this._room.role==="audience")throw new de({code:pe.INVALID_OPERATION,extraCode:5107,fnName:e,messageParams:{key:t}})}}},Rt={TRTC:$I};var Ft=class extends Error{};function BI(i,t){let e=Do(i);for(let r=0;r<t.length;r++)Lr(e[r],t[r]);return e}function HI(i){this._resolve=Promise.resolve(i)}function WI(i){this._reject=Promise.reject(i)}var io=class io{constructor(t,e){this.instance=t;this.group=e;u(this,"started",!1);u(this,"ops",[]);u(this,"startSame",()=>!0);u(this,"mergeUpdate",BI);let r=io.instances.get(t);r?r.set(e,this):io.instances.set(t,new Map([[e,this]]))}static get(t,e){if(!e)return;let r=io.instances.get(t);return r&&r.get(e)||new io(t,e)}static gets(t,e){let r=io.instances.get(t),o=[];return r&&r.forEach((s,n)=>{e.test(n)&&o.push(s)}),o}action(t,e,r){let o=d=>{var m;return t===0?this.started=!0:t===3&&(this.started=!1),this.ops.shift(),(m=this.currentOp)==null||m.action(),d},s=d=>{var m,l;throw this.ops.shift(),t===0&&((m=this.currentOp)==null?void 0:m.type)===2&&this.ops.shift().reject(new Ft("start failed")),(l=this.currentOp)==null||l.action(),d},n={type:t,action:()=>e(...n.args).then(o,s),args:r,resolve:HI,reject:WI};try{switch(this.state){case 1:if(t===0)throw new Ft("already started");break;case 4:if(t===2)throw new Ft("not started");break;default:return this.cacheOp(n)}}catch(d){return Promise.reject(d)}return this.ops.push(n),n.promise=e(...n.args).then(o,s)}cacheOp(t){if(this.ops.length===1)switch(this.state){case 0:case 2:if(t.type===0)throw new Ft("already start");break;case 3:switch(t.type){case 2:throw new Ft("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Ft("unknown state")}else switch(t.type){case 3:switch(this.lastOpType){case 3:return this.lastOp.promise;default:let r=new Ft("keep stop");if(this.ops.slice(1).forEach(o=>o.reject(r)),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,t.args),this.lastOp.promise;case 3:throw new Ft("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Ft("start not allowed after update");case 0:throw new Ft("duplicate start");case 3:if(this.startSame(this.currentOp.args,t.args))throw this.ops.pop().reject(new Ft("keep start")),new Ft("already start")}}t.promise=new Promise((r,o)=>{t._resolve?t._resolve.then(r):t.resolve=r,t._reject?t._reject.catch(o):t.reject=o});let{action:e}=t;return t.action=()=>e().then(t.resolve,t.reject),this.ops.push(t),t.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}};u(io,"instances",new WeakMap);var Ti=io;var Bd=new WeakMap,Hd=(i,t)=>{if(t instanceof Ft){let{stack:e}=t;t=new de({code:pe.OPERATION_ABORT,message:`${i} abort: ${t.message}`,fnName:i}),e&&(t.stack+=e.substr(e.indexOf(`
|
|
94
|
+
`)))}throw t};function oo(i,t){return Me((e,r)=>function(...o){let s=Ti.get(this,typeof i=="string"?i:i.call(this,...o));return s?(t&&(s.startSame=t.bind(this)),s.action(0,e.bind(this),o).catch(Hd.bind(null,r))):e.apply(this,o)})}function Ko(i,t){let{merge:e,debounce:r}=t||{};return Me((o,s)=>function(...n){let d=Ti.get(this,typeof i=="string"?i:i.call(this,...n));if(!d)return o.apply(this,n);if(e&&(d.mergeUpdate=e.bind(this)),r&&r.isNeedToDebounce.apply(this,n)){let{delay:m,getKey:l}=r;return new Promise((g,_)=>{var x,P;let S=(x=Bd.get(this))==null?void 0:x.get(l(...n));if(S){let{timeoutId:M,resolve:G}=S;clearTimeout(M),G()}let v=setTimeout(()=>{if(d.state===3||d.state===4)return g();d.action(2,o.bind(this),n).catch(Hd.bind(null,s)).then(g,_)},m);Bd.has(this)?(P=Bd.get(this))==null||P.set(l(...n),{timeoutId:v,resolve:g}):Bd.set(this,new Map([[l(...n),{timeoutId:v,resolve:g}]]))})}return d.action(2,o.bind(this),n).catch(Hd.bind(null,s))})}function so(i){return Me((t,e)=>function(...r){let o=typeof i=="function"?i.call(this,...r):i;if(o instanceof RegExp)return Promise.all(Ti.gets(this,o).map(n=>n.action(3,()=>Promise.resolve(),r))).then(()=>t.call(this,...r));let s=Ti.get(this,o);return s?s.action(3,t.bind(this),r).catch(Hd.bind(null,e)):t.apply(this,r)})}var K={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"},Zf=new Set([K.ERROR,K.AUTOPLAY_FAILED,K.KICKED_OUT,K.REMOTE_USER_ENTER,K.REMOTE_USER_EXIT,K.REMOTE_AUDIO_AVAILABLE,K.REMOTE_AUDIO_UNAVAILABLE,K.REMOTE_VIDEO_AVAILABLE,K.REMOTE_VIDEO_UNAVAILABLE,K.CONNECTION_STATE_CHANGED,K.PUBLISH_STATE_CHANGED,K.SCREEN_SHARE_STOPPED,K.DEVICE_CHANGED,K.FIRST_VIDEO_FRAME]);function no(i){return i==="sub"?"auxiliary":i==="auxiliary"?"sub":"main"}function Ca(i){return i===ur.QOS_PREFERENCE_CLEAR?"detail":i===ur.QOS_PREFERENCE_SMOOTH?"motion":""}var Qm={};Yr(Qm,{bytes2ms:()=>Bp,convertObjectNumberToInt:()=>wn,copyProperties:()=>$p,deepClone:()=>Do,deepMerge:()=>Lr,delay:()=>Mn,fibonacci:()=>No,formatedTime:()=>fc,getConstructorName:()=>Ts,getContainerFromElement:()=>Xp,getEnv:()=>Up,getInternalVersion:()=>zp,getLoggerUrl:()=>ti,getMediaStreamTrackInfo:()=>Ic,getMuteStateFromFlag:()=>Nn,getNetworkType:()=>vn,getNumNetworkType:()=>hc,getReconnectionTimeout:()=>Wp,getStringByteLength:()=>Qp,getTurnServer:()=>Jp,getUint32Version:()=>_c,getValueType:()=>nt,getViewListFromView:()=>ys,glog:()=>Cn,ipv4ToUint32:()=>Ss,isArray:()=>it,isAudioWorkletSupported:()=>qp,isBoolean:()=>dt,isConstructor:()=>wo,isEmpty:()=>Is,isFunction:()=>He,isLangChinese:()=>_r,isMediaStreamTrack:()=>Gp,isNumber:()=>We,isObject:()=>Er,isOverseaSdkAppId:()=>Rn,isPlainObject:()=>xt,isPortrait:()=>Ec,isPromise:()=>Ui,isRemoteTrack:()=>jp,isString:()=>ve,isUndefined:()=>V,loadImage:()=>As,ms2bytes:()=>Hp,ms2samples:()=>ju,normalizeUrl:()=>Mo,performanceNow:()=>Te,promiseAny:()=>Dn,samples2ms:()=>Gu,setNetworkType:()=>Fp,stringify:()=>ar,stringifyIncludeValue:()=>gc,throttlePromise:()=>Tc});var Km={};Yr(Km,{ScheduleRequestType:()=>eg,getAbilityConfig:()=>jI,getScheduleDomain:()=>tg,isNeedToSchedule:()=>Wd,scheduleProxy:()=>co,sendScheduleRequest:()=>Zm,setIsNeedToSchedule:()=>es,setScheduleProxy:()=>Gd});var Ym=null,Wd=!0;typeof document!="undefined"&&document.head.insertAdjacentHTML("beforeend",Object.values(ei).map(i=>`<link rel="dns-prefetch" href="https://${i}">`).join(`\r
|
|
95
|
+
`));function es(i){dt(i)&&i!==Wd&&(Wd=i,F.info(`setIsNeedToSchedule ${i}`))}L.on("28",()=>es(!0));L.on("63",()=>es(!0));L.on("84",()=>es(!0));L.on("201",i=>{i.state==="RECONNECTING"&&es(!0)});L.on("202",i=>{i.state==="RECONNECTING"&&es(!0)});function GI(i,t,e){let r={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let o=performance.getEntriesByType("resource"),s=ao(i,"config",N.MAIN),n=ao(i,"config",N.BACKUP);for(let d of o)if(d.startTime>=e&&(d.name===s||d.name===n)&&d.transferSize>0){let m=d.name===s?N.MAIN:N.BACKUP,l=Math.round(d.duration),g=Math.round(d.domainLookupStart-d.startTime),_=d.redirectStart>0?Math.round(d.redirectEnd-d.redirectStart):0,S=d.fetchStart>0?Math.round(d.domainLookupStart-d.fetchStart):0,v=Math.round(d.domainLookupEnd-d.domainLookupStart),x=Math.round(d.requestStart-d.secureConnectionStart),P=Math.round(d.secureConnectionStart-d.connectStart),M=Math.round(d.responseStart-d.requestStart),G=Math.round(d.responseEnd-d.responseStart),se=[v,x,P,M,G];je.uploadEvent({log:`stat-schedule-net:${l}(${g}(${_}->${S})->${se.join("->")}) ${m}`,userId:t}),r=Ee(Z({},r),{totalCost:l,local:g,dns:v,tcp:P,tls:x,request:M,response:G});break}}catch(o){F.error("getScheduleDetailCost error",o)}return r}function Zm(l){return A(this,arguments,function*({userId:i,sdkAppId:t,useStringRoomId:e,roomId:r,userSig:o,version:s,frameWorkType:n,role:d,latencyLevel:m}){if(!Wd&&Ym)return{isCached:!0,result:Ym};let g={delta:0,count:[1,1],msg:[],detail:[]};try{let _=new FormData;_.append("userId",String(i)),_.append("sdkAppId",String(t)),_.append("isStrGroupId",String(e)),_.append("groupId",String(r)),_.append("sdkVersion",s),_.append("userSig",String(o)),d&&_.append("role",String(d)),m&&_.append("latencyLevel",String(m)),n&&_.append("frameWorkType",String(n));let S=Te(),v=yield zI(_,g,t);v.config&&(v.config.loggerDomain&&Ro(v.config.loggerDomain),dt(v.config.scheduleCache)&&es(!v.config.scheduleCache)),g.delta=Te()-S;let x=GI(Number(t),i,S);return Ym=v,{isCached:!1,result:v,detailCost:x}}catch(_){let S=it(_)?_[0]:_,v=We(S.code)?S.code:0,x=`schedule failed${S.message?`: ${S.message}`:""}`,P=new ae({code:q.SCHEDULE_FAILED,extraCode:v,message:$e({key:Fe.JOIN_ROOM_FAILED,data:{error:x,code:v}})});throw F.error(x,v),P}})}var co={main:"",backup:""};function Gd(i){it(i)?(co.main=i[0],co.backup=i[1]):co.main=i}var eg=(r=>(r.CONFIG="config",r.TRTC_AUTO_CONF="trtcAutoConf",r.AUDIO_AI_AUTH="audioAiAuth",r))(eg||{});function ao(i,t,e=N.MAIN,r=!1){return`https://${co[e]||tg(i,e,r)}/api/v1/${t}`}function jI(i,t,e){let r=ao(i,t),o=ao(i,t,N.BACKUP),s=new URLSearchParams(e).toString(),n=fetch(`${r}?${s}`).then(m=>m.json()),d=fetch(`${o}?${s}`).then(m=>m.json());return Dn([n,d])}function tg(i,t=N.MAIN,e=!1){let r;return Rn(i)?e?r=t===N.MAIN?ei.MAIN_OVERSEA_BACKUP:ei.BACKUP_OVERSEA:r=t===N.MAIN?ei.MAIN_OVERSEA:ei.BACKUP_OVERSEA:r=t===N.MAIN?ei.MAIN:ei.BACKUP,r}function qI(i,t,e){return new Promise((r,o)=>{ri({url:i,body:t,timeout:e.timeout,priority:"high"}).then(s=>{s.data.code===0?r(s.data.data):o({code:s.data.code,message:s.data.msg})}).catch(o)})}var Kf=(i,t)=>Fi({retryFunction:qI,settings:{retries:3,timeout:0},onError:t,onRetrying:i});function zI(i,t,e){return new Promise((r,o)=>{let s=null;Dn([Kf(n=>t.count[0]=n+1,({error:n,retry:d,retriedCount:m,retryFuncArgs:l})=>{t.msg[0]=n.message,s||(m>=1&&(l[0]=ao(e,"config",N.MAIN,!0)),d())})(ao(e,"config",N.MAIN),i,{get timeout(){return No(2+t.count[0])*1e3}}),Kf(n=>t.count[1]=n+1,({error:n,retry:d,retriedCount:m,retryFuncArgs:l})=>{t.msg[1]=n.message,s||(m>=2&&(l[0]=ao(e,"config",N.BACKUP,!0)),d())})(ao(e,"config",N.BACKUP),i,{get timeout(){return No(2+t.count[1])*1e3}})]).then(n=>{s=n,r(s)}).catch(o)})}var JI=i=>i.startsWith("data:application/octet-stream;base64,"),XI=i=>i.startsWith("file://"),jd=class{constructor(){u(this,"_log");this._log=F.createLogger({id:"fd"})}download(t,e){return A(this,null,function*(){let{type:r="blob"}=e||{};t=Mo(t);try{let o=Te(),s;if(He(fetch)?s=yield this.downloadWithFetch(t,r):s=yield this.downloadWithXHR(t,r),!s||!s.data)throw new Error("data is empty");let n=Te()-o;return this._log.info(`downloaded: ${t}, return type: ${r}, cost: ${n}ms`),X.addSuccessEvent({key:522700,cost:Te()-o}),s.data}catch(o){throw this._log.error(`failed to download: ${t}, error: ${o}`),X.addFailedEvent({key:522700,error:o}),o}})}downloadWithFetch(t,e){return A(this,null,function*(){this._log.info(`download with fetch: ${t}, return type: ${e}`);try{let r=yield fetch(t);if(!r.ok)throw new Error("network response was not ok");let o;return e==="arraybuffer"?o=yield r.arrayBuffer():o=yield r.blob(),{data:o}}catch(r){throw r}})}downloadWithXHR(t,e){return this._log.info(`download with xhr: ${t}, return type: ${e}`),new Promise((r,o)=>{let s=new XMLHttpRequest;s.open("GET",t,!0),s.responseType=e,s.onload=()=>{s.status===200||s.status===0&&s.response?r({data:s.response}):o(new Error("XHR failed"))},s.onerror=o,s.send(null)})}loadWasm(t,e){return A(this,null,function*(){this._log.info(`loadWasm ${t}, importObject: ${JSON.stringify(e)}`);let r=Te(),o=null,s=null;if(He(WebAssembly.instantiateStreaming)&&!JI(t)&&!XI(t)&&He(fetch))try{let n=fetch(t);o=(yield WebAssembly.instantiateStreaming(n,e)).instance}catch(n){s=n}if(!o)try{let n=yield this.download(t,{type:"arraybuffer"});o=(yield WebAssembly.instantiate(n,e)).instance}catch(n){s=n}if(o){let n=Te()-r;return this._log.info(`loadedWasm ${t}, cost: ${n}ms`),X.addSuccessEvent({key:522701,cost:n}),o}throw this._log.error(`failed to loadWasm ${t}, error: ${s}`),X.addFailedEvent({key:522701,error:s}),s})}};J([Ji({settings:{timeout:0,retries:3},onRetrying(t){this._log.warn(`download retrying: ${t}`)}})],jd.prototype,"download",1);var rg=new jd;function ig({TRTC:i,room:t,errorModule:e,assetsPath:r}){return{TRTC:i,room:t,assetsPath:r,fileDownloader:rg,innerEmitter:L,constants:Wu,environment:ks,utils:Qm,eventLogger:je,log:this.room.getLogger(),loggerManager:F,errorModule:e,kvStatManager:X,rtcDectection:zi,trtc:this,rx:Hm,enums:vl,schedule:Km,clearStarted:(o,s)=>{let n=o.getAlias(),d=Ti.instances.get(this);if(d)if(s){let m=d.get(n+s);if(!m)return;m.started=!1}else d.forEach((m,l)=>{l.startsWith(n)&&(m.started=!1)})},startGetPCM:fa,createAudioNode:Yl}}var og=(i,t)=>{let{emit:e}=i;return i.emit=(...r)=>{try{return e.apply(i,r)}catch(o){let s=$e({key:Fe.CATCH_HANDLER_ERROR,data:{name:t,event:r[0]},addDocLink:!1});return F.warn(`${s}
|
|
56
96
|
|
|
57
|
-
${r.stack}`),!1}},s};var vs=new WeakMap;function xm(s){let i=vs.get(s);i&&(i.forEach(e=>clearTimeout(e)),vs.delete(s))}function Um(s,i){return z((e,t)=>function(...r){let o=vs.get(this);o||(o=new Map,vs.set(this,o));let n=i(...r),a=o.get(n);if(!a||a<=0){e.apply(this,r);let d=setTimeout(()=>{var l;(l=vs.get(this))==null||l.delete(n)},s);o.set(n,d)}else{clearTimeout(a);let d=window.setTimeout(()=>{var l;e.apply(this,r),(l=vs.get(this))==null||l.delete(n)},s);o.set(n,d)}})}var Bm="trtc-sdk-v5",Fm="5.10.2-beta.2";function qe(...s){return z((i,e)=>function(...t){try{Xa.call(this,s,t,e,this._name)}catch(r){return Promise.reject(r)}return i.apply(this,t)})}function Wl(...s){return z((i,e)=>function(...t){try{Xa.call(this,s,t,e,this._name)}catch(r){throw r}return i.apply(this,t)})}function Xa(s,i,e,t){if(Ie(s))for(let r=0;r<s.length;r++)qa.call(this,{rule:s[r],value:i[r],key:s[r].name,fnName:e,className:t});else qa.call(this,{rule:s,value:i[0],key:s.name,fnName:e,className:t})}function qa({rule:s,value:i,key:e,fnName:t,className:r}){function o(d){return{code:B.INVALID_PARAMETER,extraCode:d,fnName:t,messageParams:{key:e,rule:s,value:i}}}if(T(i)){if(s.required)throw new x(o(5001));if(T(s.defaultValue)){ce(s.validate)&&s.validate.call(this,i,e,t,r,this);return}i=s.defaultValue}if(Array.isArray(s.type)){let d=!1;for(let l=0;l<s.type.length;l++)s.type[l]===null&&i===null&&(d=!0),ce(s.type[l])&&i instanceof s.type[l]&&(d=!0),Z(s.type[l])&&ye(i)===s.type[l].toLowerCase()&&(d=!0);if(!d)throw new x({code:B.INVALID_PARAMETER,extraCode:5002,fnName:t,messageParams:{key:e,rule:{type:s.type.map(l=>qr(l)?Ks(l):Z(l)?l:ye(l))},value:i}})}else if(!T(s.type)&&ye(i)!==s.type)throw new x(o(5002));if(s.allowEmpty===!1){let d=Y(i)&&(i===0||Number.isNaN(i)),l=Z(i)&&i.trim()==="";if(d||l)throw new x(o(5003))}if(s.notLessThanZero&&Y(i)&&i<0)throw new x(o(5006));if(!T(s.min)&&Y(i)&&i<s.min)throw new x(o(5007));if(!T(s.max)&&Y(i)&&i>s.max)throw new x(o(5008));if(Z(s.instanceOf)){if(!i||i._name!==s.instanceOf)throw new x(o(5004))}else if(ce(s.instanceOf)&&!(i instanceof s.instanceOf))throw new x(o(5004));if(Array.isArray(s.values)&&!s.values.includes(i))throw new x(o(5005));let{properties:n}=s;rt(n)&&Gt(i)&&Object.keys(n).forEach(d=>{qa.call(this,{rule:n[d],value:i&&i[d],key:`${d}`,fnName:t,className:r})});let{arrayItem:a}=s;rt(a)&&Ie(i)&&i.forEach((d,l)=>{qa.call(this,{rule:a,value:d,key:`${e}[${l}]`,fnName:t,className:r})}),ce(s.validate)&&s.validate.call(this,i,e,t,r,this)}function fe(s={}){let{getRemoteId:i=()=>"",replaceArg:e,getKVReportKey:t,ignoreLog:r}=s;return z((o,n)=>function(...a){var h;function d(f,g,D){if(D&&D.includes(f))return"hided";if(e){let _=e(...a);if(a[_.argIndex]===g)return _.value}if(g===a||f in a)return g;try{return g instanceof HTMLElement?`id: ${g.id} type:${ye(g)}`:g instanceof MediaStreamTrack?bn(g):(JSON.stringify(g),g)}catch(_){return`type:${ye(g)}`}}let l=this._log||C;if(r!=null&&r(...a))return o.apply(this,a);a.length>0?l.info(`${n}() ${JSON.stringify(a,(f,g)=>d(f,g,["userSig","privateMapKey"]))}`):l.info(`${n}()`);let u=t?t(...a):Zn[n];try{let f=o.apply(this,a),g=P();return ji(f)?f.then(D=>(l.info(`${n}() success ${i.call(this,...a)}`),N.addSuccessEvent({key:u,cost:P()-g}),D)).catch(D=>{var k;D=x.convertFrom.call(this,D,n,a.length===1?a[0]:a);let _=D.extraCode||D.code,R=(k=D.message)!=null&&k.includes(_)?"":` code:${_}`;throw l.error(`${n}() failed ${i.call(this,...a)} ${D}${R} params: ${JSON.stringify(a,d)}`),N.addFailedEvent({key:u,error:D}),D}):(N.addSuccessEvent({key:u}),f)}catch(f){f=x.convertFrom.call(this,f,n);let g=f.extraCode||f.code,D=(h=f.message)!=null&&h.includes(g)?"":` code:${g}`;throw l.error(`${n}() failed ${f}${D} params: ${JSON.stringify(a,d)}`),N.addFailedEvent({key:u,error:f}),f}})}var za=s=>z((i,e)=>function(t,r){return p(this,null,function*(){let o=this._plugins.get(t);if(!o)throw this._log.error(`plugin ${String(t)} is not found`),new x({code:B.OPERATION_ABORT,message:`plugin ${String(t)} is not found`,fnName:e});if(ce(o.constructor.isSupported)&&!o.constructor.isSupported())throw this._log.error(`plugin ${String(t)} is not supported`),new x({code:B.ENV_NOT_SUPPORTED,message:`plugin ${String(t)} is not supported`,extraCode:5210,fnName:e});return Xa.call(this,o.getValidateRule(s),[r],e,"TRTC"),i.call(this,o,r)})});var Qa=0,Jl=class{constructor(i,e){c(this,"player");c(this,"publisher");c(this,"mixInput");this.mixInput=new gs(e),i.url?(this.player=new Audio(i.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(i.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(i.track),this.mixInput.connect()}updateSettings(i){this.player&&(T(i.volume)||(this.volume=i.volume),T(i.loop)||(this.loop=i.loop),T(i.playbackRate)||(this.playbackRate=i.playbackRate))}updateListener(i){if(this.player){if(i.onDurationChange){let{onDurationChange:e}=i;this.player.ondurationchange=t=>{e(t.target.duration)}}if(i.onTimeUpdate){let e=i.onTimeUpdate,{player:t}=this;t.ontimeupdate=()=>{e(t.currentTime,t.duration)}}i.onEnded&&(this.player.onended=i.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(i){this.player&&(i<0&&i>this.player.duration||(this.player.currentTime=i,this.publisher.currentTime=i))}play(){var i,e;return(i=this.publisher)==null||i.play(),(e=this.player)==null?void 0:e.play()}pause(){var i,e;(i=this.player)==null||i.pause(),(e=this.publisher)==null||e.pause()}stop(){var i;(i=this.player)==null||i.pause(),this.mixInput.disconnect()}setOperation(i){i==="pause"&&this.pause(),i==="resume"&&(this.pause(),this.play()),i==="stop"&&(this.pause(),this.seek(0))}set volume(i){!this.player||!this.publisher||(this.player.volume=i,this.publisher.volume=i)}set loop(i){!this.player||!this.publisher||(this.player.loop=i,this.publisher.loop=i)}set playbackRate(i){!this.player||!this.publisher||(this.player.playbackRate=i,this.publisher.playbackRate=i)}};function Ds(s,i){if(i&&typeof i!="function")throw new x({code:B.INVALID_PARAMETER,message:`start audioMixer plugin: param ${s} should be a function.`})}var li=class li{constructor(i){this.core=i;c(this,"log");c(this,"mixedMusicMap",new Map);c(this,"cacheMusicMap",new Map);Qa=Qa+1,this.log=i.log.createChild({id:`${this.getAlias()}${Qa}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Qa}`),this.core=i}getName(){return li.Name}getAlias(){return"ax"}getGroup(i){return i==null?void 0:i.id}getValidateRule(i){switch(i){case"start":return li.startValidateRule;case"update":return li.updateValidateRule;case"stop":return li.stopValidateRule}}start(i){return p(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 Jl(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 p(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),T(t)||n.setOperation(t),T(r)||n.seek(r),this.kvUpload(i)})}stop(e){return p(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:d,onDurationChange:l,onEnded:u}=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 d!="function"&&N.addCount({key:502709}),typeof u!="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()}};c(li,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(i,e,t){if(i.url&&i.url!=="*"){let r=i.url.split("?")[0],o=["mp3","ogg","wav","flac"],n=r.split(".").pop(),a=o.indexOf(n)>=0,d=r.startsWith("blob"),l=r.startsWith("data");if(!(a||d||l))throw new x({code:B.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:t})}if(!i.url&&!i.track)throw new x({code:B.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:t});Ds("onTimeUpdate",i.onTimeUpdate),Ds("onEnded",i.onEnded),Ds("onDurationChange",i.onDurationChange)}}),c(li,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(i,e,t){Ds("onTimeUpdate",i.onTimeUpdate),Ds("onEnded",i.onEnded),Ds("onDurationChange",i.onDurationChange)}}),c(li,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),c(li,"Name","AudioMixer");var Ya=li;var Ka=0,jl,Bi=class Bi{constructor(i){this.core=i;c(this,"log");c(this,"audioContext",ve("denoiser"));c(this,"workletNode");Ka=Ka+1,this.log=i.log.createChild({id:`${this.getAlias()}${Ka}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${Ka}`),i.assetsPath&&this.preload(`${i.assetsPath}/denoiser-wasm.js`).catch(e=>{})}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 x({code:B.INVALID_OPERATION,extraCode:5106,fnName:r})}}}preload(i){return jl||(jl=this.doPreload(i)),jl}doPreload(i){return p(this,null,function*(){let e=yield this.core.fileDownloader.download(i,{type:"blob"}),t=URL.createObjectURL(e);try{yield Rr(this.audioContext,t)}catch(r){throw this.log.error("load worklet failed",r),r}finally{URL.revokeObjectURL(t)}})}getName(){return Bi.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(i){switch(i){case"start":return Bi.startValidateRule(this.core);case"update":return Bi.updateValidateRule;case"stop":return Bi.stopValidateRule}}start(i){return p(this,null,function*(){let{room:e,schedule:t}=this.core;if(yield this.preload(`${i.assetsPath}/denoiser-wasm.js`),!this.workletNode){let r=String(Date.now()).slice(0,-3),{auth:o,sign:n,status:a,message:d}=yield TT(t,L(v({},i),{timestamp:r}));if(!o)throw this.log.info(`RTCAIDenoiser: ${i.userId} auth result: ${o}. Message: ${d}`),new x({code:B.INVALID_PARAMETER,message:d});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:r,sign:n,status:a}}),this.workletNode.port.onmessage=l=>{var h;let{data:u}=l;if(u.type==="cost"){let f=(u==null?void 0:u.max)>20?"warn":(u==null?void 0:u.max)>10?"info":"debug";this.log[f](`avg cost: ${u.value} max: ${u==null?void 0:u.max}(${dn(new Date(u==null?void 0:u.maxCostTimestamp))}) hist: ${(h=u==null?void 0:u.hist)==null?void 0:h.join(" ")}`)}else u.type==="log"&&this.log[u.logLevel](`${u.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return p(this,null,function*(){})}stop(){return p(this,null,function*(){if(!this.workletNode)return;let{room:i}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield i.audioManager.removeDenoiser(this.workletNode)})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};c(Bi,"updateValidateRule",{type:"object"}),c(Bi,"stopValidateRule",{type:"object"}),c(Bi,"Name","AIDenoiser");var Za=Bi;function TT(o,n){return p(this,arguments,function*(s,{sdkAppId:i,userId:e,userSig:t,timestamp:r}){try{let{data:{errCode:a,errMsg:d,sign:l,status:u}}=yield s.getAbilityConfig(i,s.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:i,userId:e,userSig:t,timestamp:r});if(u==="1")return{auth:!0,sign:l,status:u,message:d};let h="Init RTCAIDenoiser failed.",f="";switch(a){case 1:f="Please check your params.";break;case 2:f="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:f="Server is invalid. Please contact our engineer. ";break;case 4:f="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:f="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:f="Your version is not supported.";break}return{auth:!1,status:u,message:d?`${h} Reason: ${d}. ${f}`:`${h}, ${f}`}}catch(a){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${a}`}}})}var Hm=Be(ze(),1);var ql=class extends Hm.EventEmitter{constructor(){super();c(this,"observer");c(this,"state","nominal");this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return p(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!he&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){te.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){te.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},ET=new ql,Xl=ET;function zl([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 Li(new DataView(new Uint8Array(o).buffer),!0)}function Ql(s){return s.type==="empty"||s.data.byteLength===0}function Yl(s){return s.getInt32(0)===1&&s.getInt8(4)===6}function Kl(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 Zl({frame:s,seiMessageList:i}){if(!i||i.length===0||s.data.byteLength===0)return s;let t=9-Kl(s.data);if(t<=0)return s;let r=i.splice(0,t).reverse().map(zl),o=r.reduce((u,h)=>u+h.dataView.byteLength,0),n=new ArrayBuffer(o+s.data.byteLength),a=new DataView(n),d=new DataView(s.data),l=0;for(let u=0;u<r.length;u++)for(let h=0;h<r[u].dataView.byteLength;h++)a.setInt8(l++,r[u].dataView.getInt8(h));for(let u=0;u<s.data.byteLength;u++)a.setInt8(l++,d.getInt8(u));return s.data=n,s}function eu({frame:s,onSEI:i}){try{let e=new DataView(s.data);if(Ql(s)||!Yl(e))return s;let t=[],r=0,o=-1,n=-1;for(let a=0;a<s.data.byteLength;a++){let d=e.getUint8(a);if(d===0)r++;else if(d===1){if(r===2||r===3){let l=a-r;if(o===-1?o=l:n===-1&&(n=l,t.push(new Li(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 tu=0,qo=class qo{constructor(i){this.core=i;c(this,"log");c(this,"_seiMessageList",[]);c(this,"_smallSeiMessageList",[]);c(this,"_subStreamSeiMessageList",[]);tu++,this.log=i.log.createChild({id:`${this.getAlias()}${tu}`}),this.log.info(`[sei] created id=${this.getAlias()}${tu}`),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 Zl({frame:i,seiMessageList:t})}catch(t){this.log.warn(t)}return i}decode({frame:i,track:e}){return eu({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:Di?this.encode:Zl,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:Di?this.decode:eu,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 qo.Name}getAlias(){return"sei"}getGroup(){return"sei"}};c(qo,"autoStart",!0),c(qo,"Name","SEI");var ec=qo;function iu({frame:s,onDump:i}){return i==null||i(),s}function ru({frame:s,onDump:i}){return i==null||i(),s}var $m={"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:
|
|
97
|
+
${o.stack}`),!1}},i};var Ks=new WeakMap;function sg(i){let t=Ks.get(i);t&&(t.forEach(e=>clearTimeout(e)),Ks.delete(i))}function ng(i,t){return Me((e,r)=>function(...o){let s=Ks.get(this);s||(s=new Map,Ks.set(this,s));let n=t(...o),d=s.get(n);if(!d||d<=0){e.apply(this,o);let m=setTimeout(()=>{var l;(l=Ks.get(this))==null||l.delete(n)},i);s.set(n,m)}else{clearTimeout(d);let m=window.setTimeout(()=>{var l;e.apply(this,o),(l=Ks.get(this))==null||l.delete(n)},i);s.set(n,m)}})}var cg="trtc-sdk-v5",dg="5.10.2-wasm.1";function $t(...i){return Me((t,e)=>function(...r){try{zd.call(this,i,r,e,this._name)}catch(o){return Promise.reject(o)}return t.apply(this,r)})}function ep(...i){return Me((t,e)=>function(...r){try{zd.call(this,i,r,e,this._name)}catch(o){throw o}return t.apply(this,r)})}function zd(i,t,e,r){if(it(i))for(let o=0;o<i.length;o++)qd.call(this,{rule:i[o],value:t[o],key:i[o].name,fnName:e,className:r});else qd.call(this,{rule:i,value:t[0],key:i.name,fnName:e,className:r})}function qd({rule:i,value:t,key:e,fnName:r,className:o}){function s(m){return{code:pe.INVALID_PARAMETER,extraCode:m,fnName:r,messageParams:{key:e,rule:i,value:t}}}if(V(t)){if(i.required)throw new de(s(5001));if(V(i.defaultValue)){He(i.validate)&&i.validate.call(this,t,e,r,o,this);return}t=i.defaultValue}if(Array.isArray(i.type)){let m=!1;for(let l=0;l<i.type.length;l++)i.type[l]===null&&t===null&&(m=!0),He(i.type[l])&&t instanceof i.type[l]&&(m=!0),ve(i.type[l])&&nt(t)===i.type[l].toLowerCase()&&(m=!0);if(!m)throw new de({code:pe.INVALID_PARAMETER,extraCode:5002,fnName:r,messageParams:{key:e,rule:{type:i.type.map(l=>wo(l)?Ts(l):ve(l)?l:nt(l))},value:t}})}else if(!V(i.type)&&nt(t)!==i.type)throw new de(s(5002));if(i.allowEmpty===!1){let m=We(t)&&(t===0||Number.isNaN(t)),l=ve(t)&&t.trim()==="";if(m||l)throw new de(s(5003))}if(i.notLessThanZero&&We(t)&&t<0)throw new de(s(5006));if(!V(i.min)&&We(t)&&t<i.min)throw new de(s(5007));if(!V(i.max)&&We(t)&&t>i.max)throw new de(s(5008));if(ve(i.instanceOf)){if(!t||t._name!==i.instanceOf)throw new de(s(5004))}else if(He(i.instanceOf)&&!(t instanceof i.instanceOf))throw new de(s(5004));if(Array.isArray(i.values)&&!i.values.includes(t))throw new de(s(5005));let{properties:n}=i;xt(n)&&Er(t)&&Object.keys(n).forEach(m=>{qd.call(this,{rule:n[m],value:t&&t[m],key:`${m}`,fnName:r,className:o})});let{arrayItem:d}=i;xt(d)&&it(t)&&t.forEach((m,l)=>{qd.call(this,{rule:d,value:m,key:`${e}[${l}]`,fnName:r,className:o})}),He(i.validate)&&i.validate.call(this,t,e,r,o,this)}function et(i={}){let{getRemoteId:t=()=>"",replaceArg:e,getKVReportKey:r,ignoreLog:o}=i;return Me((s,n)=>function(...d){var _;function m(S,v,x){if(x&&x.includes(S))return"hided";if(e){let P=e(...d);if(d[P.argIndex]===v)return P.value}if(v===d||S in d)return v;try{return v instanceof HTMLElement?`id: ${v.id} type:${nt(v)}`:v instanceof MediaStreamTrack?Ic(v):(JSON.stringify(v),v)}catch(P){return`type:${nt(v)}`}}let l=this._log||F;if(o!=null&&o(...d))return s.apply(this,d);d.length>0?l.info(`${n}() ${JSON.stringify(d,(S,v)=>m(S,v,["userSig","privateMapKey"]))}`):l.info(`${n}()`);let g=r?r(...d):Jc[n];try{let S=s.apply(this,d),v=Te();return Ui(S)?S.then(x=>(l.info(`${n}() success ${t.call(this,...d)}`),X.addSuccessEvent({key:g,cost:Te()-v}),x)).catch(x=>{var G;x=de.convertFrom.call(this,x,n,d.length===1?d[0]:d);let P=x.extraCode||x.code,M=(G=x.message)!=null&&G.includes(P)?"":` code:${P}`;throw l.error(`${n}() failed ${t.call(this,...d)} ${x}${M} params: ${JSON.stringify(d,m)}`),X.addFailedEvent({key:g,error:x}),x}):(X.addSuccessEvent({key:g}),S)}catch(S){S=de.convertFrom.call(this,S,n);let v=S.extraCode||S.code,x=(_=S.message)!=null&&_.includes(v)?"":` code:${v}`;throw l.error(`${n}() failed ${S}${x} params: ${JSON.stringify(d,m)}`),X.addFailedEvent({key:g,error:S}),S}})}var Jd=i=>Me((t,e)=>function(r,o){return A(this,null,function*(){let s=this._plugins.get(r);if(!s)throw this._log.error(`plugin ${String(r)} is not found`),new de({code:pe.OPERATION_ABORT,message:`plugin ${String(r)} is not found`,fnName:e});if(He(s.constructor.isSupported)&&!s.constructor.isSupported())throw this._log.error(`plugin ${String(r)} is not supported`),new de({code:pe.ENV_NOT_SUPPORTED,message:`plugin ${String(r)} is not supported`,extraCode:5210,fnName:e});return zd.call(this,s.getValidateRule(i),[o],e,"TRTC"),t.call(this,s,o)})});var Xd=0,tp=class{constructor(t,e){u(this,"player");u(this,"publisher");u(this,"mixInput");this.mixInput=new Ws(e),t.url?(this.player=new Audio(t.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(t.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(t.track),this.mixInput.connect()}updateSettings(t){this.player&&(V(t.volume)||(this.volume=t.volume),V(t.loop)||(this.loop=t.loop),V(t.playbackRate)||(this.playbackRate=t.playbackRate))}updateListener(t){if(this.player){if(t.onDurationChange){let{onDurationChange:e}=t;this.player.ondurationchange=r=>{e(r.target.duration)}}if(t.onTimeUpdate){let e=t.onTimeUpdate,{player:r}=this;r.ontimeupdate=()=>{e(r.currentTime,r.duration)}}t.onEnded&&(this.player.onended=t.onEnded)}}reset(){this.seek(0),this.mixInput.connect()}seek(t){this.player&&(t<0&&t>this.player.duration||(this.player.currentTime=t,this.publisher.currentTime=t))}play(){var t,e;return(t=this.publisher)==null||t.play(),(e=this.player)==null?void 0:e.play()}pause(){var t,e;(t=this.player)==null||t.pause(),(e=this.publisher)==null||e.pause()}stop(){var t;(t=this.player)==null||t.pause(),this.mixInput.disconnect()}setOperation(t){t==="pause"&&this.pause(),t==="resume"&&(this.pause(),this.play()),t==="stop"&&(this.pause(),this.seek(0))}set volume(t){!this.player||!this.publisher||(this.player.volume=t,this.publisher.volume=t)}set loop(t){!this.player||!this.publisher||(this.player.loop=t,this.publisher.loop=t)}set playbackRate(t){!this.player||!this.publisher||(this.player.playbackRate=t,this.publisher.playbackRate=t)}};function en(i,t){if(t&&typeof t!="function")throw new de({code:pe.INVALID_PARAMETER,message:`start audioMixer plugin: param ${i} should be a function.`})}var jr=class jr{constructor(t){this.core=t;u(this,"log");u(this,"mixedMusicMap",new Map);u(this,"cacheMusicMap",new Map);Xd=Xd+1,this.log=t.log.createChild({id:`${this.getAlias()}${Xd}`}),this.log.info(`[audioMixer] created id=${this.getAlias()}${Xd}`),this.core=t}getName(){return jr.Name}getAlias(){return"ax"}getGroup(t){return t==null?void 0:t.id}getValidateRule(t){switch(t){case"start":return jr.startValidateRule;case"update":return jr.updateValidateRule;case"stop":return jr.stopValidateRule}}start(t){return A(this,null,function*(){let{room:e}=this.core;this.log.info(`add music source, id: ${t.id} url: ${t.url}, track: ${t.track}`);let{id:r,url:o}=t;if(this.mixedMusicMap.has(r))return;let s=this.cacheMusicMap.get(r);s?t.url?s.reset():(s.mixInput.replaceSource(t.track),s.mixInput.connect()):(s=new tp(t,e.audioManager),this.cacheMusicMap.set(r,s)),s.updateListener(t),s.updateSettings(t),yield s.play(),this.mixedMusicMap.set(r,s),this.log.info(`start mix audio track ${r} success.`),X.addEnum({key:502700,value:3}),this.kvUpload(t)})}update(t){return A(this,null,function*(){let{id:e,operation:r,seekFrom:o,playbackRate:s}=t;this.log.info(`update music source, ${JSON.stringify(t)}`);let n=this.mixedMusicMap.get(e);if(!n){this.log.warn(`update music source failed, music id: ${e} not found.`);return}n.updateSettings(t),n.updateListener(t),V(r)||n.setOperation(r),V(o)||n.seek(o),this.kvUpload(t)})}stop(e){return A(this,arguments,function*({id:t}){var r;this.mixedMusicMap.has(t)&&(this.log.info(`remove music source, music id: ${t}`),(r=this.mixedMusicMap.get(t))==null||r.stop(),this.mixedMusicMap.delete(t)),t==="*"&&this.destroyAllMusic()})}kvUpload(t){let{track:e,loop:r,volume:o,playbackRate:s,operation:n,seekFrom:d,onTimeUpdate:m,onDurationChange:l,onEnded:g}=t;e&&X.addCount({key:502711}),r&&X.addCount({key:502703}),o&&X.addCount({key:502704}),s&&X.addCount({key:502705}),n&&X.addCount({key:502706}),d&&X.addCount({key:502707}),typeof m!="function"&&X.addCount({key:502709}),typeof g!="function"&&X.addCount({key:502710}),typeof l!="function"&&X.addCount({key:502708})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((t,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()}};u(jr,"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(t,e,r){if(t.url&&t.url!=="*"){let o=t.url.split("?")[0],s=["mp3","ogg","wav","flac"],n=o.split(".").pop(),d=s.indexOf(n)>=0,m=o.startsWith("blob"),l=o.startsWith("data");if(!(d||m||l))throw new de({code:pe.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:r})}if(!t.url&&!t.track)throw new de({code:pe.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:r});en("onTimeUpdate",t.onTimeUpdate),en("onEnded",t.onEnded),en("onDurationChange",t.onDurationChange)}}),u(jr,"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(t,e,r){en("onTimeUpdate",t.onTimeUpdate),en("onEnded",t.onEnded),en("onDurationChange",t.onDurationChange)}}),u(jr,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),u(jr,"Name","AudioMixer");var Qd=jr;var Yd=0,rp,Ii=class Ii{constructor(t){this.core=t;u(this,"log");u(this,"audioContext",Ke("denoiser"));u(this,"workletNode");Yd=Yd+1,this.log=t.log.createChild({id:`${this.getAlias()}${Yd}`}),this.log.info(`[audioDenoiser] created id=${this.getAlias()}${Yd}`),t.assetsPath&&this.preload(`${t.assetsPath}/denoiser-wasm.js`).catch(e=>{})}static startValidateRule(t){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,r,o,s){if(!t.room.audioManager.hasAudioTrack)throw new de({code:pe.INVALID_OPERATION,extraCode:5106,fnName:o})}}}preload(t){return rp||(rp=this.doPreload(t)),rp}doPreload(t){return A(this,null,function*(){let e=yield this.core.fileDownloader.download(t,{type:"blob"}),r=URL.createObjectURL(e);try{yield $o(this.audioContext,r)}catch(o){throw this.log.error("load worklet failed",o),o}finally{URL.revokeObjectURL(r)}})}getName(){return Ii.Name}getAlias(){return"ad"}getGroup(){return`AIDenoiser_${Date.now()}`}getValidateRule(t){switch(t){case"start":return Ii.startValidateRule(this.core);case"update":return Ii.updateValidateRule;case"stop":return Ii.stopValidateRule}}start(t){return A(this,null,function*(){let{room:e,schedule:r}=this.core;if(yield this.preload(`${t.assetsPath}/denoiser-wasm.js`),!this.workletNode){let o=String(Date.now()).slice(0,-3),{auth:s,sign:n,status:d,message:m}=yield QI(r,Ee(Z({},t),{timestamp:o}));if(!s)throw this.log.info(`RTCAIDenoiser: ${t.userId} auth result: ${s}. Message: ${m}`),new de({code:pe.INVALID_PARAMETER,message:m});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(t.sdkAppId),userId:t.userId,timestamp:o,sign:n,status:d}}),this.workletNode.port.onmessage=l=>{var _;let{data:g}=l;if(g.type==="cost"){let S=(g==null?void 0:g.max)>20?"warn":(g==null?void 0:g.max)>10?"info":"debug";this.log[S](`avg cost: ${g.value} max: ${g==null?void 0:g.max}(${oc(new Date(g==null?void 0:g.maxCostTimestamp))}) hist: ${(_=g==null?void 0:g.hist)==null?void 0:_.join(" ")}`)}else g.type==="log"&&this.log[g.logLevel](`${g.value}`)}}this.workletNode.port.postMessage({type:"enable"}),e.audioManager.addDenoiser(this.workletNode),e.sendAbilityStatus({ai_denoise:1})})}update(){return A(this,null,function*(){})}stop(){return A(this,null,function*(){if(!this.workletNode)return;let{room:t}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield t.audioManager.removeDenoiser(this.workletNode)})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};u(Ii,"updateValidateRule",{type:"object"}),u(Ii,"stopValidateRule",{type:"object"}),u(Ii,"Name","AIDenoiser");var Zd=Ii;function QI(s,n){return A(this,arguments,function*(i,{sdkAppId:t,userId:e,userSig:r,timestamp:o}){try{let{data:{errCode:d,errMsg:m,sign:l,status:g}}=yield i.getAbilityConfig(t,i.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:t,userId:e,userSig:r,timestamp:o});if(g==="1")return{auth:!0,sign:l,status:g,message:m};let _="Init RTCAIDenoiser failed.",S="";switch(d){case 1:S="Please check your params.";break;case 2:S="You need to buy packages. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 3:S="Server is invalid. Please contact our engineer. ";break;case 4:S="Your packages is not active. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 5:S="Your packages is expired. Refer to: https://cloud.tencent.com/document/product/647/44247";break;case 6:S="Your version is not supported.";break}return{auth:!1,status:g,message:m?`${_} Reason: ${m}. ${S}`:`${_}, ${S}`}}catch(d){return{auth:!1,status:"0",message:`Init RTCAIDenoiser failed. All requests failed. ${d}`}}})}var ug=ki(Wi(),1);var ip=class extends ug.EventEmitter{constructor(){super();u(this,"observer");u(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 A(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!ut&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(e){je.uploadEvent({log:"stat-pressure-detector-start-failed",error:e})}})}onPressureChange(e){let r=this.stateNum,o=e[e.length-1];this.state=o.state,(this.stateNum>3||r>3)&&F.info(`${o.source}: ${o.state}`),this.emit("state-changed",{type:o.source,state:this.state})}destroy(){var e;try{(e=this.observer)==null||e.disconnect(),this.observer=null}catch(r){je.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:r})}}},YI=new ip,op=YI;function ZI([i,t]){let e=t.byteLength,r=parseInt(String(e/255),10),o=e%255,s=[];s.push(0,0,0,1,6,i);for(let d=0;d<r;d++)s.push(255);s.push(o);let n=new DataView(t);return s.push(...new Uint8Array(n.buffer)),s.push(128),new Wo(new DataView(new Uint8Array(s).buffer),!0)}function KI(i){return i.type==="empty"||i.data.byteLength===0}function eS(i){return i.getInt32(0)===1&&i.getInt8(4)===6}function tS(i){let t=0,e=0,r=new DataView(i);for(let o=0;o<i.byteLength;o++)switch(r.getUint8(o)){case 0:t++;break;case 1:(t===2||t===3)&&e++,t=0;break;default:t=0;break}return e}function sp({frame:i,seiMessageList:t}){if(!t||t.length===0||i.data.byteLength===0)return i;let r=9-tS(i.data);if(r<=0)return i;let o=t.splice(0,r).reverse().map(ZI),s=o.reduce((g,_)=>g+_.dataView.byteLength,0),n=new ArrayBuffer(s+i.data.byteLength),d=new DataView(n),m=new DataView(i.data),l=0;for(let g=0;g<o.length;g++)for(let _=0;_<o[g].dataView.byteLength;_++)d.setInt8(l++,o[g].dataView.getInt8(_));for(let g=0;g<i.data.byteLength;g++)d.setInt8(l++,m.getInt8(g));return i.data=n,i}function np({frame:i,onSEI:t}){try{let e=new DataView(i.data);if(KI(i)||!eS(e))return i;let r=[],o=0,s=-1,n=-1;for(let d=0;d<i.data.byteLength;d++){let m=e.getUint8(d);if(m===0)o++;else if(m===1){if(o===2||o===3){let l=d-o;if(s===-1?s=l:n===-1&&(n=l,r.push(new Wo(new DataView(e.buffer.slice(s,n)))),s=l,n=-1),!(e.getUint8(d+1)===6)){i.data=e.buffer.slice(l);break}}o=0}else o=0}t==null||t(r.reverse())}catch(e){}return i}var ap=0,Da=class Da{constructor(t){this.core=t;u(this,"log");u(this,"_seiMessageList",[]);u(this,"_smallSeiMessageList",[]);u(this,"_subStreamSeiMessageList",[]);ap++,this.log=t.log.createChild({id:`${this.getAlias()}${ap}`}),this.log.info(`[sei] created id=${this.getAlias()}${ap}`),this.core=t,this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode({frame:t,mediaType:e}){try{let r=e===8?this._smallSeiMessageList:e===2?this._subStreamSeiMessageList:this._seiMessageList;return sp({frame:t,seiMessageList:r})}catch(r){this.log.warn(r)}return t}decode({frame:t,track:e}){return np({frame:t,onSEI:r=>{r.forEach(o=>{this.core.trtc.emit(K.SEI_MESSAGE,{seiPayloadType:o.seiPayloadType,data:o.seiPayload.buffer,userId:e.userId,streamType:e.mediaType===2?"sub":"main"})})}})}destroy(){this.log.debug("destory"),this.stop(),delete this.core}getValidateRule(t){switch(t){case"start":return{type:"object"};case"update":return{type:"object"};case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:ia?this.encode:sp,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:ia?this.decode:np,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update({buffer:t,options:e}){var s;let r=[e.seiPayloadType,t],o=!!e.small;e.toSubStream?this._subStreamSeiMessageList.push(r):(this._seiMessageList.push(r),o&&this._smallSeiMessageList.push(r)),(s=this.core.room.scriptTransformWorker)==null||s.postMessage({type:"sei",data:r,isMain:!e.toSubStream,small:o})}getName(){return Da.Name}getAlias(){return"sei"}getGroup(){return"sei"}};u(Da,"autoStart",!0),u(Da,"Name","SEI");var Kd=Da;function cp({frame:i,onDump:t}){return t==null||t(),i}function dp({frame:i,onDump:t}){return t==null||t(),i}var lg={"play() error: NotAllowedError:":{tips:i=>i.includes("main <video>")||i.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:i=>i.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:i=>i.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:
|
|
58
98
|
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.
|
|
59
99
|
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:
|
|
60
100
|
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.
|
|
61
|
-
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=>{$m[`${s}()`]={tips:`Call trtc.${s}`,color:"blue",class:"blue",textColor:"#fff"}});var dM=Object.keys($m);var ST=0,tc,Os=class Os{constructor(i){this.core=i;c(this,"_core");c(this,"log");c(this,"dumpLocalVideoMap",{});c(this,"dumpRemoteVideoMap",{});c(this,"dialog");this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${++ST}`}),this.log.info("created")}getName(){return Os.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(i){switch(i){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return p(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog(),this.addVideoProcessor())})}update(){}stop(){this.closeDebugDiaLog(),this.removeVideoProcessor()}destroy(){this.stop()}openDebugDiaLog(){return p(this,null,function*(){var i;try{if(tc)yield tc;else{let e=Date.now(),t=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((i=window.sessionStorage)==null?void 0:i.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${Bm}@${Oe}/assets/debug-dialog.js`;tc=this.loadScript(t),yield tc,this.log.info(`download debug dialog script cost: ${Date.now()-e}ms`)}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(e){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(e))}})}closeDebugDiaLog(){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):iu,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):ru,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo({frame:i,mediaType:e}){return iu({frame:i,onDump:()=>{if(!e)return;let t=e===2?"sub":"main",r=this.dumpLocalVideoMap[t];r&&(r.data.push(i.data.slice(0)),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}})}decodeVideo({frame:i,track:e}){return ru({frame:i,onDump:()=>{if(!e)return;let t=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];t&&(t.data.push(i.data.slice(0)),t.duration>0&&Date.now()-t.startTimestamp>t.duration*1e3&&t.onDumpEnd())}})}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)})}};c(Os,"Name","Debug"),c(Os,"autoStart",!0),y([ot({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)}})],Os.prototype,"loadScript",1);var ic=Os;var Gm=s=>{switch(s){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},rc=class{constructor(i,e,t){c(this,"trackDoneOB");c(this,"startOB");c(this,"stopOB");c(this,"inputFrameCount",0);c(this,"decodedFrameCount",0);c(this,"type","auto");c(this,"config");c(this,"decoder");c(this,"_decodeSink");let{kvStatManager:r,trtc:o}=i;this.config=t.config,this.trackDoneOB=ue(e,F.INIT),this.stopOB=Ze(),this.startOB=Ze(),t.type==="auto"?this.type="webCodecs":this.type=t.type;let n=Ze(),a=d=>{let l=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),de(l,we(this.stopOB),Ae(()=>{},u=>{e.log.error(u),r.addFailedEvent({key:Gm(this.type),error:u}),d>4?this.startOB.error(u):this.startOB.next(d+1)})),de(l,xi(1),kl(Ho))};de(this.startOB,Bo(0),Is(a),we(this.stopOB),Ae(()=>{e.player.setOutput(),n.next("STARTED")},d=>{n.next("FAILED")},()=>{r.addSuccessEvent({key:Gm(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 wi()(e=>p(this,null,function*(){this._decodeSink=e,e.defer(()=>{var r;(r=this.decoder)==null||r.close()});let{type:t}=this;try{switch(t){case"webCodecs":this.decoder=new AudioDecoder({error:r=>{i.log.error(r),e.error(4)},output:r=>{this.decodedFrameCount++,e.next(r),i.player.write(r)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(r){i.log.error(r),e.error(t==="webCodecs"?2:6)}}))}decodeFrame(i){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:i.data,timestamp:i.timestamp,type:"key"}))}},IT={type:"object"},Xo=class Xo{constructor(i){this.core=i;c(this,"log");c(this,"contextMap",new Map);c(this,"decodeProcessorMap",new WeakMap);this.log=i.log.createChild({id:`${this.getAlias()}`})}getAlias(){return Xo.Name}getGroup(i){return i.track.userId+i.track.streamType}getName(){return Xo.Name}getValidateRule(i){return IT}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 rc(this.core,t,i);return de(r.trackDoneOB,xi(1),Ae(()=>{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 rc(this.core,i.track,i))}}};c(Xo,"Name","TRTCAudioDecoder");var zo=Xo;var Wm=0,Qo=new Set,Ue=null;Cc(Fm);ls.checkStorage();Md();var AT={RtcError:x,ErrorCode:B,ErrorCodeDictionary:xt},W=class W extends Jm.EventEmitter{constructor(e,t){super();c(this,"_room");c(this,"_eventListened",new Set);c(this,"_localVideoTrack",null);c(this,"_localAudioTrack",null);c(this,"_localScreenTrack",null);c(this,"_localScreenAudioTrack",null);c(this,"_localVideoConfig",null);c(this,"_localScreenConfig",null);c(this,"_localAudioConfig",null);c(this,"_remoteVideoConfigMap",new Map);c(this,"_remoteAudioConfigMap",new Map);c(this,"_remoteAudioVolumeMap",new Map);c(this,"_remoteAudioMuteMap",new Map);c(this,"_mediaTrackMap",new WeakMap);c(this,"_log",C.createLogger({id:`t${++Wm}`}));c(this,"_plugins",new Map);c(this,"_networkQuality",null);c(this,"_speakerId");c(this,"_getPCMAbortCtrl");this._room=new e(v({logger:this._log,frameWorkType:W.frameWorkType},t)),this._room.videoDecodeFallbackType=t.videoDecodeFallback,this._log.info(`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(Ya,t.assetsPath),this._use(Za,t.assetsPath),this._use(zo,t.assetsPath||ln),this._use(ic),t.enableSEI&&yo&&this._use(ec),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 x({code:B.OPERATION_FAILED,extraCode:5504,message:r.message,originError:r}))}),this._listenEvents(),this._initActiveSpeaker(),wm(this,"trtc")}static create(e){}static _create(e,t){Im();let r=new W(e,t||{});return Qo.add(r),r}get room(){return this._room}_listenEvents(){$e(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().finally(()=>{this.emit(M.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(M.ERROR,x.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(M.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let t=L(v({},e),{uplinkRTT:Math.min(e.uplinkRTT,zs),downlinkRTT:Math.min(e.downlinkRTT,zs)});this.emit(M.NETWORK_QUALITY,t)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(r=>{$e(r,r).add("player-state-changed",o=>{let n=L(v({},o),{userId:e.userId});r.kind===m.VIDEO&&(n.streamType=sr(r.streamType)),this.emit(r.kind===m.AUDIO?M.AUDIO_PLAY_STATE_CHANGED:M.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",o=>{o.getCode()===I.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=>{Re(r)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:t})=>{let{userId:r}=t,o=e.audioAvailable,n=e.videoAvailable,{audioAvailable:a,videoAvailable:d}=t;a||this._remoteAudioConfigMap.delete(r),d||this._removeRemoteVideoConfig(r,"main"),t.hasAuxiliary||this._removeRemoteVideoConfig(r,"sub"),n!==d&&(d?this._onVideoAvailable({userId:r,streamType:"main"}):this._onVideoUnavailable({userId:r,streamType:"main"}),this.emit(d?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,L(v({},e),{streamType:sr(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(M.ERROR,new x({code:B.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var o,n,a,d,l,u,h;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,zs),upLoss:((d=this._networkQuality)==null?void 0:d.uplinkLoss)||0,downLoss:((l=this._networkQuality)==null?void 0:l.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((u=e.msg_up_stream_info.msg_audio_status)==null?void 0:u.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((h=e.msg_up_stream_info.msg_audio_status)==null?void 0:h.uint32_audio_level)||0)/Et},video:e.msg_up_stream_info.msg_video_status.filter(f=>t[f.uint32_video_stream_type]).map(f=>({bitrate:(f.uint32_video_codec_bitrate||0)/1e3,width:f.uint32_video_width,height:f.uint32_video_height,frameRate:f.uint32_video_enc_fps,videoType:t[f.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(f=>({userId:f.msg_user_info.str_identifier,audio:{bitrate:(f.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(f.msg_audio_status.uint32_audio_level||0)/Et},video:f.msg_video_status.map(g=>({bitrate:(g.uint32_video_codec_bitrate||0)/1e3,width:g.uint32_video_width,height:g.uint32_video_height,frameRate:g.uint32_video_dec_fps,videoType:t[g.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,L(v({},e),{streamType:sr(e.streamType)}))}),$e(this,ke).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=>p(this,null,function*(){if(this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Ue&&Ue.deviceId===Xs){let t=(yield Zi()).find(r=>r.deviceId===Xs);t&&Ue.groupId!==t.groupId&&(Ue=t,this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:t}))}})).add("audioOutputRemoved",e=>p(this,null,function*(){this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let t=(yield Zi())[0];if(!t||!Ue||Ue.groupId===t.groupId)return;let r=Ue.deviceId===e.deviceId,o=Ue.deviceId===Xs&&Ue.deviceId===t.deviceId;(r||o)&&(Ue=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||ln)}_use(e,t){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let o=new e(Pm.call(this,{TRTC:W,room:this._room,errorModule:AT,assetsPath:t}));this._plugins.set(e.Name,o),e.autoStart&&this.startPlugin(e.Name)}enterRoom(e){return p(this,null,function*(){var d,l;let{scene:t="rtc",enableAutoPlayDialog:r=!0,autoReceiveAudio:o=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!Z(e.proxy)&&e.proxy.turnServer&&((l=(d=this._room).setTurnServer)==null||l.call(d,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=r,this._room.autoReceiveAudio=o,this._room.autoReceiveVideo=n,_e(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let a={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,keepAlive:e.keepAlive};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(a,t,W.frameWorkType),this._checkTrackToPublish(),Xl.start()})}exitRoom(){return p(this,null,function*(){return yield this._exitRoom()})}switchRole(e,t){return p(this,null,function*(){t!=null&&t.privateMapKey&&(this._room.privateMapKey=t.privateMapKey),t!=null&&t.latencyLevel&&(this._room.latencyLevel=t.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){Re(this),this.removeAllListeners(),this._room.destroy(),Qo.delete(this),Qo.size===0&&Xl.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(),S.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return p(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:t=!0,mute:r,option:o}=e,n=new St(this._room.audioManager),a={},d={muted:!0};o&&(T(o.microphoneId)?T(o.audioTrack)||(a.customSource=o.audioTrack):a.deviceId=o.microphoneId,o&&Y(o.captureVolume)&&n.setCaptureVolume(o.captureVolume),T(o.profile)||(Z(o.profile)?mn[o.profile]&&n.setProfile(mn[o.profile]):n.setProfile(o.profile)),Y(o.earMonitorVolume)&&(d.muted=!(o.earMonitorVolume>0),d.volume=o.earMonitorVolume),T(o.echoCancellation)||(n.profile.echoCancellation=o.echoCancellation),T(o.noiseSuppression)||(n.profile.noiseSuppression=o.noiseSuppression),T(o.autoGainControl)||(n.profile.autoGainControl=o.autoGainControl)),n.on("5",l=>{this.emit(M.ERROR,new x({code:B.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 u;l.error&&(u=x.convertFrom(l.error)),this.emit(M.PUBLISH_STATE_CHANGED,L(v({},l),{error:u}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(a),T(r)||n.setMute(r),$e(n,n).add("player-state-changed",l=>{this.emit(M.AUDIO_PLAY_STATE_CHANGED,L(v({},l),{userId:""}))}),this.listeners(M.AUDIO_FRAME).length>0&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(l=>{this.emit(W.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(W.EVENT.AUDIO_FRAME,{data:l})}))}),t&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=L(v({},e),{publish:t}),yield this._updateAudioPlayOption({playOption:d,track:n})})}updateLocalAudio(e){return p(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):T(o.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(o.audioTrack)),T(o.captureVolume)||this._localAudioTrack.setCaptureVolume(o.captureVolume),T(o.earMonitorVolume)||(n.muted=!(o.earMonitorVolume>0),n.volume=o.earMonitorVolume),yield this._localAudioTrack.update3A(o)),this._room.isJoined&&!T(t)&&(t&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!t&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),T(r)||this._localAudioTrack.setMute(r),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Wt(this._localAudioConfig,e)})}stopLocalAudio(){return p(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),Re(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,this._getPCMAbortCtrl&&(this._getPCMAbortCtrl.abort("stopLocalAudio"),delete this._getPCMAbortCtrl))})}startLocalVideo(){return p(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 We(this._room.videoManager),d={},l={};_e(n==null?void 0:n.avoidCropping)&&(a.avoidCropping=n.avoidCropping),n&&(n.cameraId?d.deviceId=n.cameraId:T(n.useFrontCamera)?T(n.videoTrack)||(d.customSource=n.videoTrack):d.facingMode=n.useFrontCamera?m.FACING_MODE_USER:m.FACING_MODE_ENVIRONMENT,n.qosPreference&&(d.contentHint=jo(n.qosPreference)),T(n.profile)||(Z(n.profile)?gt[n.profile]&&a.setProfile(gt[n.profile]):a.setProfile(n.profile)),T(n.fillMode)||(l.objectFit=n.fillMode),T(n.mirror)||(l.mirror=n.mirror),T(n.small)||(Ao()?Z(n.small)?a.small=gt[n.small]:n.small===!0?a.small=gt["120p"]:a.small=n.small:this._log.warn("small stream is not supported"))),a.once("first-video-frame",u=>{this.emit(M.FIRST_VIDEO_FRAME,L(v({},u),{streamType:sr(u.streamType)}))}),a.on("5",u=>{this.emit(M.ERROR,new x({code:B.DEVICE_ERROR,extraCode:5308,messageParams:{error:u}}))}),a.on("2",u=>{this.emit(M.DEVICE_CHANGED,{type:"camera",action:"active",device:u})}),a.on("4",u=>{let h;u.error&&(h=x.convertFrom(u.error)),this.emit(M.PUBLISH_STATE_CHANGED,L(v({},u),{error:h}))}),this._listenOutputTrackChanged(a),yield a.capture(d),T(o)||(yield a.setMute(o)),$e(a,a).add("player-state-changed",u=>{this.emit(M.VIDEO_PLAY_STATE_CHANGED,L(v({},u),{userId:"",streamType:"main"}))}),r&&this._room.isJoined&&this._room.publish(a).catch(()=>{}),this._localVideoTrack=a,this._localVideoConfig=L(v({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:l,track:a})})}updateLocalVideo(e){return p(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:t,publish:r,mute:o,option:n}=e,a={};if(n)if(T(n.profile)||(Z(n.profile)?gt[n.profile]&&this._localVideoTrack.setProfile(gt[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&T(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):T(n.useFrontCamera)?T(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?m.FACING_MODE_USER:m.FACING_MODE_ENVIRONMENT),T(n.fillMode)||(a.objectFit=n.fillMode),T(n.mirror)||(a.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(jo(n.qosPreference)),n.small){let d=!this._localVideoTrack.small;Ao()?(n.small===!0?this._localVideoTrack.small=gt["120p"]:Z(n.small)?this._localVideoTrack.small=gt[n.small]:this._localVideoTrack.small=n.small,this._room.videoManager.update(),d&&this._room.enableSmall(!0)):this._log.warn("small stream is not supported")}else n.small===!1&&this._localVideoTrack.small&&(delete this._localVideoTrack.small,this._room.videoManager.update(),this._room.enableSmall(!1));this._room.isJoined&&!T(r)&&(r&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!r&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),T(o)||(yield this._localVideoTrack.setMute(o)),yield this._updateVideoPlayOption({view:t,playOption:a,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Wt(this._localVideoConfig,e)})}stopLocalVideo(){return p(this,null,function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),Re(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return p(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 ct(this._room.videoManager);n.on("4",h=>{let f;h.error&&(f=x.convertFrom(h.error)),this.emit(M.PUBLISH_STATE_CHANGED,L(v({},h),{error:f}))}),n.once("first-video-frame",h=>{this.emit(M.FIRST_VIDEO_FRAME,L(v({},h),{streamType:sr(h.streamType)}))}),this._listenOutputTrackChanged(n),e.streamType==="main"&&(n.mediaType=4);let a=null,d={},l={};o&&(T(o.profile)||(Z(o.profile)?pn[o.profile]&&n.setProfile(pn[o.profile]):n.setProfile(o.profile)),o.systemAudio&&(d.systemAudio=!0,d.echoCancellation=o.echoCancellation,d.noiseSuppression=o.noiseSuppression,d.autoGainControl=o.autoGainControl),T(o.fillMode)||(l.objectFit=o.fillMode),o.videoTrack&&(d.videoTrack=o.videoTrack),o.audioTrack&&(d.audioTrack=o.audioTrack),o.captureElement&&(d.captureElement=o.captureElement),o.preferDisplaySurface&&(d.preferDisplaySurface=o.preferDisplaySurface),o.qosPreference&&(d.contentHint=jo(o.qosPreference)));let u=yield n.capture(d);if(n.mediaTrack.addEventListener(m.ENDED,()=>{this._stopScreenShare(),this.emit(M.SCREEN_SHARE_STOPPED)}),u.getAudioTracks()[0]&&(a=new ni(this._room.audioManager),yield a.setInputMediaStreamTrack(u.getAudioTracks()[0]),this._speakerId&&a.setAudioOutput(this._speakerId)),$e(n,n).add("player-state-changed",h=>{this.emit(M.VIDEO_PLAY_STATE_CHANGED,L(v({},h),{userId:"",streamType:"sub"}))}),r&&this._room.isJoined){let h=[n];a&&h.push(a),this._room.publish(...h).catch(()=>{})}this._localScreenTrack=n,this._localScreenAudioTrack=a,this._localScreenConfig=L(v({},e),{view:t,publish:r}),yield this._updateVideoPlayOption({view:t,playOption:l,track:n})})}updateScreenShare(e){return p(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:t,publish:r,option:o}=e,n={};if(o&&(T(o.fillMode)||(n.objectFit=o.fillMode),o.qosPreference)){let a=jo(o.qosPreference);this._localScreenTrack.setContentHint(a)}this._room.isJoined&&!T(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}),Wt(this._localScreenConfig,e)})}stopScreenShare(){return p(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return p(this,null,function*(){let{view:t,userId:r,streamType: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 d=this._room.remotePublishedUserMap.get(r);if(!d)return;let l={},u=o==="main"?d.remoteVideoTrack:d.remoteAuxiliaryTrack;this._listenOutputTrackChanged(u),n&&(T(n.fillMode)||(l.objectFit=n.fillMode),T(n.mirror)||(l.mirror=n.mirror),T(n.poster)||(l.poster=n.poster),l.canvasRender=n.canvasRender,o==="main"&&!T(n.small)&&(!d.remoteVideoTrack.isSubscribing&&!d.remoteVideoTrack.isSubscribed&&d.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,u.user))),yield this._room.subscribe(u),yield this._enableVideoDecodeFallback(u,o),yield this._updateVideoPlayOption({view:t,playOption:l,track:u}),this._emitTrackEvent(u),this._remoteVideoConfigMap.set(a,{config:e}),n&&!T(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:u,view:t,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return p(this,null,function*(){var R,k;let{view:t,userId:r,streamType:o,option:n}=e,a=`${r}_${o}`,d=this._remoteVideoConfigMap.get(a);if(!d||!this._room.remotePublishedUserMap.has(r))return;let l={};n&&(T(n.fillMode)||(l.objectFit=n.fillMode),T(n.mirror)||(l.mirror=n.mirror));let u=null,h=this._room.remotePublishedUserMap.get(r);if(o==="main"&&(h!=null&&h.muteState.hasVideo)&&(u=h.remoteVideoTrack),o==="sub"&&(h!=null&&h.muteState.hasAuxiliary)&&(u=h.remoteAuxiliaryTrack),!u)return;let{config:f}=d;o==="main"&&n&&!T(n.small)&&this._room.changeType(n.small,u.user),yield this._updateVideoPlayOption({view:t,playOption:l,track:u,prevConfig:f}),Wt(f,e);let g=T(n==null?void 0:n.receiveWhenViewVisible)?(R=f.option)==null?void 0:R.receiveWhenViewVisible:n.receiveWhenViewVisible,D=T(t)?f.view:t,_=T(n==null?void 0:n.viewRoot)?(k=f.option)==null?void 0:k.viewRoot:n.viewRoot;this._observeView({remoteTrack:u,view:D,receiveWhenViewVisible:g,viewRoot:_})})}stopRemoteVideo(e){return p(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,t=!0){return p(this,null,function*(){let r=[],o=this._room.remotePublishedUserMap.get(e.userId);if(o){let{muteState:n,remoteVideoTrack:a,remoteAuxiliaryTrack:d}=o;e.streamType==="main"&&(a.stop(),n.hasVideo&&r.push(a)),e.streamType==="sub"&&(d.stop(),n.hasAuxiliary&&r.push(d))}for(let n of r)t&&(yield this._room.unsubscribe(n),this._mediaTrackMap.delete(n.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)})}_removeRemoteVideoConfig(e,t){let r=`${e}_${t}`,o=this._remoteVideoConfigMap.get(r);o&&o.observer&&o.observer.disconnect(),this._remoteVideoConfigMap.delete(r)}muteRemoteAudio(e,t){return p(this,null,function*(){this._remoteAudioMuteMap.set(e,t);try{if(e==="*")if(t)yield this._stopRemoteAudio({userId:e});else{let r=[...this._room.remotePublishedUserMap.values()];for(let 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 p(this,null,function*(){return e.start(t)})}updatePlugin(e,t){return p(this,null,function*(){return e.update(t)})}stopPlugin(e,t){return p(this,null,function*(){return e.stop(t)})}enableAudioVolumeEvaluation(e=2e3,t=!1){this._room.enableAudioVolumeEvaluation(e,t)}on(e,t,r){return this.listeners(e).includes(t)?this:(this._log.debug("on",e),super.on(e,t,r),this._eventListened.add(e),e===W.EVENT.AUDIO_FRAME&&!this._getPCMAbortCtrl&&(this._getPCMAbortCtrl=this._room.audioManager.getPCM(o=>{this.emit(W.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(W.EVENT.AUDIO_FRAME,{data:o})}))})),this)}emit(e,...t){try{Dm.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===W.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(Z(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 p(this,null,function*(){(yield Zi()).forEach(r=>{r.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}),Ue=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 p(this,null,function*(){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 a=this._remoteAudioVolumeMap.get(t),d=Y(a)?a:100;o.volume=d,this._remoteAudioConfigMap.set(t,e),yield this._room.subscribe(n),de(ue(n,"decode-failed"),we(ue(n,F.INIT)),Ae(()=>{this.startPlugin(zo.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:o,track:n})}catch(a){throw this._remoteAudioConfigMap.delete(t),a}this._emitTrackEvent(n)})}_stopRemoteAudio(e,t=!0){return p(this,null,function*(){let r=this._room.remotePublishedUserMap.get(e.userId);r&&(r.remoteAudioTrack.stop(),r.muteState.hasAudio&&t&&(yield this._room.unsubscribe(r.remoteAudioTrack)),this._mediaTrackMap.delete(r.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`)})}_enableVideoDecodeFallback(e,t){let r=this._room.videoDecodeFallbackType;if(!r||!this._plugins.has("TRTCVideoDecoder"))return;e.log.debug("remote video will fall back when decode failed",e.id);let o;de(ue(e,"decode-failed"),we(ue(e,F.INIT)),Pl(()=>{this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:r})}),Mr(ue(e,"decode-downgrade-state-changed")),Ae(n=>{o=n.state,this.emit(M.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,L(v({},n),{streamType:t,userId:e.userId}))},n=>{e.log.error("fallback",n)},()=>{o==="STARTED"&&e.log.info("fallback complete")}))}_updateVideoPlayOption(n){return p(this,arguments,function*({view:e,playOption:t,track:r,prevConfig:o}){if(r.setMirror(t.mirror),T(e)&&o&&o.view&&!Xr(t)){let a=Qr(o.view);a.length>0&&(yield r.play(a,t))}if(!T(e)){let a=Qr(e);a.length>0?yield r.play(a,t):r.stop()}})}_updateAudioPlayOption(o){return p(this,arguments,function*({playOption:e={},track:t,prevConfig:r}){if(!t.isPlayCalled)try{yield t.play(null,e)}catch(n){}T(e.muted)||t.setPlayerMute(e.muted),T(e.volume)||t.setAudioVolume(e.volume/100)})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,t=!0){let 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:sr(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(T(t))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${sr(e.streamType)}`);if(!n)return;let a=n.observer||void 0;if(t===null||Ie(t)&&t.length===0||!r){a==null||a.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let l=n.visibleViewMap||new Map,u=-1;(!a||a.root!==o)&&(a==null||a.disconnect(),l.clear(),a=new IntersectionObserver(f=>{f.forEach(g=>{l.set(g.target,g.isIntersecting),e.log.info(`view ${g.target.id} is${g.isIntersecting?"":" not"} visible`)}),clearTimeout(u),u=window.setTimeout(()=>{[...l.values()].find(D=>D)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:o}));let h=new Set(Qr(t));l.forEach((f,g)=>{h.has(g)||(a.unobserve(g),l.delete(g))}),h.forEach(f=>{l.set(f,!0),a.observe(f)}),a.takeRecords().forEach(f=>{l.set(f.target,f.isIntersecting)}),n.visibleViewMap=l,n.observer=a}_exitRoom(){return p(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(),xm(this),this._room.remotePublishedUserMap.forEach(e=>{Re(e.remoteAudioTrack),Re(e.remoteVideoTrack),Re(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return p(this,null,function*(){var e;if(this._localScreenTrack){if(this._room.isJoined){let t=[this._localScreenTrack];this._localScreenAudioTrack&&t.push(this._localScreenAudioTrack),yield(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),Re(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!Ue||Ts(Ue))&&(this._initActiveSpeaker(),S.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return p(this,null,function*(){if(Ue&&!Ts(Ue))this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:Ue});else{let e=yield Zi();e[0]&&!Ts(e[0])?(Ue=e[0],this.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):S.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable({userId:e}){let t=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(t===!1||this._room.autoReceiveAudio&&!t)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:t}){if(!this._room.autoReceiveVideo)return;let r=this._room.remotePublishedUserMap.get(e);if(r){let 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:L(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),T(t)||(t?C.enableUploadLog():C.disableUploadLog())}static isSupported(){return ra()}static getCameraList(e=!0){return _t(e)}static getMicrophoneList(e=!0){return nt(e)}static getSpeakerList(e=!0){return Zi(e)}static setCurrentSpeaker(e){return p(this,null,function*(){if(he&&(e===At.SPEAKER||e===At.HEADSET)){let r=yield W.getMicrophoneList(),o="";if(r.forEach(n=>{n.label===e&&(o=n.deviceId)}),!o)return;Qo.forEach(n=>p(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:o}}))}));return}(yield Zi()).forEach(r=>{r.deviceId===e&&(Qo.forEach(o=>{o._setCurrentSpeaker(e),o.emit(M.DEVICE_CHANGED,{type:"speaker",action:"active",device:r})}),Ue=r)})})}static _addKVStat({type:e,key:t,value:r,base:o,useUV:n,version:a}){switch(a&&(Ir.version=a),e){case"count":Ir.addCount({key:t,useUV:n});break;case"enum":Ir.addEnum({key:t,value:r,useUV:n});break;case"number":Ir.addNumber({key:t,value:r,split:o});break}}};c(W,"_loggerManager",C),c(W,"EVENT",M),c(W,"ERROR_CODE",B),c(W,"TYPE",At),c(W,"frameWorkType",30),y([fe({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"}})})],W.prototype,"use",1),y([qe(xe.TRTC.enterRoom),ir("room",([e],[t])=>(e.roomId||e.strRoomId)===(t.roomId||t.strRoomId)&&e.userId===t.userId&&e.sdkAppId===t.sdkAppId),z(e=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),e.call(this,t)}),fe()],W.prototype,"enterRoom",1),y([fe()],W.prototype,"exitRoom",1),y([qe(xe.TRTC.switchRole),xr("room",{merge:(e,t)=>t}),fe()],W.prototype,"switchRole",1),y([fe()],W.prototype,"destroy",1),y([qe(xe.TRTC.startLocalAudio),ir("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)}),fe()],W.prototype,"startLocalAudio",1),y([qe(xe.TRTC.updateLocalAudio),xr("audio",{debounce:{delay:200,getKey:()=>`${Wm}-localAudio`,isNeedToDebounce:e=>{var t;return!T((t=e.option)==null?void 0:t.captureVolume)}}}),fe()],W.prototype,"updateLocalAudio",1),y([rr("audio"),fe()],W.prototype,"stopLocalAudio",1),y([qe(xe.TRTC.startLocalVideo),ir("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)}),fe()],W.prototype,"startLocalVideo",1),y([qe(xe.TRTC.updateLocalVideo),xr("video"),fe()],W.prototype,"updateLocalVideo",1),y([rr("video"),fe()],W.prototype,"stopLocalVideo",1),y([qe(xe.TRTC.startScreenShare),ir("screen",()=>!0),fe()],W.prototype,"startScreenShare",1),y([qe(xe.TRTC.updateScreenShare),xr("screen"),fe()],W.prototype,"updateScreenShare",1),y([fe()],W.prototype,"stopScreenShare",1),y([qe(xe.TRTC.startRemoteVideo),ir(e=>`v${e.userId}${e.streamType}`,()=>!0),fe({getRemoteId:e=>`${e.userId}_${e.streamType}`})],W.prototype,"startRemoteVideo",1),y([qe(xe.TRTC.updateRemoteVideo),xr(e=>`v${e.userId}${e.streamType}`),fe({getRemoteId:e=>`${e.userId}_${e.streamType}`})],W.prototype,"updateRemoteVideo",1),y([qe(xe.TRTC.stopRemoteVideo),z(e=>function(t){return p(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)})}),fe({getRemoteId:e=>`${e.userId}_${e.streamType}`})],W.prototype,"stopRemoteVideo",1),y([rr(e=>`v${e.userId}${e.streamType}`)],W.prototype,"_stopRemoteVideo",1),y([qe(...xe.TRTC.muteRemoteAudio),fe({getRemoteId:e=>e})],W.prototype,"muteRemoteAudio",1),y([Wl(...xe.TRTC.setRemoteAudioVolume),Um(200,e=>e),fe({getRemoteId:e=>e})],W.prototype,"setRemoteAudioVolume",1),y([za("start"),Ke(e=>{var t;return(t=e.afterStart)==null?void 0:t.call(e)}),ir((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),fe({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Id[e.getName()],ignoreLog:e=>e.getName()==="Debug"})],W.prototype,"startPlugin",1),y([za("update"),xr((e,t)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(t)),fe({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Ad[e.getName()]})],W.prototype,"updatePlugin",1),y([za("stop"),rr((e,t)=>{if(e.disableRandomCall)return null;let r=e.getGroup(t),o=e.getAlias();return r==="*"?new RegExp(`${o}.*`):o+r}),fe({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Cd[e.getName()]})],W.prototype,"stopPlugin",1),y([Wl(...xe.TRTC.enableAudioVolumeEvaluation)],W.prototype,"enableAudioVolumeEvaluation",1),y([fe()],W.prototype,"getVideoSnapshot",1),y([fe()],W.prototype,"_setCurrentSpeaker",1),y([ir(e=>`a${e.userId}`,()=>!0)],W.prototype,"_startRemoteAudio",1),y([z(e=>function(t){return p(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(r=>this._stopRemoteAudio(L(v({},t),{userId:r.userId})).catch(()=>{}))):e.call(this,t)})}),rr(e=>`a${e.userId}`)],W.prototype,"_stopRemoteAudio",1),y([rr("room")],W.prototype,"_exitRoom",1),y([rr("screen")],W.prototype,"_stopScreenShare",1),y([qe(...xe.TRTC.sendSEIMessage),Ul({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],W.prototype,"sendSEIMessage",1),y([qe(xe.TRTC.sendCustomMessage),Ul({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],W.prototype,"sendCustomMessage",1),y([qe(xe.TRTC.create)],W,"_create",1);var su=W,Yo=su;var ou=class{constructor(){c(this,"_set",new Set);S.on(E.LEAVE_SUCCESS,this.delete,this)}add({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,e||i.roomId,i.sdkAppId,i.useStringRoomId);this._set.add(t)}delete({room:i,roomId:e}){if(i.scene==="rtc")return;let t=this.getKey(i.userId,i.roomId||e,i.sdkAppId,i.useStringRoomId);this._set.delete(t)}getKey(i,e,t,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 CT(){return p(this,null,function*(){let s,i;try{let h=yield nt();s=h&&h.length}catch(h){}try{let h=yield _t();i=h&&h.length}catch(h){}let e={microphone:s,camera:i},{isH264EncodeSupported:t,isVp8EncodeSupported:r,isH264DecodeSupported:o,isVp8DecodeSupported:n}=this.checkSystemResult.detail,a=Zt.basis(),d={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:d,devices:e},u={isWebCodecSupported:a.isWebCodecSupported,isMediaSessionSupported:a.isMediaSessionSupported,isWebTransportSupported:a.isWebTransportSupported};te.uploadEvent({log:`trtcstats-${JSON.stringify(l)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(l)}`),te.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(u)}`,userId:this.userId})})}function jm(){return z(s=>{let i=new ou;return function(e,t,r){return p(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:I.INVALID_OPERATION,message:V({key:U.INVALID_JOIN})});if(this.checkDestroy(),i.isJoined({userId:this.userId,roomId:o,sdkAppId:this.sdkAppId,room:this}))throw new b({code:I.INVALID_OPERATION,message:V({key:U.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}`),S.emit(E.JOIN_START,{room:this,roomId:o,params:e});let n=dt.getEnv();n||(n=pi.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(fn.OLD_CLOUD_LADDER)?n=pi.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(fn.WEBRTC)&&(n=pi.WEBRTC))),te.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:o}),Zt.checkSystemRequirementsInternal().then(a=>{this.checkSystemResult=a,CT.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!dt.getEnv()&&(yield this.schedule(e,r));let a=yield s.call(this,e,t,r);return this.roomId=o,this._joinedTimestamp=dt.performanceNow(),S.emit(E.JOIN_SUCCESS,{room:this}),r===30&&!e.component&&te.uploadEvent({log:`stat-conv-${Number(Mt)}-${location.hostname}`,userId:this.userId}),a}catch(a){throw i.delete({room:this,roomId:o}),S.emit(E.JOIN_FAILED,{room:this,error:a}),a}})}})}var qm=()=>z(s=>function(...i){return p(this,null,function*(){S.emit(E.LEAVE_START,{room:this}),yield s.call(this,...i),S.emit(E.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function Xm(){return z(s=>function(...i){let e=s.apply(this,i);return i.forEach(t=>!t.isSubscribed&&t.subscribe(e)),e})}var Qm=Be(ze());var Ce={SETUP_SUCCESS:"1",CONNECTION_STATE_CHANGED:"2",CONNECTED:"3",RECONNECT_FAILED:"4",SETUP_FAILED:"5",DISCONNECTED:"6"};var Vt={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},zm=[Vt.UPDATE_REMOTE_MUTE_STAT,Vt.UPLINK_NETWORK_STATS,Vt.USER_LIST_RES,Vt.MUTE_RESULT,Vt.SERVER_FIRST_PACKAGE_RECEIVED,Vt.RECEIVE_CUSTOM_MSG],H={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 sc=new Set;function Ym(s){let i=[...sc.values()].find(e=>e.room.userId===s&&!e.room.isJoined);return i||null}var ks=class extends Qm.default{constructor(e){var r,o,n;super();c(this,"room");c(this,"sdkAppId");c(this,"userId");c(this,"userSig");c(this,"url");c(this,"backupUrl");c(this,"destroyed",!1);c(this,"_socketInUse");c(this,"_socket");c(this,"_backupSocket");c(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[]});c(this,"_currentState","DISCONNECTED");c(this,"_isReconnecting",!1);c(this,"_seq",0);c(this,"_log");c(this,"_lastMessageTime",-1);c(this,"_connectStartTime",-1);c(this,"_stopConnectRetry");c(this,"bytesSent",0);c(this,"bytesReceived",0);c(this,"keepAlive",!1);c(this,"signalDomainWhenUnifiedProxy");c(this,"stopKeepAliveTimeout");c(this,"rtt",0);this.room=e.room,this.sdkAppId=e.sdkAppId,this.userId=e.userId,this.userSig=e.userSig,this.signalDomainWhenUnifiedProxy=e.signalDomainWhenUnifiedProxy;let t=((o=(r=this.room.scheduleResult)==null?void 0:r.config)==null?void 0:o.keepAliveClient)||0;(n=this.room.joinParams)!=null&&n.keepAlive&&!t&&(t=1),t-sc.size>0&&this.room.enableSPC&&(this.keepAlive=!0,sc.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 race(){return this.room.enableSPC&&!this.room.proxy_ws}get urlParam(){let e=`?sdkAppId=${encodeURIComponent(this.sdkAppId)}&userId=${encodeURIComponent(this.userId)}&userSig=${encodeURIComponent(this.userSig)}&keepAlive=${encodeURIComponent(Number(this.keepAlive))}`;this.signalDomainWhenUnifiedProxy&&(e+=`&signalDomain=${encodeURIComponent(this.signalDomainWhenUnifiedProxy)}`);let t=new URLSearchParams(location.search).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 isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12*1e3}connect(){return p(this,arguments,function*(e=10*1e3){if(this.isConnected)return Promise.resolve();this._log.info(`connect to [${this.url}, ${this.backupUrl}] ${this.race?"race":""}${e?` timeout: ${e}`:""} keepAlive: ${Number(this.keepAlive)}`),this.emitConnectionStateChanged("CONNECTING"),this._connectStartTime=P();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 pr(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,d)=>{o.onclose=d,o.onerror=d,o.onopen=()=>a(o),t&&(n=setTimeout(()=>{this.unbindAndCloseSocket(r?m.MAIN:m.BACKUP),d(new b({code:I.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(Ce.SETUP_FAILED,new b({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}onerror(e){this._log.error(`${e.target===this._socket?"main":"backup"} error observed`),this.emitConnectionStateChanged("DISCONNECTED"),e.target===this._socketInUse&&(this.unbindAndCloseSocket(m.MAIN),this.unbindAndCloseSocket(m.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(Ce.SETUP_FAILED,new b({code:I.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(e){if(!this.isConnected)return;this._lastMessageTime=Date.now(),this.bytesReceived+=Zs(e.data);let t=JSON.parse(e.data),{cmd:r,data:o}=t,n=Object.values(Vt),d=Object.keys(Vt)[n.indexOf(r)],l=H[d]||r;switch(zm.includes(r)||(this._log.debug(`received ${r} msg: ${e.data}`),l&&this._log.info(`Received event: [ ${l} ]`)),r){case Vt.CHANNEL_SETUP_RESULT:{if(t.code===0)this._signalInfo.clientIp=o.clientIp,this._signalInfo.signalIp=o.signalInnerIp,o.svrTime&&Lu(o.svrTime),this._log.info(`ChannelSetup Success ${P()-this._connectStartTime}`),N.addSuccessEvent({key:521701,cost:P()-this._connectStartTime}),this._connectStartTime=-1,this.emit(Ce.SETUP_SUCCESS,{signalInfo:this._signalInfo});else{let u=new b({code:I.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:t.code,message:V({key:U.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:u}),this.emit(Ce.SETUP_FAILED,u)}break}case Vt.JOIN_ROOM_RESULT:{t.code===0&&(this._signalInfo.relayIp=o.relayOuterIp,this._signalInfo.relayInnerIp=o.relayInnerIp,this._signalInfo.bakRelayIps=o.bakRelayIps,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 p(this,null,function*(){try{if(!this.room.joinParams)return;Ut(!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 p(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive){this.close();return}this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:e,useStringRoomId:t}=this.room,{relayIp:r,relayInnerIp: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:H.CHANNEL_RECONNECT_RESULT});a.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),N.addSuccessEvent({key:521702,cost:P()-this._connectStartTime}),this._connectStartTime=-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+=Zs(o),r.seq}}sendWaitForResponse({command:e,data:t,timeout:r=5e3,responseCommand:o,commandDesc:n,enableLog:a=!0,addReceiveTime:d=!1}){return new Promise((l,u)=>{let h=setTimeout(()=>{this.off(o,g);let _=new b({code:I.API_CALL_TIMEOUT,message:V({key:U.API_CALL_TIMEOUT,data:{commandDesc:n,command:e}})});a&&this._log.warn(_),u(_)},r),f=Date.now(),g=_=>{_.data.seq===D&&(clearTimeout(h),this.off(o,g),d&&(_.data.receiveTime=Date.now()),l(_))};this.on(o,g);let D=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(Ce.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),sc.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,bakRelayIps:[],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}getBackupRelayIpPair(){var t;let e=(t=this._signalInfo.bakRelayIps)==null?void 0:t.shift();return e&&(e.relayPort=e.relayPort||this._signalInfo.relayPort),e}clearBakRelayIps(){this._signalInfo.bakRelayIps=[]}stopKeepAliveIn(e=3600){if(this.keepAlive){this._log.info(`stopKeepAlive in ${e}s`),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info(`close due to not used ${e}s`),this.close(),this.off(H.JOIN_ROOM_RESULT,t)},e*1e3);let t=r=>{r.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(H.JOIN_ROOM_RESULT,t))};this.on(H.JOIN_ROOM_RESULT,t)}}emitConnectionStateChanged(e){e!==this._currentState&&(this._log.info(`${this._currentState} -> ${e}`),this.emit(Ce.CONNECTION_STATE_CHANGED,{prevState:this._currentState,state:e}),this._currentState=e,e==="CONNECTED"?this.emit(Ce.CONNECTED):e==="DISCONNECTED"&&this.emit(Ce.DISCONNECTED))}};y([ot({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())}})],ks.prototype,"connect",1);var Km=Be(ze());var nu=0,au=!1,oc=new Set,yT=s=>nu>2&&!au&&oc.size===0&&s,cu=!1,tt=class{constructor(i){c(this,"userId");c(this,"tinyId");c(this,"_sdpSemantics");c(this,"_isUplink");c(this,"_room");c(this,"_log");c(this,"_signalChannel");c(this,"_isErrorObserved",!1);c(this,"_waitForPeerConnectionConnectedPromise");c(this,"_waitForPeerConnectionConnectedPromiseReject",null);c(this,"_peerConnection",null);c(this,"_emitter",new Km.default);c(this,"_currentState","DISCONNECTED");c(this,"_isReconnecting",!1);c(this,"_reconnectionCount",0);c(this,"_reconnectionTimer",-1);c(this,"_isFirstConnection",!0);c(this,"_prevTime",-1);c(this,"_localAddress");c(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=P())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,N.addSuccessEvent({key:521705,cost:Math.min(P()-this._prevTime,30*1e3)})):this._isReconnecting&&N.addSuccessEvent({key:521706,cost:P()-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(),oc.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:I.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return yt;let i=null;if(this._isUplink){if(!Ki()||this._peerConnection.getSenders().length===0)return yt;i=this._peerConnection.getSenders()[0].transport}else{if(!Ar()||this._peerConnection.getReceivers().length===0)return yt;i=this._peerConnection.getReceivers()[0].transport}return i?i.state:yt}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===me.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),i.target.connectionState===me.FAILED||i.target.connectionState===me.CLOSED){let r=`connection ${i.target.connectionState}. ICE Transport state: ${e}, DTLS Transport state: ${t}`,o=new b({message:r,code:I.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",o)}(i.target.connectionState===me.CONNECTED||i.target.connectionState===me.COMPLETED)&&(this.logSelectedCandidate(),te.logSuccessEvent({userId:this._room.userId,eventType:it.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(i){return i===this._currentState?!1:(i==="CONNECTED"?(nu=0,au=!1,cu=!0,oc.add(this)):oc.delete(this),S.emit(E.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:i,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:i}),this._currentState=i,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return p(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:I.API_CALL_ABORTED,message:V({key:U.CONNECTION_ABORTED,data:"leave room"})})))},o=()=>{S.off(E.LEAVE_SUCCESS,r,this),this._emitter.off("connection-state-changed",t,this)},n=setTimeout(()=>{o();let a=new b({code:I.API_CALL_TIMEOUT,message:"connection timeout"});nu+=1,yT(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),au=!0,this._emitter.emit("firewall-restriction")),e(a)},qs);S.on(E.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(Ce.CONNECTED,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=fi()){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?I.UPLINK_RECONNECTION_FAILED:I.DOWNLINK_RECONNECTION_FAILED,message:V({key:this._isUplink?U.UPLINK_RECONNECTION_FAILED:U.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(Ce.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([at(521712,!1)],tt.prototype,"setOffer",1),y([at(521713,!1)],tt.prototype,"setAnswer",1);var hu=Be(uu());var Se=function(s){return hu.default.parse(s)},Ct=function(s){return hu.default.write(s)},np=function(s){let i=Se(s);return i.media.forEach(e=>{e.type===m.AUDIO&&e.fmtp.forEach(t=>{t.config+=";sprop-stereo=1;stereo=1"})}),Ct(i)};function ap(s){let i=Se(s);return i.media.forEach(e=>{var t,r;if(e.type===m.VIDEO){let o=new Set;e.rtp.forEach(({payload:a,codec:d})=>d==="H264"&&o.add(a)),e.fmtp.forEach(({payload:a,config:d})=>{let l=d.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(" ")}}),Ct(i)}function nc(s){return Object.keys(s).filter(i=>s[i])}var Ls=class Ls extends tt{constructor(e){super(L(v({},e),{isUplink:!1}));c(this,"_flag",0);c(this,"isRobot",!1);c(this,"role","anchor");c(this,"remoteAudioTrack");c(this,"remoteVideoTrack");c(this,"remoteAuxiliaryTrack");c(this,"ssrc",{audio:0,video:0,auxiliary:0});c(this,"_isSDPExchanging",!1);this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new Pi(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new di(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new ys(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 Ti(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
|
|
62
|
-
`),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,d]=o[n];t.splice(a+n,0,d)}return t.join(`\r
|
|
63
|
-
`)}addSPSDescription(e){let t=Se(e);return t.media.forEach(r=>{r.type===m.VIDEO&&r.fmtp.forEach(o=>{o.config+=";sps-pps-idr-in-keyframe=1"})}),Ct(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=Se(e);return r.media.forEach(o=>{o.ext&&(o.ext=o.ext.filter(n=>!t.includes(n.uri)))}),Ct(r)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,t){return p(this,null,function*(){var r,o;try{if((((r=this._peerConnection)==null?void 0:r.connectionState)===me.NEW||((o=this._peerConnection)==null?void 0:o.connectionState)===me.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:I.REMOTE_STREAM_NOT_EXIST,message:`remote user ${this.userId} unpublished stream`})):n}})}unsubscribe(r){return p(this,arguments,function*({remoteTracks:e,streamType:t}){if(this._currentState==="CONNECTED"&&(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed)){this._log.info(`${t} stream already unsubscribed`);return}let 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} [${nc(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=H.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=H.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:o,data:r,responseCommand:n,timeout:1e4}).then(({data:a})=>{if(a.code!==0){let d=new b({code:a.code,message:V({key:U.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(d),d}})}connect(){return p(this,arguments,function*(e=this.subscribeState){try{yield this.exchangeSDP(e),yield this.waitForPeerConnectionConnected()}catch(t){throw this.closePeerConnection(!0),t}})}exchangeSDP(e){return p(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:t,sdp:r}=this._peerConnection.localDescription,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:H.SUBSCRIBE_RESULT,timeout:Lc});if(!this._peerConnection){let a=new b({code:I.INVALID_OPERATION,message:V({key:U.CONNECTION_CLOSED})});throw this._log.warn(a),a}yield this.onSubscribeResult(n),this._isSDPExchanging=!1}catch(t){throw this._isSDPExchanging=!1,t}})}createOffer(){return p(this,null,function*(){let e={voiceActivityDetection:!1};mt()&&this._sdpSemantics===Ji?(this._peerConnection.addTransceiver(m.AUDIO,{direction:K.RECVONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:K.RECVONLY}),this._peerConnection.addTransceiver(m.VIDEO,{direction:K.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let t=yield this._peerConnection.createOffer(e);if(t.sdp){let{isH264DecodeSupported:r}=yield ia();r||(this._log.warn("remove h264 desc from sdp"),t.sdp=ap(t.sdp)),t.sdp=this.addRRTRLine(t.sdp),t.sdp=this.addSPSDescription(t.sdp),t.sdp=np(t.sdp),this._sdpSemantics===Ji&&(t.sdp=this.removeSDESDescription(t.sdp))}yield this.setOffer(t)})}onSubscribeResult(e){return p(this,null,function*(){let{code:t,message:r=""}=e&&e.data||{},{type:o,sdp:n}=e&&e.data&&e.data.data||{};if(t===dr)throw new b({code:I.NOT_SUPPORTED_H264,message:V({key:U.NOT_SUPPORTED_H264DECODE})});try{if(t!==0)throw new b({code:t,message:V({key:U.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{Se(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 d;return(d=a.value)==null?void 0:d.includes(js)}),n=r.ssrcs.find(a=>{var d;return(d=a.value)==null?void 0:d.includes(vc)});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 p(this,null,function*(){if(!(Fe(Ls.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=Nt(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([z(e=>function(...t){return new Promise((r,o)=>{let n=a=>{this._emitter.off("closed",n),o(new b({code:I.API_CALL_ABORTED,message:V({key:U.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,o).finally(()=>{this._emitter.off("closed",n)})})})],Ls.prototype,"subscribe",1),y([at(521717,!1)],Ls.prototype,"unsubscribe",1),y([Ke(tt.prototype.afterConnect),Ta(tt.prototype.beforeConnect)],Ls.prototype,"connect",1);var mu=Ls,pu=mu;var dp={voiceActivityDetection:!1},Ps=class Ps extends tt{constructor(e){super(L(v({},e),{isUplink:!0}));c(this,"localMainAudioTrack",null);c(this,"localMainVideoTrack",null);c(this,"localAuxAudioTrack",null);c(this,"localAuxVideoTrack",null);c(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0});c(this,"_isPublishingAux",!1);c(this,"_publishingLocalAudioTrack");c(this,"_publishingLocalVideoTrack");c(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});c(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&&(Yt()?(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(d=>{d.track&&(d.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,d;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}),(d=this._publishingLocalVideoTrack)==null||d.emit("connection-state-changed",{prevState:r,state:e}))),o}publish(o){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){this._peerConnection||this.initialize(),e&&(this._publishingLocalAudioTrack=e),t&&(this._publishingLocalVideoTrack=t),this._isPublishingAux=r;let n;t&&!r&&t.small&&(n=this._room.videoManager.smallTrack),this.sendMediaSettings(),mt()?yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:n,isAuxiliary:r}):yield this.publishByAddTrack({localAudioTrack:e,localVideoTrack:t,smallTrack:n}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,r?(t&&(this.localAuxVideoTrack=t),e&&(this.localAuxAudioTrack=e)):(t&&(this.localMainVideoTrack=t),e&&(this.localMainAudioTrack=e)),this.installTrackMuteEvents(e,t),this.sendMutedFlag()})}publishByTransceiver(n){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r,isAuxiliary:o}){this._log.info("publish by transceiver");let a=new MediaStream,d=t==null?void 0:t.outMediaTrack,l=e==null?void 0:e.outMediaTrack;l&&a.addTrack(l),d&&a.addTrack(d);let u=this._peerConnection.getTransceivers();if(u.length===0)this._peerConnection.addTransceiver(l||m.AUDIO,{direction:K.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?m.VIDEO:d||m.VIDEO,{direction:K.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(r||m.VIDEO,{direction:K.SENDONLY,streams:[a]}),this._peerConnection.addTransceiver(o?d||m.VIDEO:m.VIDEO,{direction:K.SENDONLY,streams:[a]}),yield this.connect();else{let h=[];if(l&&(u[0].sender.track||h.push(0),yield u[0].sender.replaceTrack(l),yield this.setBandwidth({bandwidth:(e==null?void 0:e.profile.bitrate)||40,type:m.AUDIO})),d){let f=o?3:1;yield u[f].sender.replaceTrack(d),yield this.setBandwidth({bandwidth:t.profile.bitrate,type:m.VIDEO,videoType:o?m.AUXILIARY:m.BIG}),h.push(f),r&&(yield u[2].sender.replaceTrack(r),yield this.setBandwidth({bandwidth:t.small.bitrate,type:m.VIDEO,videoType:m.SMALL}),h.push(2))}yield this.setTransceiverDirection(K.SENDONLY,h),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 p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,smallTrack:r}){this._log.info("publish by addtrack");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack;if(this._peerConnection&&this._peerConnection.connectionState!=="new"){e&&a&&(yield this.addTrack(e)),n&&(yield this.addTrack(t));return}let d=new MediaStream;if(a&&d.addTrack(a),n&&d.addTrack(n),a&&this._peerConnection.addTrack(a,d),n&&(this._peerConnection.addTrack(n,d),r)){let l=new MediaStream;l.addTrack(r),this._peerConnection.addTrack(r,l)}yield this.connect()})}enableSmall(e){return p(this,null,function*(){let t=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield t[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(K.SENDONLY,[2])):(yield t[2].sender.replaceTrack(null),yield this.setTransceiverDirection(K.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){if(!Yt()){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(),d=[];e&&(o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localAuxAudioTrack&&!this.localMainAudioTrack&&(yield a[0].replaceTrack(null),d.push(0))),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=L(v({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),d.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=L(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}),d.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.setTransceiverDirection(K.INACTIVE,d),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return p(this,null,function*(){let t={state:this.publishState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponse({command:Q.PUBLISH_STATE_CHANGE,data:t,responseCommand:H.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:H.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===I.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:t}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":t&&(this._mediaSettings.videoCodec="VP8");let r=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:o,localAuxVideoTrack:n}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?n=this._publishingLocalVideoTrack:o=this._publishingLocalVideoTrack),Kt){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:H.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return p(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?m.AUXILIARY:m.MAIN} stream`),mt()?yield this.addTrackByTransceiver(e,t):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,t){return p(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===K.INACTIVE&&(yield this.setTransceiverDirection(K.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return p(this,null,function*(){if(!e.outMediaTrack)return;let t=e.outMediaTrack;Yt()&&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 We&&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===Wr||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,t=Se(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;Yt()&&(t=this._peerConnection.getTransceivers().find(r=>r.sender&&r.sender.track===e.track)),this._peerConnection.removeTrack(e),t&&ce(t.stop)&&(this._log.info("stop transceiver"),t.stop())}removeTrack(e){return p(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?m.AUXILIARY:m.MAIN} stream`),mt()?yield this.removeTrackByTransceiver(e,t):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,t){return p(this,null,function*(){if(!e.outMediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===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(K.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,t){return p(this,null,function*(){if(!se)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,d=this._peerConnection.remoteDescription.sdp.split(`\r
|
|
64
|
-
`).map(l=>{if(l.match(new RegExp(`a=(${K.INACTIVE}|${K.RECVONLY}|${K.SENDONLY})`))&&a++,t.includes(a)){if(e===K.INACTIVE&&l.includes(`a=${K.RECVONLY}`))return o=!0,`a=${e}`;if(e===K.SENDONLY&&l.includes(`a=${K.INACTIVE}`))return o=!0,`a=${K.RECVONLY}`}return l}).join(`\r
|
|
65
|
-
`);o&&(this._log.info("updating answer"),yield this.setAnswer({type:"answer",sdp:d}))})}removeTrackBySender(e){return p(this,null,function*(){if(!e.outMediaTrack)return;if(e.kind===m.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack){this.reset(),this.initialize(),yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1});return}let t=this._peerConnection.getSenders().find(r=>r.track===e.outMediaTrack);t&&(this.removeSender(t),e.kind===m.VIDEO&&e.small&&this._peerConnection.getSenders().forEach(r=>{r.track&&r.track.kind===m.VIDEO&&this.removeSender(r)})),yield this.updateOffer("remove",e.outMediaTrack)})}replaceTrack(e){return p(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders();if(!t||t.length===0||!e.mediaTrack)return!1;let r;if(mt()?r=e.kind===m.AUDIO?t[0]:t[1]:r=t.find(a=>a.track&&a.track.kind===e.kind),!r)return!1;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info(`is replacing ${e.kind} track on ${o?m.AUXILIARY:m.MAIN} stream`),e.kind===m.AUDIO?yield r.replaceTrack(e.outMediaTrack):e.kind===m.VIDEO&&(o?t[3]&&(yield t[3].replaceTrack(e.outMediaTrack)):yield r.replaceTrack(e.outMediaTrack)),!0})}updateOffer(e,t){return p(this,null,function*(){try{let r=yield this._peerConnection.createOffer(dp);se&&r.sdp&&(r.sdp=this.setSDPDirection(r.sdp,"sendrecv")),yield this.setOffer(r);let o=this.updateMediaSettings(),n={action:e,trackId:t.id,kind:t.kind===m.VIDEO?"bigVideo":t.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:o,state:this.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug(`updatedOffer: ${n.sdp}`);let a=yield this._signalChannel.sendWaitForResponse({command:Q.PUBLISH_CHANGE,data:n,responseCommand:H.UPDATE_OFFER_RESULT,timeout:Mc,commandDesc:"update offer"}),{code:d,message:l}=a.data;d!==0&&this.checkPublishResultCode(d,l),yield this.acceptAnswer(a.data.data),r.sdp&&this.updateSSRC(r.sdp)}catch(r){throw this._log.error(r),r}})}setBandwidth(n){return p(this,arguments,function*({bandwidth:e,type:t,videoType:r,sdp:o}){if(!Ro())return o?t===m.VIDEO?this.updateVideoBandwidthRestriction(o,e,r):this.updateAudioBandwidthRestriction(o,e):void 0;let a,d=this._peerConnection.getSenders();if(mt()){let l=0;t===m.VIDEO&&(r===m.SMALL?l=2:r===m.AUXILIARY?l=3:l=1),a=d[l]}else a=d.find(l=>l.track&&l.track.kind===t);if(a){let l=a.getParameters();(!l.encodings||l.encodings.length===0)&&(l.encodings=[{}]),l.encodings[0].maxBitrate=e*1e3;try{return yield a.setParameters(l),this._log.info(`${r||""}${t} bandwidth ${e} kbps`),o}catch(u){if(this._log.info(`failed to set bandwidth by setting maxBitrate: ${u}`),o)return t===m.VIDEO?this.updateVideoBandwidthRestriction(o,e,r):this.updateAudioBandwidthRestriction(o,e)}}return o})}updateVideoBandwidthRestriction(e,t,r){let o="AS";se&&(o="TIAS",t=t*1e3);let n=0,a=-1;return r===m.SMALL?n=1:r===m.AUXILIARY&&(n=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,d=>(a+=1,a===n?`${d}b=${o}:${t}\r
|
|
66
|
-
`:d)),e}updateAudioBandwidthRestriction(e,t){let r="AS";return se&&(r="TIAS",t=t*1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,`m=audio $1\r
|
|
67
|
-
c=IN $2\r
|
|
68
|
-
b=${r}:${t}\r
|
|
69
|
-
`),e}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return p(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(e){throw this.closePeerConnection(!0),this.uninstallEvents(),e}})}exchangeSDP(){return p(this,null,function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(e){throw e}})}createOffer(){return p(this,null,function*(){try{let e=yield this._peerConnection.createOffer(dp);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:Q.PUBLISH,responseCommand:H.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof ct||this.localAuxVideoTrack instanceof ct,state:this.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug(`sending sdp offer: ${e.data.sdp}`),this._signalChannel.sendWaitForResponse(e).then(t=>{let{code:r,message:o,data:n}=t.data;return r===0?this.acceptAnswer(n):this.checkPublishResultCode(r,o)})}setSDPDirection(e,t,r="all"){let o=Se(e);return o.media.forEach(n=>{(r==="all"||n.type===r)&&(n.direction=t)}),Ct(o)}acceptAnswer(e){return p(this,null,function*(){var t,r,o,n,a;try{let d;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let h=((t=this._publishingLocalVideoTrack)==null?void 0:t.profile.bitrate)||((r=this.localMainVideoTrack)==null?void 0:r.profile.bitrate),f=((o=this._publishingLocalAudioTrack)==null?void 0:o.profile.bitrate)||((n=this.localMainAudioTrack)==null?void 0:n.profile.bitrate);if(h){let g=this._isPublishingAux?m.AUXILIARY:m.BIG;d=yield this.setBandwidth({bandwidth:h,type:m.VIDEO,sdp:d,videoType:g})}f&&(d=yield this.setBandwidth({bandwidth:f,type:m.AUDIO,sdp:d}))}if(d=this.removeVideoOrientation(e.sdp),(a=this._publishingLocalVideoTrack)!=null&&a.small){let{smallStreamConfig:h}=this._room;d=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||h.bitrate,type:m.VIDEO,videoType:m.SMALL,sdp:d})}let u={type:e.type,sdp:d};yield this.setAnswer(u),this._log.debug(`accepted answer: ${d}`)}catch(d){throw this._log.error(`failed to accept remote answer ${d}`),d}})}sendMutedFlag(e){var o,n,a;if(e===this.localAuxAudioTrack||e===this.localAuxVideoTrack)return;let r={audio:!!((o=this.localMainAudioTrack)!=null&&o.muted),bigVideo:!!((n=this.localMainVideoTrack)!=null&&n.muted),auxVideo:!!((a=this.localAuxVideoTrack)!=null&&a.muted)};this._log.info(`send muted state: ${JSON.stringify(r)}`),this._signalChannel.send(Q.UPDATE_MUTE_STAT,r)}getIsReconnecting(){return this._isReconnecting}reconnect(){return p(this,null,function*(){if(!(Fe(Ps.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:Q.UNPUBLISH,responseCommand:H.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch(t){let r=Nt(this._reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${r/1e3}s`),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},r)}})}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&S.emit(E.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{Se(e).media.forEach((r,o)=>{if(r.type===m.AUDIO){let n=r.ssrcs&&r.ssrcs[0];n&&(this.ssrc.audio=Number(n.id))}else{if(this._sdpSemantics===Wr&&r.ssrcGroups){r.ssrcGroups.forEach((a,d)=>{let l=Number(a.ssrcs.split(" ")[0]);d===0?this.ssrc.video=l:d===1&&(this.ssrc.small=l)});return}let n=r.ssrcs&&r.ssrcs[0];if(!n)return;switch(o){case 1:this.ssrc.video=Number(n.id);break;case 2:this.ssrc.small=Number(n.id);break;case 3:this.ssrc.auxiliary=Number(n.id);break;default:break}}})}catch(t){}}getVideoTrackId(e=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(Pe.NOT_SUPPORTED_H264ENCODE),new b({code:I.NOT_SUPPORTED_H264,message:V({key:U.NOT_SUPPORTED_H264ENCODE})})):new b({code:I.UNKNOWN,message:V({key:U.SIGNAL_RESPONSE_FAILED,data:{signalResponse:H.PUBLISH_RESULT,code:e,message:t}})})}};y([z(e=>function(...t){return new Promise((r,o)=>{let n=a=>{this._emitter.off("closed",n),o(new b({code:I.API_CALL_ABORTED,message:V({key:U.CONNECTION_ABORTED,data:a})}))};this._emitter.on("closed",n),e.apply(this,t).then(r,o).finally(()=>{this._emitter.off("closed",n)})})})],Ps.prototype,"publish",1),y([at(521715,!1)],Ps.prototype,"unpublish",1),y([Ke(tt.prototype.afterConnect),Ta(tt.prototype.beforeConnect)],Ps.prototype,"connect",1);var fu=Ps,Zo=fu;var en=class{constructor(i,e){this.room=i;c(this,"_log");c(this,"_prevReportTime",0);c(this,"_prevReport",{});c(this,"_prevStats",null);c(this,"_prevEncoderImplementation","");c(this,"_prevAuxEncoderImpl","");c(this,"_prevQualityLimitationReason","");c(this,"_prevAuxQualityLimitationReason","");c(this,"_prevDecoderImplementationMap",new Map);c(this,"totalBytesSent",0);c(this,"totalBytesReceived",0);c(this,"_spcStats",null);this._log=e}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(i){return p(this,null,function*(){var o;let e={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},t=i.getPeerConnection(),r=i.getSSRC();if(t)try{if((this._spcStats||(yield t.getStats())).forEach(a=>{var u,h,f;let d,l;if(a.type==="outbound-rtp")if((a.mediaType||a.kind)===m.VIDEO){if(a.ssrc===r.video?(d=m.VIDEO,l=i.localMainVideoTrack):a.ssrc===r.small?d=m.SMALL:a.ssrc===r.auxiliary&&(l=i.localAuxVideoTrack,d=m.AUXILIARY),!d)return;if(e[d].bytesSent=a.bytesSent,e[d].packetsSent=a.packetsSent,e[d].framesEncoded=a.framesEncoded,T(a.keyFramesEncoded)||(e[d].keyFramesEncoded=a.keyFramesEncoded),T(a.nackCount)||(e[d].nackCount=a.nackCount),T(a.pliCount)||(e[d].pliCount=a.pliCount),T(a.retransmittedPacketsSent)||(e[d].retransmittedPacketsSent=a.retransmittedPacketsSent),T(a.totalEncodeTime)||(e[d].totalEncodeTime=a.totalEncodeTime),T(a.totalPacketSendDelay)||(e[d].totalPacketSendDelay=a.totalPacketSendDelay),!T(a.encoderImplementation)&&(d===m.VIDEO&&this._prevEncoderImplementation!==a.encoderImplementation||d===m.AUXILIARY&&this._prevAuxEncoderImpl!==a.encoderImplementation)){let D=2,_=this._prevEncoderImplementation;d===m.AUXILIARY&&(D=7,_=this._prevAuxEncoderImpl),S.emit("262",{userId:i.userId,streamType:D,prevImplementation:_,implementation:a.encoderImplementation,codec:i.videoCodec,isHWCodec:a.powerEfficientEncoder}),this[d===m.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=a.encoderImplementation,this._log.info(`${d===m.AUXILIARY?"aux ":""}encoderImplementation change to ${a.encoderImplementation}(${i.videoCodec}) HWEncoder: ${a.powerEfficientEncoder}`)}a.ssrc===r.video?!T(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`qualityLimitationReason change to ${a.qualityLimitationReason}`),S.emit("263",{userId:i.userId,reason:a.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:(u=i.localMainVideoTrack)==null?void 0:u.isQosClearFirst}),this._prevQualityLimitationReason=a.qualityLimitationReason):a.ssrc===r.auxiliary&&!T(a.qualityLimitationReason)&&a.bytesSent!==0&&this._prevAuxQualityLimitationReason!==a.qualityLimitationReason&&(this._log.info(`aux qualityLimitationReason change to ${a.qualityLimitationReason}`),S.emit("263",{userId:i.userId,reason:a.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:(h=i.localAuxVideoTrack)==null?void 0:h.isQosClearFirst}),this._prevAuxQualityLimitationReason=a.qualityLimitationReason)}else e.audio.bytesSent=a.bytesSent,e.audio.packetsSent=a.packetsSent;else a.type==="candidate-pair"?Yi(a)&&(this.totalBytesSent=a.bytesSent,Y(a.currentRoundTripTime)&&(e.rtt=Math.floor(a.currentRoundTripTime*1e3))):a.type==="media-source"&&(a.kind===m.AUDIO?(e.audio.audioLevel=a.audioLevel||0,e.audio.totalAudioEnergy=a.totalAudioEnergy||0,a.echoReturnLoss,a.totalSamplesDuration&&(e.audio.totalSamplesDuration=a.totalSamplesDuration)):a.kind===m.VIDEO&&(a.trackIdentifier===i.getVideoTrackId(m.VIDEO)?e.video.fpsCapture=a.framesPerSecond:a.trackIdentifier===i.getVideoTrackId(m.AUXILIARY)?e.auxiliary.fpsCapture=a.framesPerSecond:e.small.fpsCapture=a.framesPerSecond));if(!T(a.audioLevel)&&((f=i.localMainAudioTrack)!=null&&f.mediaTrack)&&a.trackIdentifier===i.localMainAudioTrack.mediaTrack.id&&(e.audio.audioLevel=a.audioLevel||0),!T(a.frameWidth)){let g=m.SMALL;a.trackIdentifier===i.getVideoTrackId(m.VIDEO)||a.ssrc===r.video?g=m.VIDEO:(a.trackIdentifier===i.getVideoTrackId(m.AUXILIARY)||a.ssrc===r.auxiliary)&&(g=m.AUXILIARY),e[g].frameWidth=a.frameWidth,e[g].frameHeight=a.frameHeight,e[g].framesSent=a.framesSent}}),i.localMainAudioTrack){let a=i.localMainAudioTrack.getInternalAudioLevel();e.audio.micAudioLevel=a,e.audio.audioLevel===0&&(e.audio.audioLevel=a)}this.totalBytesSent||(this.totalBytesSent+=e.audio.bytesSent+e.video.bytesSent+e.auxiliary.bytesSent),Object.keys(e).forEach(a=>{a===m.AUDIO?(i.localMainAudioTrack&&(i.localMainAudioTrack.stat=e[a]),i.localAuxAudioTrack&&(i.localAuxAudioTrack.stat=e[a])):a===m.VIDEO?i.localMainVideoTrack&&(i.localMainVideoTrack.stat=e[a]):a===m.AUXILIARY&&i.localAuxVideoTrack&&(i.localAuxVideoTrack.stat=e[a])})}catch(n){this._log.warn(`failed to getStats on sender connection ${n}`)}return e.rtt===0&&(e.rtt=((o=this.room.networkQuality)==null?void 0:o.uplinkRTT)||0),e})}getReceiverStats(i){return p(this,null,function*(){var r,o,n;let e={tinyId:i.tinyId,userId:i.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0}},t=i.getPeerConnection();if(t)try{let{ssrc:a}=i,{muteState:d,subscribeState:l}=i;(this._spcStats||(yield t.getStats())).forEach(h=>{if(h.type==="inbound-rtp"){let f=(h.mediaType||h.kind)===m.AUDIO;if(f){if(h.ssrc!==a.audio||!d.hasAudio)return;e.audio.packetsReceived=h.packetsReceived,e.audio.bytesReceived=h.bytesReceived,e.audio.packetsLost=h.packetsLost,h.insertedSamplesForDeceleration&&(e.audio.insertedSamplesForDeceleration=h.insertedSamplesForDeceleration),h.removedSamplesForAcceleration&&(e.audio.removedSamplesForAcceleration=h.removedSamplesForAcceleration),h.totalSamplesDuration&&(e.audio.totalSamplesDuration=h.totalSamplesDuration),h.totalSamplesReceived&&(e.audio.totalSamplesReceived=h.totalSamplesReceived),h.concealedSamples&&(e.audio.concealedSamples=h.concealedSamples);let{remoteAudioTrack:g}=i;g.stat.packetsReceived=h.packetsReceived,g.stat.bytesReceived=h.bytesReceived,g.stat.packetsLost=h.packetsLost,e.audio.p2pDelay=g.stat.end2EndDelay,e.hasAudio=!0}else{if(se&&h.bytesReceived===0)return;let g;h.ssrc===a.video&&d.hasVideo&&(e.video.packetsReceived=h.packetsReceived,e.video.bytesReceived=h.bytesReceived,e.video.packetsLost=h.packetsLost,e.video.framesReceived=h.framesReceived,e.video.framesDecoded=h.framesDecoded,e.video.fpsDecoded=h.framesPerSecond,e.hasVideo=!0,g=i.remoteVideoTrack,d.hasSmall&&l.smallVideo&&(e.isSmallSubscribed=!0),h.decoderImplementation&&(!this._prevDecoderImplementationMap.has(e.userId)||this._prevDecoderImplementationMap.get(e.userId)!==h.decoderImplementation)&&(this._log.info(`${e.userId} decoderImplementation change to ${h.decoderImplementation} HWDecoder: ${h.powerEfficientDecoder}`),S.emit("262",{userId:this.room.userId,remoteUserId:e.userId,prevImplementation:this._prevDecoderImplementationMap.get(e.userId),implementation:h.decoderImplementation,codec:i.videoCodec,isHWCodec:h.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(e.userId,h.decoderImplementation))),h.ssrc===a.auxiliary&&d.hasAuxiliary&&(e.auxiliary.packetsReceived=h.packetsReceived,e.auxiliary.bytesReceived=h.bytesReceived,e.auxiliary.packetsLost=h.packetsLost,e.auxiliary.framesReceived=h.framesReceived,e.auxiliary.framesDecoded=h.framesDecoded,e.auxiliary.fpsDecoded=h.framesPerSecond,g=i.remoteAuxiliaryTrack,e.hasAuxiliary=!0),g&&(g.stat.packetsReceived=h.packetsReceived,g.stat.bytesReceived=h.bytesReceived,g.stat.packetsLost=h.packetsLost,g.stat.framesReceived=h.framesReceived,g.stat.framesDecoded=h.framesDecoded,h.jitterBufferDelay&&(g.stat.jitterBufferDelay=Math.floor(h.jitterBufferDelay/h.jitterBufferEmittedCount*1e3)))}h.jitterBufferDelay&&(f?(e.audio.totalJitter=h.jitterBufferDelay,e.audio.totalJitterCount=h.jitterBufferEmittedCount):h.ssrc===a.video&&d.hasVideo?(e.video.totalJitter=h.jitterBufferDelay,e.video.totalJitterCount=h.jitterBufferEmittedCount):h.ssrc===a.auxiliary&&d.hasAuxiliary&&(e.auxiliary.totalJitter=h.jitterBufferDelay,e.auxiliary.totalJitterCount=h.jitterBufferEmittedCount))}else h.type==="candidate-pair"&&Yi(h)&&(this.totalBytesReceived=h.bytesReceived,Y(h.currentRoundTripTime)&&(e.rtt=Math.floor(h.currentRoundTripTime*1e3)));T(h.frameWidth)||((h.trackIdentifier===i.getMainStreamVideoTrackId()||h.ssrc===a.video)&&(e.video.frameWidth=h.frameWidth,e.video.frameHeight=h.frameHeight,i.remoteVideoTrack.stat.frameWidth=h.frameWidth,i.remoteVideoTrack.stat.frameHeight=h.frameHeight),(h.trackIdentifier===i.getAuxStreamVideoTrackId()||h.ssrc===a.auxiliary)&&(e.auxiliary.frameWidth=h.frameWidth,e.auxiliary.frameHeight=h.frameHeight,i.remoteAuxiliaryTrack.stat.frameWidth=h.frameWidth,i.remoteAuxiliaryTrack.stat.frameHeight=h.frameHeight)),!T(h.audioLevel)&&i.muteState.audioAvailable&&i.remoteAudioTrack.mediaTrack&&h.trackIdentifier===i.remoteAudioTrack.mediaTrack.id&&(e.audio.audioLevel=h.audioLevel||0,e.audio.totalAudioEnergy=h.totalAudioEnergy||0)}),e.audio.audioLevel===0&&i.muteState.audioAvailable&&(e.audio.audioLevel=i.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=e.audio.bytesReceived+e.video.bytesReceived+e.auxiliary.bytesReceived),T((r=i.remoteVideoTrack.player.stat)==null?void 0:r.fps)||(e.video.fpsRender=i.remoteVideoTrack.player.stat.fps),T((o=i.remoteAuxiliaryTrack.player.stat)==null?void 0:o.fps)||(e.auxiliary.fpsRender=i.remoteAuxiliaryTrack.player.stat.fps)}catch(a){this._log.warn(`failed to getStats on receiver connection ${a}`)}return e.rtt===0&&(e.rtt=((n=this.room.networkQuality)==null?void 0:n.uplinkRTT)||0),e})}getStats(i,e){return p(this,null,function*(){let t={},r=[];if(this.room.singlePC){let o=this.room.singlePC.getPeerConnection();if(!o)return{senderStats:t,receiverStats:r};let n=P(),a=yield o.getStats(),d=P();d-n>2e3&&this._log.warn(`getStats cost ${d-n}ms`);let l=[],u=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source"]);a.forEach(h=>u.has(h.type)&&l.push(h)),this._spcStats=l}i&&(t=yield this.getSenderStats(i));for(let[o,n]of e){let a=yield this.getReceiverStats(n);r.push(a)}return{senderStats:t,receiverStats:r}})}getDifferenceValue(i,e){if(ri(i))return e;let t=e-i;return t<0?0:t}prepareReport({stats:i,report:e,freezeMap:t}){var f,g,D;if(!ri(i.senderStats)){let _={uint32_audio_level:i.senderStats.audio.audioLevel*Et,uint32_audio_energy:(i.senderStats.audio.totalAudioEnergy||0)*1e6,uint32_audio_codec_bitrate:i.senderStats.audio.bytesSent};i.senderStats.audio.micAudioLevel&&(_.uint32_mic_audio_level=i.senderStats.audio.micAudioLevel*Et),i.senderStats.audio.totalSamplesDuration&&(e.msg_device_info.uint32_audio_capture_cost=i.senderStats.audio.totalSamplesDuration);let R=[];if(i.senderStats.video.bytesSent){let j={uint32_video_stream_type:2,uint32_video_codec_fps:i.senderStats.video.framesSent,uint32_video_capture_fps:i.senderStats.video.fpsCapture,uint32_video_width:i.senderStats.video.frameWidth,uint32_video_height:i.senderStats.video.frameHeight,uint32_video_codec_bitrate:i.senderStats.video.bytesSent,uint32_video_enc_fps:i.senderStats.video.framesEncoded,uint32_key_frame_count:i.senderStats.video.keyFramesEncoded,uint32_nack_count:i.senderStats.video.nackCount,uint32_pli_count:i.senderStats.video.pliCount,uint32_encode_cost:(i.senderStats.video.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.video.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.video.retransmittedPacketsSent};R.push(j)}if(i.senderStats.small.bytesSent){let j={uint32_video_stream_type:3,uint32_video_codec_fps:i.senderStats.small.framesSent||0,uint32_video_capture_fps:i.senderStats.small.fpsCapture||0,uint32_video_width:i.senderStats.small.frameWidth||0,uint32_video_height:i.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:i.senderStats.small.bytesSent,uint32_video_enc_fps:i.senderStats.small.framesEncoded||0,uint32_key_frame_count:i.senderStats.small.keyFramesEncoded,uint32_nack_count:i.senderStats.small.nackCount,uint32_pli_count:i.senderStats.small.pliCount,uint32_encode_cost:(i.senderStats.small.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.small.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.small.retransmittedPacketsSent};R.push(j)}if(i.senderStats.auxiliary.bytesSent){let j={uint32_video_stream_type:7,uint32_video_codec_fps:i.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:i.senderStats.auxiliary.fpsCapture||0,uint32_video_width:i.senderStats.auxiliary.frameWidth||0,uint32_video_height:i.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:i.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:i.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:i.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:i.senderStats.auxiliary.nackCount,uint32_pli_count:i.senderStats.auxiliary.pliCount,uint32_encode_cost:(i.senderStats.auxiliary.totalEncodeTime||0)*1e3,uint32_send_packet_cost:(i.senderStats.auxiliary.totalPacketSendDelay||0)*1e3,uint32_video_arq_packets:i.senderStats.auxiliary.retransmittedPacketsSent};R.push(j)}let k={uint32_bitrate:0,uint32_lost:0,uint32_rtt:i.senderStats.rtt};e.msg_up_stream_info={msg_audio_status:_,msg_video_status:R,msg_network_status:k}}let r=(f=ve())==null?void 0:f.playoutStats;r&&(e.msg_device_info.uint32_audio_play_cost=r.totalFramesDuration);let{statInterval:o}=this;e.msg_down_stream_info=[],i.receiverStats.forEach(_=>{let R={msg_user_info:{str_identifier:_.userId,uint64_tinyid:_.tinyId},msg_network_status:{uint32_rtt:_.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(_.hasAudio){let k={uint32_audio_p2p_delay:_.audio.p2pDelay,uint32_audio_cache_ms:_.audio.totalJitter,uint32_audio_cache_ms_count:_.audio.totalJitterCount,uint32_audio_codec_bitrate:_.audio.bytesReceived,uint32_audio_total_bitrate:_.audio.bytesReceived,uint32_audio_level:_.audio.audioLevel*1e8,uint32_audio_energy:_.audio.totalAudioEnergy*1e6,uint32_audio_receive:_.audio.packetsReceived,uint32_audio_origin_lost:_.audio.packetsLost};R.msg_audio_status=k}if(_.hasVideo){let k=t.get(`${_.userId}_${Dc}`),j=k?k.duration:0,oe={uint32_video_stream_type:_.isSmallSubscribed?3:2,uint32_video_receive_fps:_.video.framesReceived,uint32_video_width:_.video.frameWidth,uint32_video_height:_.video.frameHeight,uint32_video_codec_bitrate:_.video.bytesReceived,uint32_video_receive:_.video.packetsReceived,uint32_video_origin_lost:_.video.packetsLost,uint32_video_block_time:j,uint32_video_dec_fps:_.video.framesDecoded,uint32_video_codec_fps:_.video.fpsRender,uint32_video_cache_ms:_.video.totalJitter,uint32_video_cache_ms_count:_.video.totalJitterCount};R.msg_video_status.push(oe)}if(_.hasAuxiliary){let k=t.get(`${_.userId}_${Oc}`),j=k?k.duration:0,oe={uint32_video_stream_type:7,uint32_video_receive_fps:_.auxiliary.framesReceived,uint32_video_width:_.auxiliary.frameWidth,uint32_video_height:_.auxiliary.frameHeight,uint32_video_codec_bitrate:_.auxiliary.bytesReceived,uint32_video_receive:_.auxiliary.packetsReceived+_.auxiliary.packetsLost,uint32_video_origin_lost:_.auxiliary.packetsLost,uint32_video_block_time:j,uint32_video_dec_fps:_.auxiliary.framesDecoded,uint32_video_codec_fps:_.video.fpsRender,uint32_video_cache_ms:_.auxiliary.totalJitter,uint32_video_cache_ms_count:_.auxiliary.totalJitterCount};R.msg_video_status.push(oe)}e.msg_down_stream_info.push(R)});let n=this._prevReport,a=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(e)),this._prevStats=JSON.parse(JSON.stringify(i)),e.msg_up_stream_info.msg_audio_status&&n.msg_up_stream_info.msg_audio_status){let _=n.msg_up_stream_info.msg_audio_status,R=e.msg_up_stream_info.msg_audio_status;if(_.uint32_audio_codec_bitrate===0)R.uint32_audio_codec_bitrate=0;else{let k=this.getDifferenceValue(_.uint32_audio_codec_bitrate,R.uint32_audio_codec_bitrate);R.uint32_audio_codec_bitrate=Math.round(k*8/o),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=R.uint32_audio_codec_bitrate}(g=n.msg_device_info)!=null&&g.uint32_audio_capture_cost?e.msg_device_info.uint32_audio_capture_cost=2*Math.floor(this.getDifferenceValue(n.msg_device_info.uint32_audio_capture_cost,e.msg_device_info.uint32_audio_capture_cost)*1e3/o):delete e.msg_device_info.uint32_audio_capture_cost}let d=n.msg_up_stream_info.msg_video_status;e.msg_up_stream_info.msg_video_status.forEach(_=>{let R=d.find(G=>G.uint32_video_stream_type===_.uint32_video_stream_type);if(!R||R.uint32_video_codec_bitrate===0){_.uint32_video_codec_bitrate=0,_.uint32_video_enc_fps=0,_.uint32_video_codec_fps=0;return}let k=0,j=0,oe=0;R&&_.uint32_video_codec_bitrate>=R.uint32_video_codec_bitrate&&(k=R.uint32_video_codec_bitrate,j=R.uint32_video_enc_fps,oe=R.uint32_video_codec_fps);let Ve=this.getDifferenceValue(k,_.uint32_video_codec_bitrate);_.uint32_video_codec_bitrate=Math.round(Ve*8/o),e.msg_up_stream_info.msg_network_status.uint32_bitrate+=_.uint32_video_codec_bitrate,_.uint32_video_enc_fps=Math.round(this.getDifferenceValue(j,_.uint32_video_enc_fps)/o),_.uint32_video_codec_fps=Math.round(this.getDifferenceValue(oe,_.uint32_video_codec_fps)/o),R.uint32_video_width===0&&R.uint32_video_height===0&&R.uint32_video_codec_fps===0&&(_.uint32_video_codec_fps=_.uint32_video_enc_fps),T(R.uint32_key_frame_count)||(_.uint32_key_frame_count=Math.round(this.getDifferenceValue(R.uint32_key_frame_count,_.uint32_key_frame_count))),T(R.uint32_nack_count)||(_.uint32_nack_count=Math.round(this.getDifferenceValue(R.uint32_nack_count,_.uint32_nack_count))),T(R.uint32_pli_count)||(_.uint32_pli_count=Math.round(this.getDifferenceValue(R.uint32_pli_count,_.uint32_pli_count))),T(R.uint32_video_arq_packets)||(_.uint32_video_arq_packets=Math.round(this.getDifferenceValue(R.uint32_video_arq_packets,_.uint32_video_arq_packets))),T(R.uint32_encode_cost)||(_.uint32_encode_cost=Math.round(this.getDifferenceValue(R.uint32_encode_cost,_.uint32_encode_cost)/o)),T(R.uint32_send_packet_cost)||(_.uint32_send_packet_cost=Math.round(this.getDifferenceValue(R.uint32_send_packet_cost,_.uint32_send_packet_cost)/o))});let u=n.msg_down_stream_info;e.msg_down_stream_info=e.msg_down_stream_info.filter(_=>u.find(R=>R.msg_user_info.uint64_tinyid===_.msg_user_info.uint64_tinyid));let h=e.msg_down_stream_info;return h.forEach(_=>{let R=u.find(k=>k.msg_user_info.uint64_tinyid===_.msg_user_info.uint64_tinyid);if(!ri(_.msg_audio_status)&&!ri(R.msg_audio_status)){let k=_.msg_audio_status,j=R.msg_audio_status,oe=this.getDifferenceValue(j.uint32_audio_cache_ms_count,k.uint32_audio_cache_ms_count);delete k.uint32_audio_cache_ms_count,k.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(j.uint32_audio_cache_ms,k.uint32_audio_cache_ms)/oe)||0;let Ve=this.room.remotePublishedUserMap.get(_.msg_user_info.str_identifier);Ve&&(Ve.remoteAudioTrack.stat.jitterBufferDelay=k.uint32_audio_cache_ms),k.uint32_audio_origin_lost=this.getDifferenceValue(j.uint32_audio_origin_lost,k.uint32_audio_origin_lost),k.uint32_audio_receive=this.getDifferenceValue(j.uint32_audio_receive,k.uint32_audio_receive),k.uint32_audio_receive+=k.uint32_audio_origin_lost;let G=this.getDifferenceValue(j.uint32_audio_codec_bitrate,k.uint32_audio_codec_bitrate);k.uint32_audio_codec_bitrate=Math.round(G*8/o),k.uint32_audio_total_bitrate=Math.round(G*8/o)}else _.msg_audio_status={};if(_.msg_video_status&&R.msg_video_status){let k=R.msg_video_status;_.msg_video_status=_.msg_video_status.filter(oe=>k.find(Ve=>Ve.uint32_video_stream_type===oe.uint32_video_stream_type)),_.msg_video_status.forEach(oe=>{let Ve=k.find(jp=>jp.uint32_video_stream_type===oe.uint32_video_stream_type),G=Ve.uint32_video_receive,Bp=Ve.uint32_video_origin_lost,Fp=Ve.uint32_video_codec_bitrate,Hp=Ve.uint32_video_receive_fps,$p=Ve.uint32_video_dec_fps;oe.uint32_video_origin_lost=this.getDifferenceValue(Bp,oe.uint32_video_origin_lost),oe.uint32_video_receive=this.getDifferenceValue(G,oe.uint32_video_receive)+oe.uint32_video_origin_lost;let Gp=this.getDifferenceValue(Fp,oe.uint32_video_codec_bitrate);oe.uint32_video_codec_bitrate=Math.round(Gp*8/o);let Wp=this.getDifferenceValue(Hp,oe.uint32_video_receive_fps);oe.uint32_video_receive_fps=Math.round(Wp/o),oe.uint32_video_dec_fps=Math.round(this.getDifferenceValue($p,oe.uint32_video_dec_fps)/o);let Jp=this.getDifferenceValue(Ve.uint32_video_cache_ms_count,oe.uint32_video_cache_ms_count);delete oe.uint32_video_cache_ms_count,oe.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(Ve.uint32_video_cache_ms,oe.uint32_video_cache_ms)/Jp)||0})}}),(D=n.msg_device_info)!=null&&D.uint32_audio_play_cost?e.msg_device_info.uint32_audio_play_cost=2*Math.floor(this.getDifferenceValue(n.msg_device_info.uint32_audio_play_cost,e.msg_device_info.uint32_audio_play_cost)/o):delete e.msg_device_info.uint32_audio_play_cost,a&&i.receiverStats.forEach(_=>{if(_.audio.concealedSamples&&_.audio.totalSamplesReceived){let R=a.receiverStats.find(k=>k.userId===_.userId);if(R&&R.audio.concealedSamples&&R.audio.totalSamplesReceived){let k=_.audio.concealedSamples-R.audio.concealedSamples,j=_.audio.totalSamplesReceived-R.audio.totalSamplesReceived,oe=Math.floor(k/j*1e3*o);if(oe>o*1e3/5){let Ve=h.find(G=>G.msg_user_info.str_identifier===_.userId);Ve&&(Ve.msg_audio_status.uint32_audio_block_time=oe)}}}}),e}getStatsReport(r){return p(this,arguments,function*({uplinkConnection:i,downlinkConnections:e,freezeMap:t}){let o={msg_device_info:{},msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_cache_ms:0,uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},n=yield this.getStats(i,e);return JSON.stringify(this._prevReport)==="{}"&&(this._prevReport=JSON.parse(JSON.stringify(o))),this.prepareReport({stats:n,report:o,freezeMap:t}),this._prevReportTime=Date.now(),o})}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map}};var hp=Be(ze());function lp(s){let i={totalCost:0,local:0,redirect:0,httpCache:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let e=performance.getEntriesByType("resource").reverse();for(let t of e)if(t.name===s){let r=Math.round(t.duration),o=Math.max(Math.round(t.domainLookupStart-t.startTime),0),n=t.redirectStart>0?Math.max(Math.round(t.redirectEnd-t.redirectStart),0):0,a=t.fetchStart>0?Math.max(Math.round(t.domainLookupStart-t.fetchStart),0):0,d=Math.round(t.domainLookupEnd-t.domainLookupStart),l=Math.round(t.requestStart-t.secureConnectionStart),u=Math.round(t.secureConnectionStart-t.connectStart),h=Math.round(t.responseStart-t.requestStart),f=Math.round(t.responseEnd-(t.responseStart||t.startTime));i=L(v({},i),{totalCost:r,local:o,redirect:n,httpCache:a,dns:d,tcp:u,tls:l,request:h,response:f});break}}catch(e){}return i}function up(s){return new Promise(i=>p(this,null,function*(){let e=setTimeout(()=>{i({totalCost:1e4,local:0,dns:0,tcp:0,tls:0,request:0,response:0})},1e4),t=Date.now(),r=`https://${s}/?t=${t}`;try{yield fetch(r)}catch(n){}clearTimeout(e);let o=lp(r);o.totalCost===0&&(o.totalCost=Date.now()-t),i(o)}))}var wT=700,Vr=class Vr extends hp.default{constructor({signalChannel:e,room:t}){super();c(this,"_room");c(this,"_signalChannel");c(this,"_log");c(this,"uplinkRTT",0);c(this,"uplinkLoss",0);c(this,"downlinkRTT",0);c(this,"downlinkLoss",0);c(this,"pingResults",{});c(this,"_downlinkPrevStatMap",new Map);c(this,"_downlinkLossAndRTTMap",new Map);c(this,"_interval",-1);c(this,"_uplinkNetworkQuality",0);c(this,"_downlinkNetworkQuality",0);this._room=t,this._signalChannel=e,this._log=C.createLogger({id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info(`uplink ${this.uplinkNetworkQuality} -> ${e}, rtt: ${this.uplinkRTT}, loss: ${this.uplinkLoss} ws-rtt: ${this._signalChannel.rtt}`),this._uplinkNetworkQuality=e}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:t,loss:r}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info(`downlink ${this.downlinkNetworkQuality} -> ${e}, rtt: ${t}, loss: ${r} ws-rtt: ${this._signalChannel.rtt}`)}this._downlinkNetworkQuality=e}initialize(){this._signalChannel.on(H.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(Ce.CONNECTION_STATE_CHANGED,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var d,l;if(e.data.code!==0)return;let t=e.data.data;if(t.delay&&this.updateDelay(t.delay),this._room.signalChannel&&t.wsRtt&&(this._room.signalChannel.rtt=t.wsRtt),!this._room.uplinkConnection){this.uplinkNetworkQuality=0,this.uplinkLoss=0,this.uplinkRTT=0;return}let r=(l=(d=this._room)==null?void 0:d.uplinkConnection)==null?void 0:l.getPeerConnection();if(r&&this.isPeerConnectionDisconnected(r)){this.uplinkNetworkQuality=6,this.uplinkLoss=0,this.uplinkRTT=0;return}let o=t.expectAudPkg+t.expectVidPkg,n=t.recvAudPkg+t.recvVidPkg,a=o-n;o===0&&n===0||(a<=0?this.uplinkLoss=0:this.uplinkLoss=Math.round(a/o*100),this.uplinkRTT=t.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return p(this,null,function*(){if(this._room.remotePublishedUserMap.size===0){this.downlinkNetworkQuality=0;return}let e=[...this._room.remotePublishedUserMap.values()],t=e.filter(a=>{var d;return((d=a.getPeerConnection())==null?void 0:d.connectionState)===me.CONNECTED});if(e.filter(a=>this.isPeerConnectionDisconnected(a.getPeerConnection())).length===e.length){this.downlinkNetworkQuality=6;return}for(let a=0;a<t.length;a++){let d=t[a].getPeerConnection();if(!d)return;let{rtt:l,totalPacketsLost:u,totalPacketsReceived:h}=yield this.getStat(d);if(!this._downlinkPrevStatMap.has(d)){this._downlinkPrevStatMap.set(d,{totalPacketsLost:u,totalPacketsReceived:h});continue}let f=0,g=this._downlinkPrevStatMap.get(d),D=u-g.totalPacketsLost,_=h-g.totalPacketsReceived;D<=0||_<0?f=0:f=Math.round(D/(D+_)*100),this._downlinkPrevStatMap.set(d,{totalPacketsLost:u,totalPacketsReceived:h}),this._downlinkLossAndRTTMap.set(d,{rtt:l,loss:f,userId:t[a].getUserId(),audioDelay:t[a].remoteAudioTrack.stat.end2EndDelay,videoDelay:t[a].remoteVideoTrack.stat.end2EndDelay})}if([...this._downlinkPrevStatMap.keys()].forEach(a=>{this.isPeerConnectionDisconnected(a)&&(this._downlinkPrevStatMap.delete(a),this._downlinkLossAndRTTMap.delete(a))}),this._downlinkLossAndRTTMap.size===0){this.downlinkRTT=0,this.downlinkLoss=0,this.downlinkNetworkQuality=0;return}let{rtt:o,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=o,this.downlinkLoss=n,this.downlinkNetworkQuality=this.getNetworkQuality(n,o)})}getStat(e){return p(this,null,function*(){let t={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!Ar())return t;let r=e.getReceivers();try{for(let o=0;o<r.length;o++)(yield r[o].getStats()).forEach(d=>{d.type==="candidate-pair"&&Y(d.currentRoundTripTime)&&(t.rtt=Math.round(d.currentRoundTripTime*1e3)),d.type==="inbound-rtp"&&(d.mediaType===m.AUDIO||d.mediaType===m.VIDEO)&&(t.totalPacketsLost+=d.packetsLost,t.totalPacketsReceived+=d.packetsReceived)});return t.rtt===0&&(t.rtt=this.uplinkRTT),t}catch(o){return t}})}getAverageLossAndRTT(e){let t={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach(r=>{t.rtt+=r.rtt,t.loss+=r.loss}),Object.keys(t).forEach(r=>{t[r]=Math.round(t[r]/e.length)})),t}getNetworkQuality(e,t){return e>50||t>500?5:e>30||t>350?4:e>20||t>200?3:e>10||t>100?2:e>=0||t>=0?1:0}handleSignalConnectionStateChange(e){e.state==="DISCONNECTED"?(this.uplinkRTT=0,this.uplinkLoss=0,this.uplinkNetworkQuality=6):e.state==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}handleUplinkConnectionStateChange({state:e}){e==="DISCONNECTED"?(this.uplinkLoss=0,this.uplinkRTT=0,this.uplinkNetworkQuality=6):e==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!!(e&&(e.connectionState===me.DISCONNECTED||e.connectionState===me.FAILED||e.connectionState===me.CLOSED))}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this.uplinkRTT=0,this.uplinkLoss=0)}start(){if(this._interval!==-1){this._log.info("network quality calculating is already started");return}this._log.debug("start network quality calculating"),this._interval=re.run("ric",()=>{var n;this.handleDownlinkNetworkQuality();let e=[...this._downlinkLossAndRTTMap.values()];S.emit(E.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this.uplinkRTT,loss:this.uplinkLoss},downlinks:e});let t=(n=this._room.scheduleResult.config)==null?void 0:n.pingDomainInfo,r={uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this.uplinkRTT,uplinkLoss:this.uplinkLoss,downlinkRTT:this.downlinkRTT,downlinkLoss:this.downlinkLoss};t&&(r=L(v({},r),{pingResults:this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold?this.pingResults:{}})),this.emit(Vr.EVENT_NETWORK_QUALITY,r);let o=Date.now();if(t&&(this.uplinkRTT>t.rttThreshold||this.downlinkRTT>t.rttThreshold)&&o-Vr.lastPingTime>t.interval*1e3){Vr.lastPingTime=Date.now();let a=t.domain.map(d=>up(d).then(l=>({domain:d,cost:l.totalCost})));Promise.all(a).then(d=>{this.pingResults.isPoorNetwork=d.some(l=>l.cost>wT),this.pingResults.timestamp=o,this.pingResults.data=d,d.forEach(l=>{N.addSuccessEvent({key:521718,cost:l.cost})}),this._log.warn(`All ping results: ${JSON.stringify(d)}`)}).catch(d=>{this._log.warn(`Error during pinging domains: ${d}`)})}},{delay:2e3})}stop(){this._log.debug("stopped"),this._interval!==-1&&(re.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:t}=this._room;e.forEach(({srcTinyId:r,videoDelay:o,audioDelay:n})=>{let a=t.get(r);if(a){let d=this._room.remotePublishedUserMap.get(a);d==null||d.setDelay({videoDelay:o,audioDelay:n})}})}};c(Vr,"EVENT_NETWORK_QUALITY","0"),c(Vr,"lastPingTime",0);var ws=Vr;function xT({fn:s,context:i}){return function(...e){try{let t=s.apply(i,e);return ji(t)?t.catch(r=>C.error(`${s.name}() error observed ${r}`)):t}catch(t){C.error(`${s.name}() error observed ${t}`)}}}var ac=class{constructor(i){c(this,"_frameWorkType");c(this,"_component");c(this,"_language");c(this,"connectionType");c(this,"_room");c(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0});c(this,"_keyPrefix");c(this,"_log");c(this,"_intervalId");c(this,"_firstPublishedUserList");c(this,"_networkQuality");c(this,"_basicInfo");c(this,"_pathJoinRoom");c(this,"_pathLeaveRoom");c(this,"_pathMainVideoMap");c(this,"_pathMainAudioMap");c(this,"_pathAuxiliaryMap");c(this,"_remoteStreamStatMap");c(this,"_localStreamStat");c(this,"_eventMap",new Map);c(this,"_captureCostSum",0);c(this,"_captureCostCount",0);c(this,"isDestroyed",!1);this._frameWorkType=i.frameWorkType||30,this._component=i.component||0,this.connectionType=i.connectionType||1,this._language=i.language||0,this._room=i.room,this._keyPrefix="key_point",this._log=C.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&ce(this[e])&&(this[e]=xT({fn:this[e],context:this}))}),this.initData(),this.installEvents()}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:Oe,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,po().then(i=>{this._basicInfo.string_os_version=Ri(),i?this._basicInfo.string_device_name=i.mobile?i.model:this._basicInfo.string_os_version:this._basicInfo.string_device_name=this._basicInfo.string_os_version})}addEvent(i,e){return this._eventMap.set(i,e),S.on(i,e),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("pagehide",this.handleUnload),this._room.once("banned",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(E.JOIN_START,this.handleJoinStart).addEvent(E.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(E.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(E.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(E.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(E.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(E.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(E.JOIN_FAILED,this.handleJoinFailed).addEvent(E.LEAVE_START,this.handleLeaveStart).addEvent(E.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(E.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(E.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(E.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(E.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(E.PUBLISH_START,this.handlePublishStart).addEvent(E.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(E.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(E.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(E.PLAY_TRACK_START,this.handlePlayStart).addEvent(E.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(E.PLAYER_STATE_CHANGED,({track:i,state:e,type:t})=>{!i.isRemote||!this.hitTest(i.room)||e==="PLAYING"&&(t===m.AUDIO?this.handleAudioPlaying(i):this.handleVideoPlaying(i))}).addEvent(E.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(E.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(E.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(E.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let r=e.hasAudio||e.hasVideo||e.hasSmall,o=e.hasAuxiliary,n=t.hasAudio||t.hasVideo||t.hasSmall,a=t.hasAuxiliary;!r&&n&&this.handleRemoteStreamAdded(t.userId,"main"),!o&&a&&this.handleRemoteStreamAdded(t.userId,"auxiliary")}).addEvent(E.SINGLE_CONNECTION_STAT,({room:i,stat:e})=>{this.hitTest(i)&&(this._pathJoinRoom.int32_ice_cost=e.ice,this._pathJoinRoom.int32_dtls_cost=e.dtls,this._pathJoinRoom.int32_peer_connection_cost=e.peerConnection)})}uninstallEvents(){window.removeEventListener("pagehide",this.handleUnload),this._eventMap.forEach((i,e)=>S.off(e,i)),this._eventMap.clear()}destroy(){this.uninstallEvents(),re.clearTask(this._intervalId),this._pathJoinRoom.uint64_start_time===0&&(this._room=null),this.isDestroyed=!0}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(i){this.hitTest(i.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now()),i.params&&(T(i.params.frameWorkType)||(this._frameWorkType=i.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),T(i.params.component)||(this._component=i.params.component,this._basicInfo.uint32_component=this._component),T(i.params.language)||(this._language=i.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess({room:i,detailCost:e}){if(this.hitTest(i)&&e){let{totalCost:t,local:r,dns:o,tcp:n,tls:a,request:d,response:l}=e;this._pathJoinRoom.int32_schedule_cost=t,this._pathJoinRoom.int32_schedule_local=r,this._pathJoinRoom.int32_schedule_dns=o,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=a,this._pathJoinRoom.int32_schedule_request=d,this._pathJoinRoom.int32_schedule_response=l}}handleSignalConnectionStart({room:i}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd({room:i,error:e}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),e&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=e instanceof b?Number(e.getExtraCode()||e.getCode()):I.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=i.code,i.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=i.room.getSignalInfo())}handleJoinFailed({room:i,error:e}){this.hitTest(i)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=e.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(i){this.hitTest(i.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=i.publishedUserList||[])}handleSendFirstVideoFrame({room:i}){this.hitTest(i)&&this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(i){this.hitTest(i.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(i){this.hitTest(i.room)&&this._pathLeaveRoom.uint64_end_time===0&&(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(i){this.hitTest(i.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(i,e){var r;let t=`${i}_${e}`;if(!this._remoteStreamStatMap.has(t)){let o={userId:i,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:L(v({},UT),{msg_user_info:new tn({userId:i,tinyId:(r=this._room.remotePublishedUserMap.get(i))==null?void 0:r.tinyId,role:20})})};o.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(t,o)}}handleSubscribeStart({room:i,remotePublishedUser:e,streamType:t,subscribeState:r}){if(!this.hitTest(i))return;let{userId:o,tinyId:n,role:a}=e,d=new tn({userId:o,tinyId:n,role:a==="anchor"?20:21}),l=Date.now(),u=`${o}_${t}`,h=this._remoteStreamStatMap.get(u);h&&h.subscribeStartTime===0&&(h.subscribeStartTime=l),t==="main"?(e.muteState.hasVideo&&(r.video||r.smallVideo)&&!this._pathMainVideoMap.has(u)&&this._pathMainVideoMap.set(u,{statsToReport:{msg_user_info:d,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:o,sendSubscribeCMDTime:l}),e.muteState.hasAudio&&r.audio&&!this._pathMainAudioMap.has(u)&&this._pathMainAudioMap.set(u,{statsToReport:{msg_user_info:d,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:o,sendSubscribeCMDTime:l})):e.muteState.hasAuxiliary&&r.auxiliary&&!this._pathAuxiliaryMap.has(u)&&this._pathAuxiliaryMap.set(u,{sendSubscribeCMDTime:l})}handleSubscribed({room:i,remotePublishedUser:e,streamType:t}){if(this.hitTest(i)){let r=`${e.userId}_${t}`,o=this._remoteStreamStatMap.get(r);o&&o.subscribedTime===0&&(o.subscribedTime=Date.now())}}handlePlayStart({track:i}){if(!i.isRemote||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._remoteStreamStatMap.get(e);(t==null?void 0:t.playStreamTime)===0&&(t.playStreamTime=Date.now())}handleVideoLoadedData({track:i}){if(!i.isRemote||!this.hitTest(i.room))return;let e=`${i.userId}_${i.streamType}`,t=this._pathMainVideoMap.get(e);t&&t.statsToReport.uint64_combine_first_frame_time===0&&(t.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(i){let e=`${i.userId}_${i.streamType}`,t=Date.now(),r=this._pathMainVideoMap.get(e),o=this._remoteStreamStatMap.get(e);if(o){let{statsToReport:n}=o;if(!n.uint32_video_render_first&&i.streamType==="main"?this.hasVideoFlag(i.userId):this.hasAuxFlag(i.userId)){let a=t-this._pathJoinRoom.uint64_start_time;n.uint32_video_render_first=a,N.addNumber({key:516820,value:a})}}(r==null?void 0:r.statsToReport.uint64_render_first_frame_time)===0&&(r.statsToReport.uint64_render_first_frame_time=t)}handleAudioPlaying(i){let e=`${i.userId}_${i.streamType}`,t=this._pathMainAudioMap.get(e);t&&t.statsToReport.uint64_play_first_frame_time===0&&(t.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(i){this.hitTest(i.room)&&(this._networkQuality.totalUplinkLoss+=i.uplink.loss,this._networkQuality.totalUplinkRTT+=i.uplink.rtt,this._networkQuality.count++,i.downlinks.forEach(({rtt:e,loss:t,userId:r,videoDelay:o,audioDelay:n})=>{let a=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(a)a.totalRTT+=e,a.totalLoss+=t,o&&(a.totalVideoDelay=(a.totalVideoDelay||0)+o,a.videoDelayCount=(a.videoDelayCount||0)+1),n&&(a.totalAudioDelay=(a.totalAudioDelay||0)+n,a.audioDelayCount=(a.audioDelayCount||0)+1),a.count++;else{let d,l,u,h;o&&(l=o,u=1),n&&(d=n,h=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(r,{totalRTT:e,totalLoss:t,count:1,totalAudioDelay:d,totalVideoDelay:l,audioDelayCount:h,videoDelayCount:u})}}))}handleHeartbeatStats(i){if(this.hitTest(i.room)){let{msg_device_info:e,msg_up_stream_info:t,msg_down_stream_info:r}=i.report;if(t.msg_video_status[0]){let{uint32_video_codec_bitrate:o,uint32_video_enc_fps:n,uint32_video_width:a,uint32_video_height:d}=t.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=o,this._localStreamStat.totalVideoFPS+=n,this._localStreamStat.totalVideoWidth+=a,this._localStreamStat.totalVideoHeight+=d,this._localStreamStat.videoCount++}if(t.msg_audio_status){let{uint32_audio_level:o}=t.msg_audio_status;Math.floor(o/Et*100)>0&&(this._localStreamStat.totalAudioLevel+=o/Et,this._localStreamStat.audioLevelCount++)}r.forEach(o=>{let{msg_user_info:n,msg_audio_status:a,msg_video_status:d}=o,l=n.str_identifier,u=this._room.remotePublishedUserMap.get(l);if(d.forEach(h=>{let f=h.uint32_video_stream_type===2,g=h.uint32_video_stream_type===7,D=`${l}_${f?"main":"auxiliary"}`,_=this._remoteStreamStatMap.get(D);if(_&&(f&&(u!=null&&u.remoteVideoTrack.isSubscribed)||g&&(u!=null&&u.remoteAuxiliaryTrack))){_.totalVideoFPS+=h.uint32_video_receive_fps,_.totalVideoBitrate+=h.uint32_video_codec_bitrate,_.videoCount++,_.statsToReport.uint32_video_width===0&&(_.statsToReport.uint32_video_width=h.uint32_video_width),_.statsToReport.uint32_video_height===0&&(_.statsToReport.uint32_video_height=h.uint32_video_height);let R=f?u.remoteVideoTrack:u.remoteAuxiliaryTrack;R.stat.jitterBufferDelay&&(_.videoJitterBufferDelay=R.stat.jitterBufferDelay),R.stat.framesReceived&&(_.statsToReport.uint32_video_consume_render_rate=Math.floor(R.stat.framesDecoded/R.stat.framesReceived*Bs(10,6)))}}),!Xr(a)){let h=`${l}_main`,f=this._remoteStreamStatMap.get(h);this._remoteStreamStatMap.has(h)&&f&&u!=null&&u.remoteAudioTrack.isSubscribed&&(f.totalAudioBitrate+=a.uint32_audio_codec_bitrate,f.audioCount++,u.remoteAudioTrack.stat.jitterBufferDelay&&(f.audioJitterBufferDelay=u.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(a.uint32_audio_level/Et*100)>0&&(f.totalAudioLevel+=a.uint32_audio_level/Et,f.audioLevelCount++))}}),e.uint32_audio_capture_cost&&(this._captureCostSum+=e.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0))}}handlePublishStart({room:i}){this.hitTest(i)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:i}){i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed({track:i,error:e}){let r={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof b?e.getExtraCode()||e.getCode():I.UNKNOWN);i.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=r,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),i.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=r,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&Gi)>=0}hasAudioFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&Wi)>=0}hasAuxFlag(i){return this._firstPublishedUserList.findIndex(e=>e.userId===i&&e.flag&cr)>=0}hitTest(i){return i===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let i=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=i<<16|e}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((i,e)=>{let{userId:t}=i,r=this._networkQuality.totalDownlinkRTTAndLossMap.get(t);if(r){let{totalLoss:u,count:h,audioDelayCount:f,videoDelayCount:g,totalAudioDelay:D,totalVideoDelay:_}=r;i.statsToReport.uint32_avg_down_loss=Math.floor(u/h),f&&D&&(i.statsToReport.uint32_audio_network_p2p_delay=Math.floor(D/f),i.audioJitterBufferDelay&&(i.statsToReport.uint32_p2p_delay=Math.floor(i.statsToReport.uint32_audio_network_p2p_delay+i.audioJitterBufferDelay))),g&&_&&(i.statsToReport.uint32_video_network_p2p_delay=Math.floor(_/g))}i.videoCount>0&&(i.statsToReport.uint32_video_avg_fps=Math.floor(i.totalVideoFPS/i.videoCount),i.statsToReport.uint32_video_avg_bitrate=Math.floor(i.totalVideoBitrate/i.videoCount)),i.audioCount>0&&(i.statsToReport.uint32_audio_recv_bitrate=i.statsToReport.uint32_audio_bitrate=Math.floor(i.totalAudioBitrate/i.audioCount)),i.audioLevelCount>0&&(i.statsToReport.uint32_audio_play_db=Math.floor(i.totalAudioLevel/i.audioLevelCount*100));let{callDurationCalculator:o}=this._room;o&&(i.statsToReport.uint32_audio_play_time=o.getDuration(e,m.AUDIO),i.statsToReport.uint32_video_play_time=o.getDuration(e,m.VIDEO)),i.statsToReport.uint32_video_render_first&&(i.statsToReport.uint32_video_render_first=Math.min(i.statsToReport.uint32_video_render_first,Br));let{badCaseDetector:n}=this._room,{dataFreeze:a,count:d}=n.getDataFreezeDuration(e),{renderFreeze:l}=n.getRenderFreezeDuration(e);i.statsToReport.uint32_video_block_count=d,i.statsToReport.uint32_video_block_time=Math.min(a,i.statsToReport.uint32_video_play_time),i.statsToReport.uint32_video_external_block_time=Math.min(l,i.statsToReport.uint32_video_play_time),n.isBlackStream(e)&&i.statsToReport.uint32_video_avg_fps===0?i.statsToReport.uint32_video_black_screen_subjective=1:i.statsToReport.uint32_video_black_screen_subjective=0}),this._pathMainAudioMap.forEach((i,e)=>{if(!this.hasAudioFlag(i.userId)){this._pathMainAudioMap.delete(e);return}i.statsToReport.uint64_play_first_frame_time-i.statsToReport.uint64_start_enter_time>Br&&(i.statsToReport.uint64_play_first_frame_time=i.statsToReport.uint64_start_enter_time+Br)}),this._pathMainVideoMap.forEach((i,e)=>{if(!this.hasVideoFlag(i.userId)){this._pathMainVideoMap.delete(e);return}i.statsToReport.uint64_render_first_frame_time-i.statsToReport.uint64_start_enter_time>Br&&(i.statsToReport.uint64_render_first_frame_time=i.statsToReport.uint64_start_enter_time+Br)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>Br&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+Br)}getReportData(){this._basicInfo.uint32_networkType=hr();let i={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new tn({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:zr(this._signalInfo.relayIp),uint32_client_ip:zr(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*Bs(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map(e=>e.statsToReport),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map(e=>e.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(e=>e.statsToReport),uint32_info_client_ip:zr(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend};return eo(i),i}report(){return p(this,null,function*(){try{this.prepareReport();let i=this.getReportData();yield this.upload(i),this.initData()}catch(i){this._log.warn(i)}finally{this.isDestroyed&&(this._room=null)}})}upload(i){return p(this,null,function*(){if(i.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),t=yield Hc(i),r=t instanceof ArrayBuffer,o=`${gi(e,$i.KEY_POINT)}&gzip=${+r}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(o,t));let a=[this.uploadKVStat(N),this.uploadKVStat(Ir)];n||a.push(Si({url:o,body:t,priority:"low"})),yield Promise.all(a)})}setConnectionType(i){this.connectionType=i,this._basicInfo.uint32_connection_type=i}uploadKVStat(i){return p(this,null,function*(){let e=i.getReportData();if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=L(v({},e.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(e);let t=yield Hc(e),r=`${gi(+this._room.sdkAppId,$i.KV_STAT)}&gzip=${+(t instanceof ArrayBuffer)}`,o=!1;navigator.sendBeacon&&(o=navigator.sendBeacon(r,t)),o||Si({url:r,body:t})})}};y([ot({settings:{timeout:500,retries:3}})],ac.prototype,"upload",1);var Br=5e3,UT={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},tn=class{constructor(i){c(this,"str_identifier");c(this,"str_tinyid");c(this,"uint32_role");this.str_identifier=String(i.userId),this.str_tinyid=String(i.tinyId||0),this.uint32_role=i.role}},mp=ac;var _u=class{constructor(){c(this,"_startTime");c(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=P())}stop(){this._endTime===0&&(this._endTime=P())}getDuration(){return this._endTime===0?P()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},cc=_u;var gu=class{constructor(i){c(this,"_room",null);c(this,"_durationMap");c(this,"_eventMap",new Map);this._room=i.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(E.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(E.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(E.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{var n;let{userId:r}=t;if(!this.hitTest(i))return;e.hasAudio&&!t.hasAudio&&this.stopDurationItem(`${r}_main`,m.AUDIO),e.hasVideo&&!t.hasVideo&&this.stopDurationItem(`${r}_main`,m.VIDEO),e.hasAuxiliary&&!t.hasAuxiliary&&this.stopDurationItem(`${r}_auxiliary`,m.VIDEO);let o=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(r);o&&(!e.hasAudio&&t.hasAudio&&o.remoteAudioTrack.isSubscribed&&this.addDuractionItem(r,m.AUDIO,"main"),!e.hasVideo&&t.hasVideo&&o.remoteVideoTrack.isSubscribed&&this.addDuractionItem(r,m.VIDEO,"main"),!e.hasAuxiliary&&t.hasAuxiliary&&o.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(r,m.VIDEO,"auxiliary"))}),this._eventMap.forEach((i,e)=>S.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>S.off(e,i,this)),this._eventMap.clear()}handleSubscribed({track:i}){if(!this.hitTest(i.room))return;let{userId:e,streamType:t,kind:r}=i;i.isSubscribed?this.addDuractionItem(e,r,t):this.stopDurationItem(`${e}_${t}`,r)}handleUnsubscribed({track:i}){this.hitTest(i.room)&&this.stopDurationItem(`${i.userId}_${i.streamType}`,i.kind)}isRecording(i){return i.findIndex(e=>e.endTime===0)>=0}addDuractionItem(i,e,t){let r=`${i}_${t}`,o=new cc,n=this._durationMap.get(r);n?this.isRecording(n[e])||n[e].push(o):this._durationMap.set(r,{userId:i,type:t,audio:e===m.AUDIO?[o]:[],video:e===m.AUDIO?[]:[o]})}stopDurationItem(i,e){if(this._durationMap.has(i)){let r=this._durationMap.get(i)[e].find(o=>o.endTime===0);r&&r.stop()}}hitTest(i){return this._room===i}getDuration(i,e){return this._durationMap.has(i)?this._durationMap.get(i)[e].reduce((r,o)=>r+o.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},pp=gu;var Tu=class{constructor(i){c(this,"_room");c(this,"_renderFreezeMap",new Map);c(this,"_isVideoPlayingEventFiredMap",new Map);c(this,"_dataFreezeMap",new Map);c(this,"_monitorFreezeData",new Map);c(this,"_eventMap",new Map);this._room=i.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(E.LEAVE_SUCCESS,({room:i})=>{this.hitTest(i)&&this.stop()}).set(E.PLAY_TRACK_START,this.onPlayTrackStart).set(E.UNSUBSCRIBE_SUCCESS,({room:i,streamType:e,remotePublishedUser:t})=>{if(!this.hitTest(i))return;let{userId:r}=t,o=`${r}_${e}`;this.stopDataFreeze({key:o,userId:r,type:e})}).set(E.REMOTE_PUBLISH_STATE_CHANGED,({room:i,prevMuteState:e,muteState:t})=>{if(!this.hitTest(i))return;let{userId:r}=t;if(e.hasVideo&&!t.hasVideo){let o="main",n=`${t.userId}_${o}`;this.stopDataFreeze({key:n,userId:r,type:o})}if(e.hasAuxiliary&&!t.hasAuxiliary){let o="auxiliary",n=`${t.userId}_${o}`;this.stopDataFreeze({key:n,userId:r,type:o})}}).set(E.PLAYER_STATE_CHANGED,({track:i,state:e,reason:t,type:r})=>{if(!(!i.isRemote||!i.room||!this.hitTest(i.room)||r!==m.VIDEO)){if(e==="PLAYING"){let o=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.set(o,!0)}t===m.MUTE?this.onVideoTrackMuted(i):t===m.UNMUTE&&this.onVideoTrackUnmuted(i)}}).set(E.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((i,e)=>S.on(e,i,this))}uninstallEvents(){this._eventMap.forEach((i,e)=>S.off(e,i,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,r=`${e}_${t}`,o=this._dataFreezeMap.get(r),n=new cc;o?o.durationItemList.push(n):this._dataFreezeMap.set(r,{userId:e,type:t,durationItemList:[n],isFreezing(){let a=this.durationItemList[this.durationItemList.length-1];return a&&a.endTime===0}})}onVideoTrackUnmuted(i){if(!i.isSubscribed)return;let{userId:e,streamType:t}=i,r=`${e}_${t}`;this.stopDataFreeze({key:r,userId:e,type:t})}onHearBeatReport({room:i,report:e}){this.hitTest(i)&&e.msg_down_stream_info.forEach(t=>{let r=this._room.remotePublishedUserMap.get(t.msg_user_info.str_identifier);if(!r)return;let{userId:o,muteState:n}=r;t.msg_video_status.forEach(a=>{a.uint32_video_stream_type===2&&n.hasVideo&&!n.videoMuted&&r.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:o,fps:a.uint32_video_dec_fps,type:"main"}),a.uint32_video_stream_type===7&&n.hasAuxiliary&&r.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:o,fps:a.uint32_video_dec_fps,type:"auxiliary"})})})}stopDataFreeze({key:i,userId:e,type:t}){let r=this._dataFreezeMap.get(i);if(!r||!r.isFreezing())return;let o=r.durationItemList[r.durationItemList.length-1];o.stop();let n=o.getDuration();n>Tn?this._monitorFreezeData.set(i,{userId:e,type:t,duration:n}):r.durationItemList.pop()}getTotalDuration(i){return i.reduce((e,t)=>{let r=t.getDuration();return e+Math.min(r,5e3)},0)}handleRenderFreeze(r){return p(this,arguments,function*({userId:i,fps:e,type:t}){let o=`${i}_${t}`,n=this._renderFreezeMap.get(o);if(e<=2){let a=P();n&&!n.isFreeze&&(n.freezeTimeline.push({startTime:a,endTime:0}),n.isFreeze=!0),n||this._renderFreezeMap.set(o,{userId:i,type:t,isFreeze:!0,freezeTimeline:[{startTime:a,endTime:0}],renderFreezeTotal:0})}else if(n&&n.isFreeze){n.isFreeze=!1;let a=n.freezeTimeline.pop();if(a){a.endTime=P();let d=a.endTime-a.startTime;n.freezeTimeline.push(a),n.renderFreezeTotal+=Math.min(5e3,d)}}})}onPlayTrackStart({track:i}){if(!i.isRemote||!this.hitTest(i.room)||i.kind!==m.VIDEO||!i.isRemotePublished)return;let e=`${i.userId}_${i.streamType}`;this._isVideoPlayingEventFiredMap.has(e)||this._isVideoPlayingEventFiredMap.set(e,!1)}getDataFreezeDuration(i){let e={dataFreeze:0,count:0},t=this._dataFreezeMap.get(i);if(t){if(t.isFreezing()){let r=t.durationItemList[t.durationItemList.length-1];r.stop(),r.getDuration()<Tn&&t.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(t.durationItemList),e.count=t.durationItemList.length}return e}getRenderFreezeDuration(i){let e=this._renderFreezeMap.get(i),t=0,r=0;if(e)if(!e.isFreeze)t=e.renderFreezeTotal;else{let o=P(),n=e.freezeTimeline[e.freezeTimeline.length-1],a=o-n.startTime;t=e.renderFreezeTotal+Math.min(a,5e3),r=e.freezeTimeline.length}return{renderFreeze:t,count:r}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(i){return this._isVideoPlayingEventFiredMap.has(i)?!this._isVideoPlayingEventFiredMap.get(i):!1}resetMonitor(){this._monitorFreezeData.clear()}hitTest(i){return i===this._room}destroy(){this.uninstallEvents()}},fp=Tu;var gp=Be(ze(),1);var VT=[1,0,0,0,1,1,0,1],dc=class extends et{constructor(i,e){if(super(i,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror",logger:e}),i instanceof De)try{this.setTexBuffer(VT)}catch(t){i.destroy(new b({code:I.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${t.message||t}`}))}}draw2d(i,e,t,r,o){if(this.ctx2d){this.ctx2d.save(),this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0);let n=super.draw2d(i,e,t,r,o);return this.ctx2d.restore(),n}return!1}render(i){var e;return(e=this.input)!=null&&e.requestFrame(i)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}};var Eu=class{constructor(i,e){this.node=i;this.layout=e;c(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}},lc=class extends et{constructor(e,t){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t});c(this,"inputs",[])}addInput(e,t){if(this.inputs[t.zIndex])throw new Error("input already exists");let r=new Eu(e,t);this.inputs[t.zIndex]=r}resize(e,t){let r=this.inputs.reduce((o,n)=>n?Object.assign(o,{width:Math.max(o.width,n.right),height:Math.max(o.height,n.bottom)}):o,{width:0,height:0});super.resize(r.width,r.height),this.context instanceof De&&this.inputs.forEach(o=>{if(o){let n=this.layout2texCoords(o);o.positionBuffer?this.changeBufferData(o.positionBuffer,n):o.positionBuffer=this.createBuffer(n)}})}connect(e,...t){return super.connect(e,...t),this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex(t=>(t==null?void 0:t.node)===e)]=void 0}render(e){let t=this.context.ctx;if(t.clearColor(0,0,0,0),!this.inputs.reduce((o,n)=>(!n||!n.node.requestFrame(e))&&o,!0)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let o=0;o<this.inputs.length;o++){let n=this.inputs[o];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){if(!this.inputs.reduce((r,o)=>(!o||!o.node.requestFrame(e))&&r,!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let r=0;r<this.inputs.length;r++){let o=this.inputs[r];o&&this.draw2d(o.node.image,o.x,o.y,o.width,o.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:t,y:r,width:o,height:n,name:a}=this,d=Date.now(),l=(e-this.lastInfo.totalFrames)/((d-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:t,y:r,width:o,height:n,timestamp:d,fps:l,name:a},v({parent:this.inputs.filter(u=>u).map(u=>u.node.getInfo())},this.lastInfo)}close(){super.close(),this.inputs.forEach(e=>{var t,r;if(e&&((t=e.node)==null||t.disconnect(),e.positionBuffer&&this.context instanceof De))try{(r=this.context.ctx)==null||r.deleteBuffer(e.positionBuffer)}catch(o){}})}};var BT=`#version 300 es
|
|
101
|
+
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(i=>{lg[`${i}()`]={tips:`Call trtc.${i}`,color:"blue",class:"blue",textColor:"#fff"}});var fx=Object.keys(lg);var rS=0,eu,tn=class tn{constructor(t){this.core=t;u(this,"_core");u(this,"log");u(this,"dumpLocalVideoMap",{});u(this,"dumpRemoteVideoMap",{});u(this,"dialog");this._core=t,this.log=t.log.createChild({id:`${this.getAlias()}${++rS}`}),this.log.info("created")}getName(){return tn.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(t){switch(t){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return A(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 A(this,null,function*(){var t;try{if(eu)yield eu;else{let e=Date.now(),r=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((t=window.sessionStorage)==null?void 0:t.getItem("TRTC_DEBUG_DIALOG_PATH"))||`https://unpkg.com/${cg}@${st}/assets/debug-dialog.js`;eu=this.loadScript(r),yield eu,this.log.info(`download debug dialog script cost: ${Date.now()-e}ms`)}this.dialog=new TRTCDebugDialog(this._core,this.log,this.dumpLocalVideoMap,this.dumpRemoteVideoMap),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(e){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(e))}})}closeDebugDiaLog(){var t;(t=this.dialog)==null||t.closeDialog(),this.dialog=null}addVideoProcessor(){this._core.room.videoManager.addEncodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.encodeVideo.bind(this):cp,type:1}),this._core.room.videoManager.addDecodeProcessor({processor:this._core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED?this.decodeVideo.bind(this):dp,type:1})}removeVideoProcessor(){this._core.room.videoManager.removeEncodeProcessor({type:1}),this._core.room.videoManager.removeDecodeProcessor({type:1})}encodeVideo({frame:t,mediaType:e}){return cp({frame:t,onDump:()=>{if(!e)return;let r=e===2?"sub":"main",o=this.dumpLocalVideoMap[r];o&&(o.data.push(t.data.slice(0)),o.duration>0&&Date.now()-o.startTimestamp>o.duration*1e3&&o.onDumpEnd())}})}decodeVideo({frame:t,track:e}){return dp({frame:t,onDump:()=>{if(!e)return;let r=this.dumpRemoteVideoMap[`${e.userId}-${e.streamType}`];r&&(r.data.push(t.data.slice(0)),r.duration>0&&Date.now()-r.startTimestamp>r.duration*1e3&&r.onDumpEnd())}})}loadScript(t){return new Promise((e,r)=>{this.log.info(`loading debug dialog from ${t}`);let o=document.createElement("script");o.type="text/javascript",o.onload=e,o.onerror=r,o.crossOrigin="anonymous",o.src=t,document.head.append?document.head.append(o):document.getElementsByTagName("head")[0].appendChild(o)})}};u(tn,"Name","Debug"),u(tn,"autoStart",!0),J([Ji({settings:{timeout:3e3,retries:3},onError(t,e,r){var o;(o=t==null?void 0:t.message)!=null&&o.includes("timeout")?e():r(t)}})],tn.prototype,"loadScript",1);var tu=tn;var mg=i=>{switch(i){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},ru=class{constructor(t,e,r){u(this,"trackDoneOB");u(this,"startOB");u(this,"stopOB");u(this,"inputFrameCount",0);u(this,"decodedFrameCount",0);u(this,"type","auto");u(this,"config");u(this,"decoder");u(this,"_decodeSink");let{kvStatManager:o,trtc:s}=t;this.config=r.config,this.trackDoneOB=Ce(e,oe.INIT),this.stopOB=It(),this.startOB=It(),r.type==="auto"?this.type="webCodecs":this.type=r.type;let n=It(),d=m=>{let l=this.pipe(e);return n.next("STARTING"),e.log.info(`decoder type: ${this.type}`),ye(l,Xe(this.stopOB),ke(()=>{},g=>{e.log.error(g),o.addFailedEvent({key:mg(this.type),error:g}),m>4?this.startOB.error(g):this.startOB.next(m+1)})),ye(l,Rr(1),Vm(Ta))};ye(this.startOB,Ea(0),eo(d),Xe(this.stopOB),ke(()=>{e.player.setOutput(),n.next("STARTED")},m=>{n.next("FAILED")},()=>{o.addSuccessEvent({key:mg(this.type)}),o.addSuccessEvent({key:504702})}))}mock(t){this._decodeSink?this._decodeSink.error(t):this.startOB.next(0)}close(t){this.stopOB.next(t)}pipe(t){return fi()(e=>A(this,null,function*(){this._decodeSink=e,e.defer(()=>{var o;(o=this.decoder)==null||o.close()});let{type:r}=this;try{switch(r){case"webCodecs":this.decoder=new AudioDecoder({error:o=>{t.log.error(o),e.error(4)},output:o=>{this.decodedFrameCount++,e.next(o),t.player.write(o)}});break;case"wasm":break}this.decoder.configure(this.config)}catch(o){t.log.error(o),e.error(r==="webCodecs"?2:6)}}))}decodeFrame(t){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:t.data,timestamp:t.timestamp,type:"key"}))}},iS={type:"object"},Na=class Na{constructor(t){this.core=t;u(this,"log");u(this,"contextMap",new Map);u(this,"decodeProcessorMap",new WeakMap);this.log=t.log.createChild({id:`${this.getAlias()}`})}getAlias(){return Na.Name}getGroup(t){return t.track.userId+t.track.streamType}getName(){return Na.Name}getValidateRule(t){return iS}start(t){let{track:e}=t;this.decodeProcessorMap.set(e,this.decode(t)),this.core.room.audioManager.addDecodeProcessor({processor:({frame:r,track:o})=>this.decodeProcessorMap.has(o)?this.decodeProcessorMap.get(o)({frame:r,track:o}):r,type:3})}decode(t){return({frame:e,track:r})=>{if(r!==t.track)return e;if(this.contextMap.has(r))return this.contextMap.get(r).decodeFrame(e);let o=new ru(this.core,r,t);return ye(o.trackDoneOB,Rr(1),ke(()=>{this.core.clearStarted(this,this.getGroup(t)),this.stop({track:r})})),this.contextMap.set(r,o),o.decodeFrame(e)}}stop({track:t}){let e=this.contextMap.get(t);e&&(e.close("stop"),this.contextMap.delete(t),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(t){let e=this.contextMap.get(t.track);if(e){if(t.type==="mock"){e.mock(10);return}e.close("update"),this.contextMap.set(t.track,new ru(this.core,t.track,t))}}};u(Na,"Name","TRTCAudioDecoder");var wa=Na;var iu=class{constructor(){u(this,"log");this.log=F.createLogger({id:"exp"})}call(t,e){return A(this,null,function*(){return He(this[t])?this[t](e):Promise.reject(new ae({code:q.INVALID_PARAMETER,message:$e({key:Fe.API_NOT_EXIST,data:{name:t}})}))})}enableAudioFrameEvent(t){return A(this,null,function*(){let{trtcInstance:e,enable:r,userId:o,sampleRate:s=48e3,channelCount:n=1,port:d}=t,{audioManager:m}=e.room,{getPCMAbortCtrlMap:l,audioFrameEventConfigMap:g}=m;if(g.set(o,{enable:r,sampleRate:s,channelCount:n}),r)if(o==="*")e.room.remotePublishedUserMap.forEach(_=>{if(_.remoteAudioTrack.isAvailable){if(l.get(_.userId))return;let S=m.getPCM(v=>{e.emit(K.AUDIO_FRAME,v)},_.userId);l.set(_.userId,S)}});else{if(l.get(o))return;let _=m.getPCM(S=>{e.emit(K.AUDIO_FRAME,S)},o);l.set(o,_)}else if(o==="*")e.room.remotePublishedUserMap.forEach(_=>{if(_.remoteAudioTrack.isSubscribed){let{userId:S}=_,v=l.get(S);v==null||v.abort("disable"),l.delete(S)}});else{let _=l.get(o);_==null||_.abort("disable"),l.delete(o)}})}};J([Pf({name:"options",type:"object",required:!0,properties:{enable:{required:!0,type:"boolean"},userId:{required:!0,type:"string"},sampleRate:{type:"number",values:[8e3,16e3,32e3,44100,48e3]},channelCount:{type:"number",values:[1,2]},port:{type:"messageport"}}})],iu.prototype,"enableAudioFrameEvent",1);var pg=new iu;var hg=0,Ma=new Set,vt=null;ku(dg);Ls.checkStorage();Vl();var oS={RtcError:de,ErrorCode:pe,ErrorCodeDictionary:Cr},_e=class _e extends fg.EventEmitter{constructor(e,r){super();u(this,"_room");u(this,"_eventListened",new Set);u(this,"_localVideoTrack",null);u(this,"_localAudioTrack",null);u(this,"_localScreenTrack",null);u(this,"_localScreenAudioTrack",null);u(this,"_localVideoConfig",null);u(this,"_localScreenConfig",null);u(this,"_localAudioConfig",null);u(this,"_remoteVideoConfigMap",new Map);u(this,"_remoteAudioConfigMap",new Map);u(this,"_remoteAudioVolumeMap",new Map);u(this,"_remoteAudioMuteMap",new Map);u(this,"_mediaTrackMap",new WeakMap);u(this,"_log",F.createLogger({id:`t${++hg}`}));u(this,"_plugins",new Map);u(this,"_networkQuality",null);u(this,"_speakerId");this._room=new e(Z({logger:this._log,frameWorkType:_e.frameWorkType},r)),this._room.videoDecodeFallbackType=r.videoDecodeFallback,this._log.info(`create() ${JSON.stringify(r,(o,s)=>o==="plugins"?s.map(n=>n.Name):s)}`),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(o){return this._room.audioManager.dump(o)}}}),r.plugins&&r.plugins.forEach(o=>{this._use(o,r.assetsPath)}),this._use(Qd,r.assetsPath),this._use(Zd,r.assetsPath),this._use(wa,r.assetsPath||sc),this._use(tu),r.enableSEI&&oa&&this._use(Kd),this._room.on("audio-volume",o=>{!o.find(s=>s.userId==="")&&this._localAudioTrack&&o.push({userId:"",volume:Math.floor(this._localAudioTrack.getAudioLevel()*100)}),r.volumeType===1&&o.forEach(s=>{var d;let n=s.userId===""?this._localAudioTrack:(d=this.room.remotePublishedUserMap.get(s.userId))==null?void 0:d.remoteAudioTrack;n&&(s.volume=n.dbVolume)}),this.emit(K.AUDIO_VOLUME,{result:o.sort((s,n)=>n.volume-s.volume)})}),this._room.videoManager.on("error",o=>{this._log.error(new de({code:pe.OPERATION_FAILED,extraCode:5504,message:o.message,originError:o}))}),this._listenEvents(),this._initActiveSpeaker(),og(this,"trtc")}static create(e){}static _create(e,r){Gf();let o=new _e(e,r||{});return Ma.add(o),o}get room(){return this._room}_listenEvents(){Lt(this,this._room).add("peer-join",e=>{let{userId:r}=e;this.emit(K.REMOTE_USER_ENTER,{userId:r})}).add("peer-leave",e=>{this.emit(K.REMOTE_USER_EXIT,{userId:e}),this._remoteAudioVolumeMap.delete(e)}).add("banned",e=>{this._exitRoom().finally(()=>{this.emit(K.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(K.ERROR,de.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(K.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let r=Ee(Z({},e),{uplinkRTT:Math.min(e.uplinkRTT,An),downlinkRTT:Math.min(e.downlinkRTT,An)});this.emit(K.NETWORK_QUALITY,r)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{Lt(o,o).add("player-state-changed",s=>{let n=Ee(Z({},s),{userId:e.userId});o.kind===N.VIDEO&&(n.streamType=no(o.streamType)),this.emit(o.kind===N.AUDIO?K.AUDIO_PLAY_STATE_CHANGED:K.VIDEO_PLAY_STATE_CHANGED,n)}).add("error",s=>{s.getCode()===q.PLAY_NOT_ALLOWED&&this.emit(K.AUTOPLAY_FAILED,{userId:o.userId,resume:()=>o.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{pt(o)})}).add("remote-publish-state-changed",({prevMuteState:e,muteState:r})=>{let{userId:o}=r,s=e.audioAvailable,n=e.videoAvailable,{audioAvailable:d,videoAvailable:m}=r;d||this._remoteAudioConfigMap.delete(o),m||this._removeRemoteVideoConfig(o,"main"),r.hasAuxiliary||this._removeRemoteVideoConfig(o,"sub"),n!==m&&(m?this._onVideoAvailable({userId:o,streamType:"main"}):this._onVideoUnavailable({userId:o,streamType:"main"}),this.emit(m?K.REMOTE_VIDEO_AVAILABLE:K.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"main"})),s!==d&&(d?this._onAudioAvailable({userId:o}):this._onAudioUnavailable({userId:o,muteState:r}),this.emit(d?K.REMOTE_AUDIO_AVAILABLE:K.REMOTE_AUDIO_UNAVAILABLE,{userId:o})),e.hasAuxiliary!==r.hasAuxiliary&&(r.hasAuxiliary?this._onVideoAvailable({userId:o,streamType:"sub"}):this._onVideoUnavailable({userId:o,streamType:"sub"}),this.emit(r.hasAuxiliary?K.REMOTE_VIDEO_AVAILABLE:K.REMOTE_VIDEO_UNAVAILABLE,{userId:o,streamType:"sub"}))}).add("sei-message",e=>{this.emit(K.SEI_MESSAGE,Ee(Z({},e),{streamType:no(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(K.ERROR,new de({code:pe.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var s,n,d,m,l,g,_;let r={2:"big",3:"small",7:"sub"},o={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((s=e.msg_down_stream_info[0])==null?void 0:s.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((d=this._networkQuality)==null?void 0:d.downlinkRTT)||0,An),upLoss:((m=this._networkQuality)==null?void 0:m.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:(((g=e.msg_up_stream_info.msg_audio_status)==null?void 0:g.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((_=e.msg_up_stream_info.msg_audio_status)==null?void 0:_.uint32_audio_level)||0)/ci},video:e.msg_up_stream_info.msg_video_status.filter(S=>r[S.uint32_video_stream_type]).map(S=>({bitrate:(S.uint32_video_codec_bitrate||0)/1e3,width:S.uint32_video_width,height:S.uint32_video_height,frameRate:S.uint32_video_enc_fps,videoType:r[S.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(S=>({userId:S.msg_user_info.str_identifier,audio:{bitrate:(S.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(S.msg_audio_status.uint32_audio_level||0)/ci,point2pointDelay:(S.msg_audio_status.uint32_audio_p2p_delay||0)+(S.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:S.msg_audio_status.uint32_audio_cache_ms||0},video:S.msg_video_status.map(v=>({bitrate:(v.uint32_video_codec_bitrate||0)/1e3,width:v.uint32_video_width,height:v.uint32_video_height,frameRate:v.uint32_video_dec_fps,videoType:r[v.uint32_video_stream_type],point2pointDelay:(v.uint32_video_p2p_delay||0)+(v.uint32_video_cache_ms||0),jitterBufferDelay:v.uint32_video_cache_ms||0}))}))};this.emit(K.STATISTICS,o)}).add("custom-message",e=>{this.emit(K.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(K.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(K.FIRST_VIDEO_FRAME,Ee(Z({},e),{streamType:no(e.streamType)}))}).add("audio-frame",e=>{this.emit(K.AUDIO_FRAME,e)}),Lt(this,Tt).add("audioInputAdded",e=>{this.emit(K.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(K.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(K.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(K.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>A(this,null,function*(){if(this.emit(K.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),vt&&vt.deviceId===yn){let r=(yield Xi()).find(o=>o.deviceId===yn);r&&vt.groupId!==r.groupId&&(vt=r,this.emit(K.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}})).add("audioOutputRemoved",e=>A(this,null,function*(){this.emit(K.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let r=(yield Xi())[0];if(!r||!vt||vt.groupId===r.groupId)return;let o=vt.deviceId===e.deviceId,s=vt.deviceId===yn&&vt.deviceId===r.deviceId;(o||s)&&(vt=r,this.emit(K.DEVICE_CHANGED,{type:"speaker",action:"active",device:r}))}))}use(e){let r,o;"plugin"in e?(r=e.plugin,o=e.assetsPath):r=e,this._use(r,o||sc)}_use(e,r){if(this._plugins.get(e.Name)){this._log.warn("duplicate install plugin",e.Name);return}let s=new e(ig.call(this,{TRTC:_e,room:this._room,errorModule:oS,assetsPath:r}));this._plugins.set(e.Name,s),e.autoStart&&this.startPlugin(e.Name)}enterRoom(e){return A(this,null,function*(){var m,l;let{scene:r="rtc",enableAutoPlayDialog:o=!0,autoReceiveAudio:s=!0,autoReceiveVideo:n=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!ve(e.proxy)&&e.proxy.turnServer&&((l=(m=this._room).setTurnServer)==null||l.call(m,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=o,this._room.autoReceiveAudio=s,this._room.autoReceiveVideo=n,dt(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let d={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,keepAlive:e.keepAlive};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(d,r,_e.frameWorkType),this._checkTrackToPublish(),op.start()})}exitRoom(){return A(this,null,function*(){return yield this._exitRoom()})}switchRole(e,r){return A(this,null,function*(){r!=null&&r.privateMapKey&&(this._room.privateMapKey=r.privateMapKey),r!=null&&r.latencyLevel&&(this._room.latencyLevel=r.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){pt(this),this.removeAllListeners(),this._room.destroy(),Ma.delete(this),Ma.size===0&&op.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),this._plugins.forEach(e=>{var r;return(r=e.destroy)==null?void 0:r.call(e)}),this._plugins.clear(),L.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return A(this,arguments,function*(e={publish:!0}){if(this._localAudioTrack){this._log.warn("local audio is already started");return}let{publish:r=!0,mute:o,option:s}=e,n=new hi(this._room.audioManager),d={},m={muted:!0};s&&(V(s.microphoneId)?V(s.audioTrack)||(d.customSource=s.audioTrack):d.deviceId=s.microphoneId,s&&We(s.captureVolume)&&n.setCaptureVolume(s.captureVolume),V(s.profile)||(ve(s.profile)?ac[s.profile]&&n.setProfile(ac[s.profile]):n.setProfile(s.profile)),We(s.earMonitorVolume)&&(m.muted=!(s.earMonitorVolume>0),m.volume=s.earMonitorVolume),V(s.echoCancellation)||(n.profile.echoCancellation=s.echoCancellation),V(s.noiseSuppression)||(n.profile.noiseSuppression=s.noiseSuppression),V(s.autoGainControl)||(n.profile.autoGainControl=s.autoGainControl)),n.on("5",l=>{this.emit(K.ERROR,new de({code:pe.DEVICE_ERROR,extraCode:5309,messageParams:{error:l}}))}),n.on("2",l=>{this.emit(K.DEVICE_CHANGED,{type:"microphone",action:"active",device:l})}),n.on("4",l=>{let g;l.error&&(g=de.convertFrom(l.error)),this.emit(K.PUBLISH_STATE_CHANGED,Ee(Z({},l),{error:g}))}),this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId),yield n.capture(d),V(o)||n.setMute(o),Lt(n,n).add("player-state-changed",l=>{this.emit(K.AUDIO_PLAY_STATE_CHANGED,Ee(Z({},l),{userId:""}))}),r&&this._room.isJoined&&this._room.publish(n).catch(()=>{}),this._localAudioTrack=n,this._localAudioConfig=Ee(Z({},e),{publish:r}),yield this._updateAudioPlayOption({playOption:m,track:n}),L.emit("113",{userId:"",room:this.room})})}updateLocalAudio(e){return A(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:r,mute:o,option:s}=e,n={};s&&(s.microphoneId?yield this._localAudioTrack.switchDevice(s.microphoneId):V(s.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(s.audioTrack)),V(s.captureVolume)||this._localAudioTrack.setCaptureVolume(s.captureVolume),V(s.earMonitorVolume)||(n.muted=!(s.earMonitorVolume>0),n.volume=s.earMonitorVolume),yield this._localAudioTrack.update3A(s)),this._room.isJoined&&!V(r)&&(r&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!r&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),V(o)||this._localAudioTrack.setMute(o),yield this._updateAudioPlayOption({playOption:n,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Lr(this._localAudioConfig,e)})}stopLocalAudio(){return A(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),L.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),pt(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null)})}startLocalVideo(){return A(this,arguments,function*(e={publish:!0,view:null}){if(this._localVideoTrack){this._log.warn("local video is already started");return}let{view:r,publish:o=!0,mute:s,option:n}=e,d=new br(this._room.videoManager),m={},l={};dt(n==null?void 0:n.avoidCropping)&&(d.avoidCropping=n.avoidCropping),n&&(n.cameraId?m.deviceId=n.cameraId:V(n.useFrontCamera)?V(n.videoTrack)||(m.customSource=n.videoTrack):m.facingMode=n.useFrontCamera?N.FACING_MODE_USER:N.FACING_MODE_ENVIRONMENT,n.qosPreference&&(m.contentHint=Ca(n.qosPreference)),V(n.profile)||(ve(n.profile)?xr[n.profile]&&d.setProfile(xr[n.profile]):d.setProfile(n.profile)),V(n.fillMode)||(l.objectFit=n.fillMode),V(n.mirror)||(l.mirror=n.mirror),V(n.small)||(ta()?ve(n.small)?d.small=xr[n.small]:n.small===!0?d.small=xr["120p"]:d.small=n.small:this._log.warn("small stream is not supported"))),d.once("first-video-frame",g=>{this.emit(K.FIRST_VIDEO_FRAME,Ee(Z({},g),{streamType:no(g.streamType)}))}),d.on("5",g=>{this.emit(K.ERROR,new de({code:pe.DEVICE_ERROR,extraCode:5308,messageParams:{error:g}}))}),d.on("2",g=>{this.emit(K.DEVICE_CHANGED,{type:"camera",action:"active",device:g})}),d.on("4",g=>{let _;g.error&&(_=de.convertFrom(g.error)),this.emit(K.PUBLISH_STATE_CHANGED,Ee(Z({},g),{error:_}))}),this._listenOutputTrackChanged(d),yield d.capture(m),V(s)||(yield d.setMute(s)),Lt(d,d).add("player-state-changed",g=>{this.emit(K.VIDEO_PLAY_STATE_CHANGED,Ee(Z({},g),{userId:"",streamType:"main"}))}),o&&this._room.isJoined&&this._room.publish(d).catch(()=>{}),this._localVideoTrack=d,this._localVideoConfig=Ee(Z({},e),{view:r,publish:o}),yield this._updateVideoPlayOption({view:r,playOption:l,track:d})})}updateLocalVideo(e){return A(this,null,function*(){if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:r,publish:o,mute:s,option:n}=e,d={};if(n)if(V(n.profile)||(ve(n.profile)?xr[n.profile]&&this._localVideoTrack.setProfile(xr[n.profile]):this._localVideoTrack.setProfile(n.profile),(!n.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(n.cameraId))&&V(n.useFrontCamera)&&this._localVideoTrack.applyProfile()),n.cameraId?yield this._localVideoTrack.switchDevice(n.cameraId):V(n.useFrontCamera)?V(n.videoTrack)||(yield this._localVideoTrack.setInputMediaStreamTrack(n.videoTrack)):yield this._localVideoTrack.switchDevice(n.useFrontCamera?N.FACING_MODE_USER:N.FACING_MODE_ENVIRONMENT),V(n.fillMode)||(d.objectFit=n.fillMode),V(n.mirror)||(d.mirror=n.mirror),n.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(Ca(n.qosPreference)),n.small){let m=!this._localVideoTrack.small;ta()?(n.small===!0?this._localVideoTrack.small=xr["120p"]:ve(n.small)?this._localVideoTrack.small=xr[n.small]:this._localVideoTrack.small=n.small,this._room.videoManager.update(),m&&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&&!V(o)&&(o&&!this._localVideoConfig.publish&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._localVideoConfig.publish&&!o&&this._room.unpublish(this._localVideoTrack).catch(()=>{})),V(s)||(yield this._localVideoTrack.setMute(s)),yield this._updateVideoPlayOption({view:r,playOption:d,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Lr(this._localVideoConfig,e)})}stopLocalVideo(){return A(this,null,function*(){this._localVideoTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),pt(this._localVideoTrack),this._localVideoTrack=null,this._localVideoConfig=null)})}startScreenShare(){return A(this,arguments,function*(e={publish:!0,view:null}){if(this._localScreenTrack){this._log.warn("screen share is already started");return}let{view:r=null,publish:o=!0,option:s}=e,n=new Yi(this._room.videoManager);n.on("4",_=>{let S;_.error&&(S=de.convertFrom(_.error)),this.emit(K.PUBLISH_STATE_CHANGED,Ee(Z({},_),{error:S}))}),n.once("first-video-frame",_=>{this.emit(K.FIRST_VIDEO_FRAME,Ee(Z({},_),{streamType:no(_.streamType)}))}),this._listenOutputTrackChanged(n),e.streamType==="main"&&(n.mediaType=4);let d=null,m={},l={};s&&(V(s.profile)||(ve(s.profile)?cc[s.profile]&&n.setProfile(cc[s.profile]):n.setProfile(s.profile)),s.systemAudio&&(m.systemAudio=!0,m.echoCancellation=s.echoCancellation,m.noiseSuppression=s.noiseSuppression,m.autoGainControl=s.autoGainControl),V(s.fillMode)||(l.objectFit=s.fillMode),s.videoTrack&&(m.videoTrack=s.videoTrack),s.audioTrack&&(m.audioTrack=s.audioTrack),s.captureElement&&(m.captureElement=s.captureElement),s.preferDisplaySurface&&(m.preferDisplaySurface=s.preferDisplaySurface),s.qosPreference&&(m.contentHint=Ca(s.qosPreference)));let g=yield n.capture(m);if(n.mediaTrack.addEventListener(N.ENDED,()=>{this._stopScreenShare(),this.emit(K.SCREEN_SHARE_STOPPED)}),g.getAudioTracks()[0]&&(d=new jo(this._room.audioManager),yield d.setInputMediaStreamTrack(g.getAudioTracks()[0]),this._speakerId&&d.setAudioOutput(this._speakerId)),Lt(n,n).add("player-state-changed",_=>{this.emit(K.VIDEO_PLAY_STATE_CHANGED,Ee(Z({},_),{userId:"",streamType:"sub"}))}),o&&this._room.isJoined){let _=[n];d&&_.push(d),this._room.publish(..._).catch(()=>{})}this._localScreenTrack=n,this._localScreenAudioTrack=d,this._localScreenConfig=Ee(Z({},e),{view:r,publish:o}),yield this._updateVideoPlayOption({view:r,playOption:l,track:n})})}updateScreenShare(e){return A(this,null,function*(){if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:r,publish:o,option:s}=e,n={};if(s&&(V(s.fillMode)||(n.objectFit=s.fillMode),s.qosPreference)){let d=Ca(s.qosPreference);this._localScreenTrack.setContentHint(d)}this._room.isJoined&&!V(o)&&(o&&!this._localScreenConfig.publish&&(this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})),this._localScreenConfig.publish&&!o&&(this._room.unpublish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.unpublish(this._localScreenAudioTrack).catch(()=>{}))),yield this._updateVideoPlayOption({view:r,playOption:n,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),Lr(this._localScreenConfig,e)})}stopScreenShare(){return A(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return A(this,null,function*(){let{view:r,userId:o,streamType:s,option:n}=e,d=`${o}_${s}`;if(this._remoteVideoConfigMap.has(d)){this._log.warn(`remote video has already started. userId:${o}, streamType:${s}`);return}let m=this._room.remotePublishedUserMap.get(o);if(!m)return;let l={},g=s==="main"?m.remoteVideoTrack:m.remoteAuxiliaryTrack;this._listenOutputTrackChanged(g),n&&(V(n.fillMode)||(l.objectFit=n.fillMode),V(n.mirror)||(l.mirror=n.mirror),V(n.poster)||(l.poster=n.poster),l.canvasRender=n.canvasRender,s==="main"&&!V(n.small)&&(!m.remoteVideoTrack.isSubscribing&&!m.remoteVideoTrack.isSubscribed&&m.remoteVideoTrack.setMediaType(n.small?8:4),this._room.changeType(n.small,g.user))),yield this._room.subscribe(g),yield this._enableVideoDecodeFallback(g,s),yield this._updateVideoPlayOption({view:r,playOption:l,track:g}),this._emitTrackEvent(g),this._remoteVideoConfigMap.set(d,{config:e}),n&&!V(n.receiveWhenViewVisible)&&this._observeView({remoteTrack:g,view:r,receiveWhenViewVisible:n.receiveWhenViewVisible,viewRoot:n==null?void 0:n.viewRoot})})}updateRemoteVideo(e){return A(this,null,function*(){var M,G;let{view:r,userId:o,streamType:s,option:n}=e,d=`${o}_${s}`,m=this._remoteVideoConfigMap.get(d);if(!m||!this._room.remotePublishedUserMap.has(o))return;let l={};n&&(V(n.fillMode)||(l.objectFit=n.fillMode),V(n.mirror)||(l.mirror=n.mirror));let g=null,_=this._room.remotePublishedUserMap.get(o);if(s==="main"&&(_!=null&&_.muteState.hasVideo)&&(g=_.remoteVideoTrack),s==="sub"&&(_!=null&&_.muteState.hasAuxiliary)&&(g=_.remoteAuxiliaryTrack),!g)return;let{config:S}=m;s==="main"&&n&&!V(n.small)&&this._room.changeType(n.small,g.user),yield this._updateVideoPlayOption({view:r,playOption:l,track:g,prevConfig:S}),Lr(S,e);let v=V(n==null?void 0:n.receiveWhenViewVisible)?(M=S.option)==null?void 0:M.receiveWhenViewVisible:n.receiveWhenViewVisible,x=V(r)?S.view:r,P=V(n==null?void 0:n.viewRoot)?(G=S.option)==null?void 0:G.viewRoot:n.viewRoot;this._observeView({remoteTrack:g,view:x,receiveWhenViewVisible:v,viewRoot:P})})}stopRemoteVideo(e){return A(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e,r=!0){return A(this,null,function*(){let o=[],s=this._room.remotePublishedUserMap.get(e.userId);if(s){let{muteState:n,remoteVideoTrack:d,remoteAuxiliaryTrack:m}=s;e.streamType==="main"&&(d.stop(),n.hasVideo&&o.push(d)),e.streamType==="sub"&&(m.stop(),n.hasAuxiliary&&o.push(m))}for(let n of o)r&&(yield this._room.unsubscribe(n),this._mediaTrackMap.delete(n.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)})}_removeRemoteVideoConfig(e,r){let o=`${e}_${r}`,s=this._remoteVideoConfigMap.get(o);s&&s.observer&&s.observer.disconnect(),this._remoteVideoConfigMap.delete(o)}muteRemoteAudio(e,r){return A(this,null,function*(){this._remoteAudioMuteMap.set(e,r);try{if(e==="*")if(r)yield this._stopRemoteAudio({userId:e});else{let o=[...this._room.remotePublishedUserMap.values()];for(let s of o)s.muteState.hasAudio&&!this._remoteAudioConfigMap.has(s.userId)&&(yield this._startRemoteAudio({userId:s.userId}))}else r?yield this._stopRemoteAudio({userId:e}):this._remoteAudioConfigMap.has(e)||(yield this._startRemoteAudio({userId:e}))}catch(o){throw this._remoteAudioMuteMap.delete(e),o}})}setRemoteAudioVolume(e,r){if(e==="*"){let o=[...this._room.remotePublishedUserMap.values()];for(let s of o)this._remoteAudioVolumeMap.set(s.userId,r),s.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:r},track:s.remoteAudioTrack})}else if(e){let o=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,r),o&&o.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:r},track:o.remoteAudioTrack})}}startPlugin(e,r){return A(this,null,function*(){return e.start(r)})}updatePlugin(e,r){return A(this,null,function*(){return e.update(r)})}stopPlugin(e,r){return A(this,null,function*(){return e.stop(r)})}enableAudioVolumeEvaluation(e=2e3,r=!1){this._room.enableAudioVolumeEvaluation(e,r)}on(e,r,o){if(this.listeners(e).includes(r))return this;if(this._log.debug("on",e),super.on(e,r,o),this._eventListened.add(e),this.listeners(K.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:s}=this.room.audioManager;s.get("")||s.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return this}emit(e,...r){try{Zf.has(e)&&this._log.debug(`emit ${e} ${JSON.stringify(r)}`)}catch(o){}return super.emit(e,...r)}off(e,r,o){if(this._log.debug("off",e),e==="*"?(this._eventListened.clear(),this.removeAllListeners()):super.off(e,r,o),(e===_e.EVENT.AUDIO_FRAME||e==="*")&&this.listeners(_e.EVENT.AUDIO_FRAME).length===0){let{getPCMAbortCtrlMap:s}=this.room.audioManager;s.forEach(n=>{n==null||n.abort("off")}),s.clear()}return this}getAudioTrack(e={userId:"",streamType:"main"}){let r,o=null,s="main",n=!1;if(ve(e)?r=e:(r=e.userId,n=e.processed===!0,e.streamType&&(s=e.streamType)),r){let d=this._room.remotePublishedUserMap.get(r);d&&(o=d.remoteAudioTrack)}else o=s==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return o?n&&o.outMediaTrack&&o.outMediaTrack!==o.mediaTrack?o.outMediaTrack.clone():o.mediaTrack:null}getVideoTrack(e={userId:"",streamType:"main"}){let{userId:r="",streamType:o="main",processed:s=!1}=e,n=null;if(r==="")o==="main"&&this._localVideoTrack&&(n=this._localVideoTrack),o==="sub"&&this._localScreenTrack&&(n=this._localScreenTrack);else{let d=this._room.remotePublishedUserMap.get(r);d&&(n=o==="main"?d.remoteVideoTrack:d.remoteAuxiliaryTrack)}return n?s&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoSnapshot(e={}){let{userId:r,streamType:o="main"}=e;if(r){let s=this._room.remotePublishedUserMap.get(r);if(o==="main"&&(s!=null&&s.muteState.hasVideo))return s.remoteVideoTrack.getVideoFrame();if(o==="sub"&&(s!=null&&s.muteState.hasAuxiliary))return s.remoteAuxiliaryTrack.getVideoFrame()}else{if(o==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(o==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var r,o;this._speakerId=e,(r=this._localAudioTrack)==null||r.setAudioOutput(e),(o=this._localScreenAudioTrack)==null||o.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(s=>s.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return A(this,null,function*(){(yield Xi()).forEach(o=>{o.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(K.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}),vt=o)}),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 A(this,null,function*(){let{userId:r}=e;if(this._remoteAudioConfigMap.has(r)){this._log.warn(`remote audio has already started. userId:${r}`);return}let o=this._room.remotePublishedUserMap.get(r);if(!o)return;let s={},n=o.remoteAudioTrack;this._listenOutputTrackChanged(n),this._speakerId&&n.setAudioOutput(this._speakerId);try{let d=this._remoteAudioVolumeMap.get(r),m=We(d)?d:100;s.volume=m,this._remoteAudioConfigMap.set(r,e),yield this._room.subscribe(n),ye(Ce(n,"decode-failed"),Xe(Ce(n,oe.INIT)),ke(()=>{this.startPlugin(wa.Name,{track:n,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:s,track:n}),L.emit("115",{userId:r,room:this.room})}catch(d){throw this._remoteAudioConfigMap.delete(r),d}this._emitTrackEvent(n)})}_stopRemoteAudio(e,r=!0){return A(this,null,function*(){let o=this._room.remotePublishedUserMap.get(e.userId);o&&(o.remoteAudioTrack.stop(),o.muteState.hasAudio&&r&&(yield this._room.unsubscribe(o.remoteAudioTrack)),this._mediaTrackMap.delete(o.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete(`${e.userId}`),L.emit("116",{userId:e.userId,room:this.room})})}_enableVideoDecodeFallback(e,r){let o=this._room.videoDecodeFallbackType;if(!o||!this._plugins.has("TRTCVideoDecoder"))return;e.log.debug("remote video will fall back when decode failed",e.id);let s;ye(Ce(e,"decode-failed"),Xe(Ce(e,oe.INIT)),Ia(()=>{this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:o})}),gi(Ce(e,"decode-downgrade-state-changed")),ke(n=>{s=n.state,this.emit(K.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,Ee(Z({},n),{streamType:r,userId:e.userId}))},n=>{e.log.error("fallback",n)},()=>{s==="STARTED"&&e.log.info("fallback complete")}))}_updateVideoPlayOption(n){return A(this,arguments,function*({view:e,playOption:r,track:o,prevConfig:s}){if(o.setMirror(r.mirror),V(e)&&s&&s.view&&!Is(r)){let d=ys(s.view);d.length>0&&(yield o.play(d,r))}if(!V(e)){let d=ys(e);d.length>0?yield o.play(d,r):o.stop()}})}_updateAudioPlayOption(s){return A(this,arguments,function*({playOption:e={},track:r,prevConfig:o}){if(!r.isPlayCalled)try{yield r.play(null,e)}catch(n){}V(e.muted)||r.setPlayerMute(e.muted),V(e.volume)||r.setAudioVolume(e.volume/100)})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e,r=!0){let o=e.isRemote?e.userId:"";e.outMediaTrack&&(r&&this._mediaTrackMap.get(e.outMediaTrack)===o||(this._mediaTrackMap.set(e.outMediaTrack,o),this.emit(K.TRACK,{userId:o,streamType:no(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var r,o,s;let e=[];if((r=this._localAudioConfig)!=null&&r.publish&&this._localAudioTrack&&e.push(this._localAudioTrack),(o=this._localVideoConfig)!=null&&o.publish&&this._localVideoTrack&&e.push(this._localVideoTrack),(s=this._localScreenConfig)!=null&&s.publish&&(this._localScreenTrack&&e.push(this._localScreenTrack),this._localScreenAudioTrack&&e.push(this._localScreenAudioTrack)),e.length!==0)return this._room.publish(...e).catch(()=>{})}_observeView({remoteTrack:e,view:r,receiveWhenViewVisible:o=!1,viewRoot:s}){if(V(r))return;let n=this._remoteVideoConfigMap.get(`${e.userId}_${no(e.streamType)}`);if(!n)return;let d=n.observer||void 0;if(r===null||it(r)&&r.length===0||!o){d==null||d.disconnect(),e.isSubscribed||this._room.subscribe(e).catch(()=>{});return}let l=n.visibleViewMap||new Map,g=-1;(!d||d.root!==s)&&(d==null||d.disconnect(),l.clear(),d=new IntersectionObserver(S=>{S.forEach(v=>{l.set(v.target,v.isIntersecting),e.log.info(`view ${v.target.id} is${v.isIntersecting?"":" not"} visible`)}),clearTimeout(g),g=window.setTimeout(()=>{[...l.values()].find(x=>x)?e.isSubscribed||this._room.subscribe(e).catch(()=>{}):e.isSubscribed&&this._room.unsubscribe(e).catch(()=>{})},200)},{root:s}));let _=new Set(ys(r));l.forEach((S,v)=>{_.has(v)||(d.unobserve(v),l.delete(v))}),_.forEach(S=>{l.set(S,!0),d.observe(S)}),d.takeRecords().forEach(S=>{l.set(S.target,S.isIntersecting)}),n.visibleViewMap=l,n.observer=d}_exitRoom(){return A(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 r=e.includes("main")?"main":"sub",o=e.split(`_${r}`)[0];o&&this._stopRemoteVideo({userId:o,streamType:r}).catch()}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),this._remoteAudioVolumeMap.clear(),sg(this),this._room.remotePublishedUserMap.forEach(e=>{pt(e.remoteAudioTrack),pt(e.remoteVideoTrack),pt(e.remoteAuxiliaryTrack)})})}_stopScreenShare(){return A(this,null,function*(){var e;if(this._localScreenTrack){if(this._room.isJoined){let r=[this._localScreenTrack];this._localScreenAudioTrack&&r.push(this._localScreenAudioTrack),yield(e=this._room)==null?void 0:e.unpublish(...r).catch(()=>{})}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),pt(this._localScreenTrack),this._localScreenTrack=null,this._localScreenConfig=null}})}_onLocalTrackCaptured({track:e}){e.kind==="audio"&&(!vt||Gs(vt))&&(this._initActiveSpeaker(),L.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return A(this,null,function*(){if(vt&&!Gs(vt))this.emit(K.DEVICE_CHANGED,{type:"speaker",action:"active",device:vt});else{let e=yield Xi();e[0]&&!Gs(e[0])?(vt=e[0],this.emit(K.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):L.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable({userId:e}){let r=this._remoteAudioMuteMap.has(e)?this._remoteAudioMuteMap.get(e):this._remoteAudioMuteMap.get("*");(r===!1||this._room.autoReceiveAudio&&!r)&&this._doStartRemoteAudio({userId:e}).catch(()=>{})}_onVideoAvailable({userId:e,streamType:r}){if(!this._room.autoReceiveVideo)return;let o=this._room.remotePublishedUserMap.get(e);if(o){let s=r==="main"?o.remoteVideoTrack:o.remoteAuxiliaryTrack,n=[s];this._room.autoReceiveAudio&&o.remoteAudioTrack.isAvailable&&n.push(o.remoteAudioTrack),this._room.subscribe(...n).then(()=>{this._emitTrackEvent(s)}).catch(()=>{})}}_onAudioUnavailable({userId:e,muteState:r}){r.hasAudio&&r.audioMuted||this._stopRemoteAudio({userId:e},!1).catch(()=>{})}_onVideoUnavailable({userId:e,streamType:r}){this._stopRemoteVideo({userId:e,streamType:r},!1).catch(()=>{})}sendSEIMessage(e,r){var s;let o=this._plugins.get("SEI");o&&(o.update({buffer:e,options:Ee(Z({seiPayloadType:243},r),{small:!!((s=this._localVideoTrack)!=null&&s.small)})}),X.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var r,o;(o=(r=this._room).sendCustomMessage)==null||o.call(r,e),X.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,r){return A(this,null,function*(){return this._log.info(`callExperimentalAPI(${e}, ${JSON.stringify(r)})`),pg.call(e,Z({trtcInstance:this},r))})}static setLogLevel(e,r){F.setLogLevel(e),V(r)||(r?F.enableUploadLog():F.disableUploadLog())}static isSupported(){return Zc()}static getCameraList(e=!0){return ir(e)}static getMicrophoneList(e=!0){return Xt(e)}static getSpeakerList(e=!0){return Xi(e)}static setCurrentSpeaker(e){return A(this,null,function*(){if(ut&&(e===ur.SPEAKER||e===ur.HEADSET)){let o=yield _e.getMicrophoneList(),s="";if(o.forEach(n=>{n.label===e&&(s=n.deviceId)}),!s)return;Ma.forEach(n=>A(this,null,function*(){n._localAudioTrack&&(yield n.updateLocalAudio({option:{microphoneId:s}}))}));return}(yield Xi()).forEach(o=>{o.deviceId===e&&(Ma.forEach(s=>{s._setCurrentSpeaker(e),s.emit(K.DEVICE_CHANGED,{type:"speaker",action:"active",device:o})}),vt=o)})})}static _addKVStat({type:e,key:r,value:o,base:s,useUV:n,version:d}){switch(d&&(Vo.version=d),e){case"count":Vo.addCount({key:r,useUV:n});break;case"enum":Vo.addEnum({key:r,value:o,useUV:n});break;case"number":Vo.addNumber({key:r,value:o,split:s});break}}};u(_e,"_loggerManager",F),u(_e,"EVENT",K),u(_e,"ERROR_CODE",pe),u(_e,"TYPE",ur),u(_e,"frameWorkType",30),J([et({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"}})})],_e.prototype,"use",1),J([$t(Rt.TRTC.enterRoom),oo("room",([e],[r])=>(e.roomId||e.strRoomId)===(r.roomId||r.strRoomId)&&e.userId===r.userId&&e.sdkAppId===r.sdkAppId),Me(e=>function(r){return this._log.setUserId(r.userId),this._log.setSdkAppId(r.sdkAppId),e.call(this,r)}),et()],_e.prototype,"enterRoom",1),J([et()],_e.prototype,"exitRoom",1),J([$t(Rt.TRTC.switchRole),Ko("room",{merge:(e,r)=>r}),et()],_e.prototype,"switchRole",1),J([et()],_e.prototype,"destroy",1),J([$t(Rt.TRTC.startLocalAudio),oo("audio",([e],[r])=>{var o,s;return((o=e==null?void 0:e.option)==null?void 0:o.microphoneId)===((s=r==null?void 0:r.option)==null?void 0:s.microphoneId)}),et()],_e.prototype,"startLocalAudio",1),J([$t(Rt.TRTC.updateLocalAudio),Ko("audio",{debounce:{delay:200,getKey:()=>`${hg}-localAudio`,isNeedToDebounce:e=>{var r;return!V((r=e.option)==null?void 0:r.captureVolume)}}}),et()],_e.prototype,"updateLocalAudio",1),J([so("audio"),et()],_e.prototype,"stopLocalAudio",1),J([$t(Rt.TRTC.startLocalVideo),oo("video",([e],[r])=>{var o,s;return((o=e==null?void 0:e.option)==null?void 0:o.cameraId)===((s=r==null?void 0:r.option)==null?void 0:s.cameraId)}),et()],_e.prototype,"startLocalVideo",1),J([$t(Rt.TRTC.updateLocalVideo),Ko("video"),et()],_e.prototype,"updateLocalVideo",1),J([so("video"),et()],_e.prototype,"stopLocalVideo",1),J([$t(Rt.TRTC.startScreenShare),oo("screen",()=>!0),et()],_e.prototype,"startScreenShare",1),J([$t(Rt.TRTC.updateScreenShare),Ko("screen"),et()],_e.prototype,"updateScreenShare",1),J([et()],_e.prototype,"stopScreenShare",1),J([$t(Rt.TRTC.startRemoteVideo),oo(e=>`v${e.userId}${e.streamType}`,()=>!0),et({getRemoteId:e=>`${e.userId}_${e.streamType}`})],_e.prototype,"startRemoteVideo",1),J([$t(Rt.TRTC.updateRemoteVideo),Ko(e=>`v${e.userId}${e.streamType}`),et({getRemoteId:e=>`${e.userId}_${e.streamType}`})],_e.prototype,"updateRemoteVideo",1),J([$t(Rt.TRTC.stopRemoteVideo),Me(e=>function(r){return A(this,null,function*(){if(r.userId==="*"){let o=[];return this._room.remotePublishedUserMap.forEach(s=>{this._remoteVideoConfigMap.has(`${s.userId}_main`)&&o.push(this.stopRemoteVideo({streamType:"main",userId:s.userId}).catch(()=>{})),this._remoteVideoConfigMap.has(`${s.userId}_sub`)&&o.push(this.stopRemoteVideo({streamType:"sub",userId:s.userId}).catch(()=>{}))}),Promise.all(o)}return e.call(this,r)})}),et({getRemoteId:e=>`${e.userId}_${e.streamType}`})],_e.prototype,"stopRemoteVideo",1),J([so(e=>`v${e.userId}${e.streamType}`)],_e.prototype,"_stopRemoteVideo",1),J([$t(...Rt.TRTC.muteRemoteAudio),et({getRemoteId:e=>e})],_e.prototype,"muteRemoteAudio",1),J([ep(...Rt.TRTC.setRemoteAudioVolume),ng(200,e=>e),et({getRemoteId:e=>e})],_e.prototype,"setRemoteAudioVolume",1),J([Jd("start"),Qi(e=>{var r;return(r=e.afterStart)==null?void 0:r.call(e)}),oo((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r)),et({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Dl[e.getName()],ignoreLog:e=>e.getName()==="Debug"})],_e.prototype,"startPlugin",1),J([Jd("update"),Ko((e,r)=>e.disableRandomCall?null:e.getAlias()+e.getGroup(r)),et({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>Nl[e.getName()]})],_e.prototype,"updatePlugin",1),J([Jd("stop"),so((e,r)=>{if(e.disableRandomCall)return null;let o=e.getGroup(r),s=e.getAlias();return o==="*"?new RegExp(`${s}.*`):s+o}),et({replaceArg:e=>({argIndex:0,value:e.getName()}),getKVReportKey:e=>wl[e.getName()]})],_e.prototype,"stopPlugin",1),J([ep(...Rt.TRTC.enableAudioVolumeEvaluation)],_e.prototype,"enableAudioVolumeEvaluation",1),J([et()],_e.prototype,"getVideoSnapshot",1),J([et()],_e.prototype,"_setCurrentSpeaker",1),J([oo(e=>`a${e.userId}`,()=>!0)],_e.prototype,"_startRemoteAudio",1),J([Me(e=>function(r){return A(this,null,function*(){return r.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(o=>this._stopRemoteAudio(Ee(Z({},r),{userId:o.userId})).catch(()=>{}))):e.call(this,r)})}),so(e=>`a${e.userId}`)],_e.prototype,"_stopRemoteAudio",1),J([so("room")],_e.prototype,"_exitRoom",1),J([so("screen")],_e.prototype,"_stopScreenShare",1),J([$t(...Rt.TRTC.sendSEIMessage),zm({timesInSecond:30,maxSizeInSecond:8e3,getSize:(...e)=>e[0].byteLength})],_e.prototype,"sendSEIMessage",1),J([$t(Rt.TRTC.sendCustomMessage),zm({timesInSecond:30,maxSizeInSecond:8e3,getSize:e=>e.data.byteLength})],_e.prototype,"sendCustomMessage",1),J([$t(Rt.TRTC.create)],_e,"_create",1);var up=_e,rn=up;var ou=class{constructor(t,e){u(this,"_flag");u(this,"terminalType");u(this,"userId");u(this,"tinyId");u(this,"role");u(this,"remoteAudioTrack");u(this,"remoteVideoTrack");u(this,"remoteAuxiliaryTrack");this.userId=e.userId||"",this.tinyId=e.tinyId||"",this.role=e.role||"audience",this.terminalType=e.terminalType,this.remoteAudioTrack=new qo(t,this),this.remoteVideoTrack=new to(t,this),this.remoteAuxiliaryTrack=new Pd(t,this),this.flag=e.flag||0}get subscribeState(){let t={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(this.remoteVideoTrack.mediaType&8?t.smallVideo=!0:t.video=!0),this.remoteAudioTrack.isSubscribed&&(t.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(t.auxiliary=!0),t}get muteState(){return Nn(this.flag,this.userId)}get flag(){return this._flag}set flag(t){if(t===this._flag)return;let e,r=this.muteState;this._flag=t;let o=this.muteState;for(e in o)r[e]!=o[e]&&console.log(this.userId,e,r[e],"->",o[e]);this.remoteAudioTrack.onFlagChanged(),this.remoteVideoTrack.onFlagChanged(),this.remoteAuxiliaryTrack.onFlagChanged()}};var lp=class{constructor(){u(this,"_set",new Set);L.on(U.LEAVE_SUCCESS,this.delete,this)}add({room:t,roomId:e}){if(t.scene==="rtc")return;let r=this.getKey(t.userId,e||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(r)}delete({room:t,roomId:e}){if(t.scene==="rtc")return;let r=this.getKey(t.userId,t.roomId||e,t.sdkAppId,t.useStringRoomId);this._set.delete(r)}getKey(t,e,r,o){return`${r}_${e}_${t}_${o}`}isJoined({userId:t,roomId:e,sdkAppId:r,room:o}){return o.scene==="rtc"?!1:this._set.has(this.getKey(t,e,r,o.useStringRoomId))}};function sS(){return A(this,null,function*(){let i,t;try{let _=yield Xt();i=_&&_.length}catch(_){}try{let _=yield ir();t=_&&_.length}catch(_){}let e={microphone:i,camera:t},{isH264EncodeSupported:r,isVp8EncodeSupported:o,isH264DecodeSupported:s,isVp8DecodeSupported:n}=this.checkSystemResult.detail,d=zi.basis(),m={webRTC:d.isWebRTCSupported,getUserMedia:d.isGetUserMediaSupported,webSocket:d.isWebSocketsSupported,screenShare:d.isScreenShareSupported,webAudio:d.isWebAudioSupported,h264Encode:r,h264Decode:s,vp8Encode:o,vp8Decode:n},l={browser:d.browser,os:d.os,trtc:m,devices:e},g={isWebCodecSupported:d.isWebCodecSupported,isMediaSessionSupported:d.isMediaSessionSupported,isWebTransportSupported:d.isWebTransportSupported};je.uploadEvent({log:`trtcstats-${JSON.stringify(l)}`,userId:this.userId}),this._log.info(`TrtcStats-${JSON.stringify(l)}`),je.uploadEvent({log:`trtcadvancedstats-${JSON.stringify(g)}`,userId:this.userId})})}function gg(){return Me(i=>{let t=new lp;return function(e,r,o){return A(this,null,function*(){let s=String(e.roomId||e.strRoomId);if(this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.userSig=e.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=r,e.privateMapKey=e.privateMapKey||"",this.isJoined)throw new ae({code:q.INVALID_OPERATION,message:$e({key:Fe.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:s,sdkAppId:this.sdkAppId,room:this}))throw new ae({code:q.INVALID_OPERATION,message:$e({key:Fe.REPEAT_JOIN,data:this.userId})});t.add({room:this,roomId:s}),this.role=e.role===21?"audience":"anchor",this._log.info(`Join() => joining room: ${s} useStringRoomId: ${this.useStringRoomId} scene: ${this.scene} role: ${this.role}`),L.emit(U.JOIN_START,{room:this,roomId:s,params:e});let n=Ur.getEnv();n||(n=Zr.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(dc.OLD_CLOUD_LADDER)?n=Zr.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(dc.WEBRTC)&&(n=Zr.WEBRTC))),je.setConfig({env:n,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:s}),zi.checkSystemRequirementsInternal().then(d=>{this.checkSystemResult=d,sS.call(this)});try{!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Ur.getEnv()&&(yield this.schedule(e,o));let d=yield i.call(this,e,r,o);return this.roomId=s,this._joinedTimestamp=Ur.performanceNow(),L.emit(U.JOIN_SUCCESS,{room:this}),o===30&&!e.component&&je.uploadEvent({log:`stat-conv-${Number(yr)}-${location.hostname}`,userId:this.userId}),d}catch(d){throw t.delete({room:this,roomId:s}),L.emit(U.JOIN_FAILED,{room:this,error:d}),d}})}})}var Eg=()=>Me(i=>function(...t){return A(this,null,function*(){L.emit(U.LEAVE_START,{room:this}),yield i.call(this,...t),L.emit(U.LEAVE_SUCCESS,{room:this,roomId:this.roomId})})});function _g(){return Me(i=>function(...t){return A(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(t=t.filter(r=>r.outMediaTrack&&r.state==="capture"),!t.length))return;L.emit("61",{room:this});let e=i.apply(this,t);return t.forEach(r=>r.publish(this,e)),e})})}function Tg(){return Me(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>r.unpublish()),e})}function Ig(){return Me(i=>function(...t){let e=i.apply(this,t);return t.forEach(r=>!r.isSubscribed&&r.subscribe(e)),e})}function nS({fn:i,context:t}){return function(...e){try{let r=i.apply(t,e);return Ui(r)?r.catch(o=>F.error(`${i.name}() error observed ${o}`)):r}catch(r){F.error(`${i.name}() error observed ${r}`)}}}var su=class{constructor(t){u(this,"_frameWorkType");u(this,"_component");u(this,"_language");u(this,"connectionType");u(this,"_room");u(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0});u(this,"_keyPrefix");u(this,"_log");u(this,"_intervalId");u(this,"_firstPublishedUserList");u(this,"_networkQuality");u(this,"_basicInfo");u(this,"_pathJoinRoom");u(this,"_pathLeaveRoom");u(this,"_pathMainVideoMap");u(this,"_pathMainAudioMap");u(this,"_pathAuxiliaryMap");u(this,"_remoteStreamStatMap");u(this,"_localStreamStat");u(this,"_eventMap",new Map);u(this,"_captureCostSum",0);u(this,"_captureCostCount",0);u(this,"isDestroyed",!1);this._frameWorkType=t.frameWorkType||30,this._component=t.component||0,this.connectionType=t.connectionType||1,this._language=t.language||0,this._room=t.room,this._keyPrefix="key_point",this._log=F.createLogger({id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&He(this[e])&&(this[e]=nS({fn:this[e],context:this}))}),this.initData(),this.installEvents()}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:st,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,Wn().then(t=>{this._basicInfo.string_os_version=Po(),t?this._basicInfo.string_device_name=t.mobile?t.model:this._basicInfo.string_os_version:this._basicInfo.string_device_name=this._basicInfo.string_os_version})}addEvent(t,e){return this._eventMap.set(t,e),L.on(t,e),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("pagehide",this.handleUnload),this._room.once("banned",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(U.JOIN_START,this.handleJoinStart).addEvent(U.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(U.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(U.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(U.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(U.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(U.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(U.JOIN_FAILED,this.handleJoinFailed).addEvent(U.LEAVE_START,this.handleLeaveStart).addEvent(U.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(U.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(U.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(U.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(U.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(U.PUBLISH_START,this.handlePublishStart).addEvent(U.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(U.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(U.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(U.PLAY_TRACK_START,this.handlePlayStart).addEvent(U.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(U.PLAYER_STATE_CHANGED,({track:t,state:e,type:r})=>{!t.isRemote||!this.hitTest(t.room)||e==="PLAYING"&&(r===N.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))}).addEvent(U.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(U.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(U.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(U.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{if(!this.hitTest(t))return;let o=e.hasAudio||e.hasVideo||e.hasSmall,s=e.hasAuxiliary,n=r.hasAudio||r.hasVideo||r.hasSmall,d=r.hasAuxiliary;!o&&n&&this.handleRemoteStreamAdded(r.userId,"main"),!s&&d&&this.handleRemoteStreamAdded(r.userId,"auxiliary")}).addEvent(U.SINGLE_CONNECTION_STAT,({room:t,stat:e})=>{this.hitTest(t)&&(this._pathJoinRoom.int32_ice_cost=e.ice,this._pathJoinRoom.int32_dtls_cost=e.dtls,this._pathJoinRoom.int32_peer_connection_cost=e.peerConnection)})}uninstallEvents(){window.removeEventListener("pagehide",this.handleUnload),this._eventMap.forEach((t,e)=>L.off(e,t)),this._eventMap.clear()}destroy(){this.uninstallEvents(),bt.clearTask(this._intervalId),this._pathJoinRoom.uint64_start_time===0&&(this._room=null),this.isDestroyed=!0}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(t){this.hitTest(t.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now()),t.params&&(V(t.params.frameWorkType)||(this._frameWorkType=t.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),V(t.params.component)||(this._component=t.params.component,this._basicInfo.uint32_component=this._component),V(t.params.language)||(this._language=t.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess({room:t,detailCost:e}){if(this.hitTest(t)&&e){let{totalCost:r,local:o,dns:s,tcp:n,tls:d,request:m,response:l}=e;this._pathJoinRoom.int32_schedule_cost=r,this._pathJoinRoom.int32_schedule_local=o,this._pathJoinRoom.int32_schedule_dns=s,this._pathJoinRoom.int32_schedule_tcp=n,this._pathJoinRoom.int32_schedule_tls=d,this._pathJoinRoom.int32_schedule_request=m,this._pathJoinRoom.int32_schedule_response=l}}handleSignalConnectionStart({room:t}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd({room:t,error:e}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),e&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=e instanceof ae?Number(e.getExtraCode()||e.getCode()):q.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=t.code,t.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=t.room.getSignalInfo())}handleJoinFailed({room:t,error:e}){this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=e.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(t){this.hitTest(t.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=t.publishedUserList||[])}handleSendFirstVideoFrame({room:t}){this.hitTest(t)&&this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(t){this.hitTest(t.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(t){this.hitTest(t.room)&&this._pathLeaveRoom.uint64_end_time===0&&(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0?this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time:this._log.warn("pathJoinRoom endTime is 0"),this.report())}handleLeaveSendCMD(t){this.hitTest(t.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleRemoteStreamAdded(t,e){var o;let r=`${t}_${e}`;if(!this._remoteStreamStatMap.has(r)){let s={userId:t,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:Ee(Z({},aS),{msg_user_info:new Oa({userId:t,tinyId:(o=this._room.remotePublishedUserMap.get(t))==null?void 0:o.tinyId,role:20})})};s.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(r,s)}}handleSubscribeStart({room:t,remotePublishedUser:e,streamType:r,subscribeState:o}){if(!this.hitTest(t))return;let{userId:s,tinyId:n,role:d}=e,m=new Oa({userId:s,tinyId:n,role:d==="anchor"?20:21}),l=Date.now(),g=`${s}_${r}`,_=this._remoteStreamStatMap.get(g);_&&_.subscribeStartTime===0&&(_.subscribeStartTime=l),r==="main"?(e.muteState.hasVideo&&(o.video||o.smallVideo)&&!this._pathMainVideoMap.has(g)&&this._pathMainVideoMap.set(g,{statsToReport:{msg_user_info:m,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:s,sendSubscribeCMDTime:l}),e.muteState.hasAudio&&o.audio&&!this._pathMainAudioMap.has(g)&&this._pathMainAudioMap.set(g,{statsToReport:{msg_user_info:m,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:s,sendSubscribeCMDTime:l})):e.muteState.hasAuxiliary&&o.auxiliary&&!this._pathAuxiliaryMap.has(g)&&this._pathAuxiliaryMap.set(g,{sendSubscribeCMDTime:l})}handleSubscribed({room:t,remotePublishedUser:e,streamType:r}){if(this.hitTest(t)){let o=`${e.userId}_${r}`,s=this._remoteStreamStatMap.get(o);s&&s.subscribedTime===0&&(s.subscribedTime=Date.now())}}handlePlayStart({track:t}){if(!t.isRemote||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,r=this._remoteStreamStatMap.get(e);(r==null?void 0:r.playStreamTime)===0&&(r.playStreamTime=Date.now())}handleVideoLoadedData({track:t}){if(!t.isRemote||!this.hitTest(t.room))return;let e=`${t.userId}_${t.streamType}`,r=this._pathMainVideoMap.get(e);r&&r.statsToReport.uint64_combine_first_frame_time===0&&(r.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(t){let e=`${t.userId}_${t.streamType}`,r=Date.now(),o=this._pathMainVideoMap.get(e),s=this._remoteStreamStatMap.get(e);if(s){let{statsToReport:n}=s;if(!n.uint32_video_render_first&&t.streamType==="main"?this.hasVideoFlag(t.userId):this.hasAuxFlag(t.userId)){let d=r-this._pathJoinRoom.uint64_start_time;n.uint32_video_render_first=d,X.addNumber({key:516820,value:d})}}(o==null?void 0:o.statsToReport.uint64_render_first_frame_time)===0&&(o.statsToReport.uint64_render_first_frame_time=r)}handleAudioPlaying(t){let e=`${t.userId}_${t.streamType}`,r=this._pathMainAudioMap.get(e);r&&r.statsToReport.uint64_play_first_frame_time===0&&(r.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(t){this.hitTest(t.room)&&(this._networkQuality.totalUplinkLoss+=t.uplink.loss,this._networkQuality.totalUplinkRTT+=t.uplink.rtt,this._networkQuality.count++,t.downlinks.forEach(({rtt:e,loss:r,userId:o,videoDelay:s,audioDelay:n})=>{let d=this._networkQuality.totalDownlinkRTTAndLossMap.get(o);if(d)d.totalRTT+=e,d.totalLoss+=r,s&&(d.totalVideoDelay=(d.totalVideoDelay||0)+s,d.videoDelayCount=(d.videoDelayCount||0)+1),n&&(d.totalAudioDelay=(d.totalAudioDelay||0)+n,d.audioDelayCount=(d.audioDelayCount||0)+1),d.count++;else{let m,l,g,_;s&&(l=s,g=1),n&&(m=n,_=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(o,{totalRTT:e,totalLoss:r,count:1,totalAudioDelay:m,totalVideoDelay:l,audioDelayCount:_,videoDelayCount:g})}}))}handleHeartbeatStats(t){if(this.hitTest(t.room)){let{msg_device_info:e,msg_up_stream_info:r,msg_down_stream_info:o}=t.report;if(r.msg_video_status[0]){let{uint32_video_codec_bitrate:s,uint32_video_enc_fps:n,uint32_video_width:d,uint32_video_height:m}=r.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=s,this._localStreamStat.totalVideoFPS+=n,this._localStreamStat.totalVideoWidth+=d,this._localStreamStat.totalVideoHeight+=m,this._localStreamStat.videoCount++}if(r.msg_audio_status){let{uint32_audio_level:s}=r.msg_audio_status;Math.floor(s/ci*100)>0&&(this._localStreamStat.totalAudioLevel+=s/ci,this._localStreamStat.audioLevelCount++)}o.forEach(s=>{let{msg_user_info:n,msg_audio_status:d,msg_video_status:m}=s,l=n.str_identifier,g=this._room.remotePublishedUserMap.get(l);if(m.forEach(_=>{let S=_.uint32_video_stream_type===2,v=_.uint32_video_stream_type===7,x=`${l}_${S?"main":"auxiliary"}`,P=this._remoteStreamStatMap.get(x);if(P&&(S&&(g!=null&&g.remoteVideoTrack.isSubscribed)||v&&(g!=null&&g.remoteAuxiliaryTrack))){P.totalVideoFPS+=_.uint32_video_receive_fps,P.totalVideoBitrate+=_.uint32_video_codec_bitrate,P.videoCount++,P.statsToReport.uint32_video_width===0&&(P.statsToReport.uint32_video_width=_.uint32_video_width),P.statsToReport.uint32_video_height===0&&(P.statsToReport.uint32_video_height=_.uint32_video_height);let M=S?g.remoteVideoTrack:g.remoteAuxiliaryTrack;M.stat.jitterBufferDelay&&(P.videoJitterBufferDelay=M.stat.jitterBufferDelay),M.stat.framesReceived&&(P.statsToReport.uint32_video_consume_render_rate=Math.floor(M.stat.framesDecoded/M.stat.framesReceived*gn(10,6)))}}),!Is(d)){let _=`${l}_main`,S=this._remoteStreamStatMap.get(_);this._remoteStreamStatMap.has(_)&&S&&g!=null&&g.remoteAudioTrack.isSubscribed&&(S.totalAudioBitrate+=d.uint32_audio_codec_bitrate,S.audioCount++,g.remoteAudioTrack.stat.jitterBufferDelay&&(S.audioJitterBufferDelay=g.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(d.uint32_audio_level/ci*100)>0&&(S.totalAudioLevel+=d.uint32_audio_level/ci,S.audioLevelCount++))}}),e.uint32_audio_capture_cost&&(this._captureCostSum+=e.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0))}}handlePublishStart({room:t}){this.hitTest(t)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart({track:t}){t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess({track:t}){t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed({track:t,error:e}){let o={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[e.name]||(e instanceof ae?e.getExtraCode()||e.getCode():q.UNKNOWN);t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=o,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=o,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&gs)>=0}hasAudioFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&Es)>=0}hasAuxFlag(t){return this._firstPublishedUserList.findIndex(e=>e.userId===t&&e.flag&Sn)>=0}hitTest(t){return t===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let t=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=t<<16|e}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((t,e)=>{let{userId:r}=t,o=this._networkQuality.totalDownlinkRTTAndLossMap.get(r);if(o){let{totalLoss:g,count:_,audioDelayCount:S,videoDelayCount:v,totalAudioDelay:x,totalVideoDelay:P}=o;t.statsToReport.uint32_avg_down_loss=Math.floor(g/_),S&&x&&(t.statsToReport.uint32_audio_network_p2p_delay=Math.floor(x/S),t.audioJitterBufferDelay&&(t.statsToReport.uint32_p2p_delay=Math.floor(t.statsToReport.uint32_audio_network_p2p_delay+t.audioJitterBufferDelay))),v&&P&&(t.statsToReport.uint32_video_network_p2p_delay=Math.floor(P/v))}t.videoCount>0&&(t.statsToReport.uint32_video_avg_fps=Math.floor(t.totalVideoFPS/t.videoCount),t.statsToReport.uint32_video_avg_bitrate=Math.floor(t.totalVideoBitrate/t.videoCount)),t.audioCount>0&&(t.statsToReport.uint32_audio_recv_bitrate=t.statsToReport.uint32_audio_bitrate=Math.floor(t.totalAudioBitrate/t.audioCount)),t.audioLevelCount>0&&(t.statsToReport.uint32_audio_play_db=Math.floor(t.totalAudioLevel/t.audioLevelCount*100));let{callDurationCalculator:s}=this._room;s&&(t.statsToReport.uint32_audio_play_time=s.getDuration(e,N.AUDIO),t.statsToReport.uint32_video_play_time=s.getDuration(e,N.VIDEO)),t.statsToReport.uint32_video_render_first&&(t.statsToReport.uint32_video_render_first=Math.min(t.statsToReport.uint32_video_render_first,ts));let{badCaseDetector:n}=this._room,{dataFreeze:d,count:m}=n.getDataFreezeDuration(e),{renderFreeze:l}=n.getRenderFreezeDuration(e);t.statsToReport.uint32_video_block_count=m,t.statsToReport.uint32_video_block_time=Math.min(d,t.statsToReport.uint32_video_play_time),t.statsToReport.uint32_video_external_block_time=Math.min(l,t.statsToReport.uint32_video_play_time),n.isBlackStream(e)&&t.statsToReport.uint32_video_avg_fps===0?t.statsToReport.uint32_video_black_screen_subjective=1:t.statsToReport.uint32_video_black_screen_subjective=0}),this._pathMainAudioMap.forEach((t,e)=>{if(!this.hasAudioFlag(t.userId)){this._pathMainAudioMap.delete(e);return}t.statsToReport.uint64_play_first_frame_time-t.statsToReport.uint64_start_enter_time>ts&&(t.statsToReport.uint64_play_first_frame_time=t.statsToReport.uint64_start_enter_time+ts)}),this._pathMainVideoMap.forEach((t,e)=>{if(!this.hasVideoFlag(t.userId)){this._pathMainVideoMap.delete(e);return}t.statsToReport.uint64_render_first_frame_time-t.statsToReport.uint64_start_enter_time>ts&&(t.statsToReport.uint64_render_first_frame_time=t.statsToReport.uint64_start_enter_time+ts)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>ts&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+ts)}getReportData(){this._basicInfo.uint32_networkType=hc();let t={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new Oa({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Ss(this._signalInfo.relayIp),uint32_client_ip:Ss(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*gn(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map(e=>e.statsToReport),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map(e=>e.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(e=>e.statsToReport),uint32_info_client_ip:Ss(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend};return wn(t),t}report(){return A(this,null,function*(){try{this.prepareReport();let t=this.getReportData();yield this.upload(t),this.initData()}catch(t){this._log.warn(t)}finally{this.isDestroyed&&(this._room=null)}})}upload(t){return A(this,null,function*(){if(t.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),r=yield qu(t),o=r instanceof ArrayBuffer,s=`${ti(e,Li.KEY_POINT)}&gzip=${+o}`,n=!1;navigator.sendBeacon&&(n=navigator.sendBeacon(s,r));let d=[this.uploadKVStat(X),this.uploadKVStat(Vo)];n||d.push(ri({url:s,body:r,priority:"low"})),yield Promise.all(d)})}setConnectionType(t){this.connectionType=t,this._basicInfo.uint32_connection_type=t}uploadKVStat(t){return A(this,null,function*(){let e=t.getReportData();if(e.stats_count.length===0&&e.stats_distribution.length===0)return;e.msg_sdk_basic_info=Ee(Z({},e.msg_sdk_basic_info),{bytes_device_name:this._basicInfo.string_device_name||"",bytes_os_version:this._basicInfo.string_os_version||"",uint32_framework:this._frameWorkType,uint32_network_type:this._basicInfo.uint32_networkType||0}),this._log.debug(e);let r=yield qu(e),o=`${ti(+this._room.sdkAppId,Li.KV_STAT)}&gzip=${+(r instanceof ArrayBuffer)}`,s=!1;navigator.sendBeacon&&(s=navigator.sendBeacon(o,r)),s||ri({url:o,body:r})})}};J([Ji({settings:{timeout:500,retries:3}})],su.prototype,"upload",1);var ts=5e3,aS={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},Oa=class{constructor(t){u(this,"str_identifier");u(this,"str_tinyid");u(this,"uint32_role");this.str_identifier=String(t.userId),this.str_tinyid=String(t.tinyId||0),this.uint32_role=t.role}},Sg=su;var mp=class{constructor(){u(this,"_startTime");u(this,"_endTime");this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=Te())}stop(){this._endTime===0&&(this._endTime=Te())}getDuration(){return this._endTime===0?Te()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},nu=mp;var pp=class{constructor(t){u(this,"_room",null);u(this,"_durationMap");u(this,"_eventMap",new Map);this._room=t.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(U.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(U.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(U.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{var n;let{userId:o}=r;if(!this.hitTest(t))return;e.hasAudio&&!r.hasAudio&&this.stopDurationItem(`${o}_main`,N.AUDIO),e.hasVideo&&!r.hasVideo&&this.stopDurationItem(`${o}_main`,N.VIDEO),e.hasAuxiliary&&!r.hasAuxiliary&&this.stopDurationItem(`${o}_auxiliary`,N.VIDEO);let s=(n=this._room)==null?void 0:n.remotePublishedUserMap.get(o);s&&(!e.hasAudio&&r.hasAudio&&s.remoteAudioTrack.isSubscribed&&this.addDuractionItem(o,N.AUDIO,"main"),!e.hasVideo&&r.hasVideo&&s.remoteVideoTrack.isSubscribed&&this.addDuractionItem(o,N.VIDEO,"main"),!e.hasAuxiliary&&r.hasAuxiliary&&s.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(o,N.VIDEO,"auxiliary"))}),this._eventMap.forEach((t,e)=>L.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>L.off(e,t,this)),this._eventMap.clear()}handleSubscribed({track:t}){if(!this.hitTest(t.room))return;let{userId:e,streamType:r,kind:o}=t;t.isSubscribed?this.addDuractionItem(e,o,r):this.stopDurationItem(`${e}_${r}`,o)}handleUnsubscribed({track:t}){this.hitTest(t.room)&&this.stopDurationItem(`${t.userId}_${t.streamType}`,t.kind)}isRecording(t){return t.findIndex(e=>e.endTime===0)>=0}addDuractionItem(t,e,r){let o=`${t}_${r}`,s=new nu,n=this._durationMap.get(o);n?this.isRecording(n[e])||n[e].push(s):this._durationMap.set(o,{userId:t,type:r,audio:e===N.AUDIO?[s]:[],video:e===N.AUDIO?[]:[s]})}stopDurationItem(t,e){if(this._durationMap.has(t)){let o=this._durationMap.get(t)[e].find(s=>s.endTime===0);o&&o.stop()}}hitTest(t){return this._room===t}getDuration(t,e){return this._durationMap.has(t)?this._durationMap.get(t)[e].reduce((o,s)=>o+s.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},yg=pp;var hp=class{constructor(t){u(this,"_room");u(this,"_renderFreezeMap",new Map);u(this,"_isVideoPlayingEventFiredMap",new Map);u(this,"_dataFreezeMap",new Map);u(this,"_monitorFreezeData",new Map);u(this,"_eventMap",new Map);this._room=t.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(U.LEAVE_SUCCESS,({room:t})=>{this.hitTest(t)&&this.stop()}).set(U.PLAY_TRACK_START,this.onPlayTrackStart).set(U.UNSUBSCRIBE_SUCCESS,({room:t,streamType:e,remotePublishedUser:r})=>{if(!this.hitTest(t))return;let{userId:o}=r,s=`${o}_${e}`;this.stopDataFreeze({key:s,userId:o,type:e})}).set(U.REMOTE_PUBLISH_STATE_CHANGED,({room:t,prevMuteState:e,muteState:r})=>{if(!this.hitTest(t))return;let{userId:o}=r;if(e.hasVideo&&!r.hasVideo){let s="main",n=`${r.userId}_${s}`;this.stopDataFreeze({key:n,userId:o,type:s})}if(e.hasAuxiliary&&!r.hasAuxiliary){let s="auxiliary",n=`${r.userId}_${s}`;this.stopDataFreeze({key:n,userId:o,type:s})}}).set(U.PLAYER_STATE_CHANGED,({track:t,state:e,reason:r,type:o})=>{if(!(!t.isRemote||!t.room||!this.hitTest(t.room)||o!==N.VIDEO)){if(e==="PLAYING"){let s=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.set(s,!0)}r===N.MUTE?this.onVideoTrackMuted(t):r===N.UNMUTE&&this.onVideoTrackUnmuted(t)}}).set(U.HEARTBEAT_REPORT,this.onHearBeatReport),this._eventMap.forEach((t,e)=>L.on(e,t,this))}uninstallEvents(){this._eventMap.forEach((t,e)=>L.off(e,t,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(t){if(!t.isSubscribed)return;let{userId:e,streamType:r}=t,o=`${e}_${r}`,s=this._dataFreezeMap.get(o),n=new nu;s?s.durationItemList.push(n):this._dataFreezeMap.set(o,{userId:e,type:r,durationItemList:[n],isFreezing(){let d=this.durationItemList[this.durationItemList.length-1];return d&&d.endTime===0}})}onVideoTrackUnmuted(t){if(!t.isSubscribed)return;let{userId:e,streamType:r}=t,o=`${e}_${r}`;this.stopDataFreeze({key:o,userId:e,type:r})}onHearBeatReport({room:t,report:e}){this.hitTest(t)&&e.msg_down_stream_info.forEach(r=>{let o=this._room.remotePublishedUserMap.get(r.msg_user_info.str_identifier);if(!o)return;let{userId:s,muteState:n}=o;r.msg_video_status.forEach(d=>{d.uint32_video_stream_type===2&&n.hasVideo&&!n.videoMuted&&o.remoteVideoTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:d.uint32_video_dec_fps,type:"main"}),d.uint32_video_stream_type===7&&n.hasAuxiliary&&o.remoteAuxiliaryTrack.isSubscribed&&this.handleRenderFreeze({userId:s,fps:d.uint32_video_dec_fps,type:"auxiliary"})})})}stopDataFreeze({key:t,userId:e,type:r}){let o=this._dataFreezeMap.get(t);if(!o||!o.isFreezing())return;let s=o.durationItemList[o.durationItemList.length-1];s.stop();let n=s.getDuration();n>mc?this._monitorFreezeData.set(t,{userId:e,type:r,duration:n}):o.durationItemList.pop()}getTotalDuration(t){return t.reduce((e,r)=>{let o=r.getDuration();return e+Math.min(o,5e3)},0)}handleRenderFreeze(o){return A(this,arguments,function*({userId:t,fps:e,type:r}){let s=`${t}_${r}`,n=this._renderFreezeMap.get(s);if(e<=2){let d=Te();n&&!n.isFreeze&&(n.freezeTimeline.push({startTime:d,endTime:0}),n.isFreeze=!0),n||this._renderFreezeMap.set(s,{userId:t,type:r,isFreeze:!0,freezeTimeline:[{startTime:d,endTime:0}],renderFreezeTotal:0})}else if(n&&n.isFreeze){n.isFreeze=!1;let d=n.freezeTimeline.pop();if(d){d.endTime=Te();let m=d.endTime-d.startTime;n.freezeTimeline.push(d),n.renderFreezeTotal+=Math.min(5e3,m)}}})}onPlayTrackStart({track:t}){if(!t.isRemote||!this.hitTest(t.room)||t.kind!==N.VIDEO||!t.isRemotePublished)return;let e=`${t.userId}_${t.streamType}`;this._isVideoPlayingEventFiredMap.has(e)||this._isVideoPlayingEventFiredMap.set(e,!1)}getDataFreezeDuration(t){let e={dataFreeze:0,count:0},r=this._dataFreezeMap.get(t);if(r){if(r.isFreezing()){let o=r.durationItemList[r.durationItemList.length-1];o.stop(),o.getDuration()<mc&&r.durationItemList.pop()}e.dataFreeze=this.getTotalDuration(r.durationItemList),e.count=r.durationItemList.length}return e}getRenderFreezeDuration(t){let e=this._renderFreezeMap.get(t),r=0,o=0;if(e)if(!e.isFreeze)r=e.renderFreezeTotal;else{let s=Te(),n=e.freezeTimeline[e.freezeTimeline.length-1],d=s-n.startTime;r=e.renderFreezeTotal+Math.min(d,5e3),o=e.freezeTimeline.length}return{renderFreeze:r,count:o}}getMonitorFreeze(){return this._monitorFreezeData}isBlackStream(t){return this._isVideoPlayingEventFiredMap.has(t)?!this._isVideoPlayingEventFiredMap.get(t):!1}resetMonitor(){this._monitorFreezeData.clear()}hitTest(t){return t===this._room}destroy(){this.uninstallEvents()}},Ag=hp;var Rg=ki(Wi(),1);var cS=[1,0,0,0,1,1,0,1],au=class extends Gt{constructor(t,e){if(super(t,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"mirror",logger:e}),t instanceof Et)try{this.setTexBuffer(cS)}catch(r){t.destroy(new ae({code:q.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${r.message||r}`}))}}draw2d(t,e,r,o,s){if(this.ctx2d){this.ctx2d.save(),this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0);let n=super.draw2d(t,e,r,o,s);return this.ctx2d.restore(),n}return!1}render(t){var e;return(e=this.input)!=null&&e.requestFrame(t)?(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0):!1}};var fp=class{constructor(t,e){this.node=t;this.layout=e;u(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}},cu=class extends Gt{constructor(e,r){super(e,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:r});u(this,"inputs",[])}addInput(e,r){if(this.inputs[r.zIndex])throw new Error("input already exists");let o=new fp(e,r);this.inputs[r.zIndex]=o}resize(e,r){let o=this.inputs.reduce((s,n)=>n?Object.assign(s,{width:Math.max(s.width,n.right),height:Math.max(s.height,n.bottom)}):s,{width:0,height:0});super.resize(o.width,o.height),this.context instanceof Et&&this.inputs.forEach(s=>{if(s){let n=this.layout2texCoords(s);s.positionBuffer?this.changeBufferData(s.positionBuffer,n):s.positionBuffer=this.createBuffer(n)}})}connect(e,...r){return super.connect(e,...r),this.resize(0,0),e}removeInput(e){this.inputs[this.inputs.findIndex(r=>(r==null?void 0:r.node)===e)]=void 0}render(e){let r=this.context.ctx;if(r.clearColor(0,0,0,0),!this.inputs.reduce((s,n)=>(!n||!n.node.requestFrame(e))&&s,!0)&&r){this.useProgram(),r.enable(r.BLEND),r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let s=0;s<this.inputs.length;s++){let n=this.inputs[s];n&&(n.node.useTexture(),this.draw(n.positionBuffer))}return!0}return!1}render2d(e){if(!this.inputs.reduce((o,s)=>(!s||!s.node.requestFrame(e))&&o,!0)&&this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height);for(let o=0;o<this.inputs.length;o++){let s=this.inputs[o];s&&this.draw2d(s.node.image,s.x,s.y,s.width,s.height)}return!0}return!1}getInfo(){let{totalFrames:e,x:r,y:o,width:s,height:n,name:d}=this,m=Date.now(),l=(e-this.lastInfo.totalFrames)/((m-this.lastInfo.timestamp)/1e3)>>0;return this.lastInfo={totalFrames:e,x:r,y:o,width:s,height:n,timestamp:m,fps:l,name:d},Z({parent:this.inputs.filter(g=>g).map(g=>g.node.getInfo())},this.lastInfo)}close(){super.close(),this.inputs.forEach(e=>{var r,o;if(e&&((r=e.node)==null||r.disconnect(),e.positionBuffer&&this.context instanceof Et))try{(o=this.context.ctx)==null||o.deleteBuffer(e.positionBuffer)}catch(s){}})}};var dS=`#version 300 es
|
|
70
102
|
in vec2 a_position;
|
|
71
103
|
in vec2 a_texCoord;
|
|
72
104
|
out vec2 v_texCoord;
|
|
73
105
|
void main() {
|
|
74
106
|
gl_Position = vec4(a_position.x, a_position.y, 0, 1);
|
|
75
107
|
v_texCoord = a_texCoord;
|
|
76
|
-
}`,
|
|
108
|
+
}`,uS=`#version 300 es
|
|
77
109
|
precision highp float;
|
|
78
110
|
uniform sampler2D u_texture;
|
|
79
111
|
uniform sampler2D mask;
|
|
@@ -82,7 +114,7 @@ in vec2 v_texCoord;
|
|
|
82
114
|
out vec4 outColor;
|
|
83
115
|
void main() {
|
|
84
116
|
outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a);
|
|
85
|
-
}`,
|
|
117
|
+
}`,du=class extends Ei{constructor(e,r){super(e,r.input,{name:"vb",create2d:!1,useDefaultProgram:!1,useFbo:!1,createTexture:!0,width:r.width,height:r.height,logger:e.log});u(this,"_bgTexture");u(this,"_waterMarkTexture");u(this,"_lastMaskTexture");u(this,"_lastMaskFbo");u(this,"_textureValid",!1);u(this,"_selfieTextureValid",!1);u(this,"_selfieSegmentation");u(this,"wasm");u(this,"_prePrograme");u(this,"_segmentationMask");u(this,"_weixin",!1);r.selfieSegmentation&&(this._selfieSegmentation=r.selfieSegmentation,this._selfieSegmentation.onResults=this.onPredict.bind(this));try{this.init(r)}catch(o){e.log.error(o),e.destroy(new ae({code:q.VIDEO_MANAGER_ERROR,extraCode:6,message:`init vb node error ${o.message||o}`}))}}init(e){let r=e.Wasm,o=this.context.ctx;if(this.wasm=new r.AllIn1(o),this.wasm.blurRadius=e.blurRadius||3,this.wasm.mirror=!!e.mirror,this.wasm.vbMode=e.bg==="blur"?1:e.bg instanceof HTMLImageElement?2:e.bg==="green"?3:0,e.waterMark){let{x:s,y:n,width:d,height:m}=e.waterMark;this.wasm.setWaterMark(s,n,d,m)}if(e.beautyParams){let{beauty:s,brightness:n,ruddy:d}=e.beautyParams;this.wasm.setBeauty(s,n,d,e==null?void 0:e.width,e==null?void 0:e.height)}if(this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),o.uniform1i(o.getUniformLocation(this.program,"mask"),1),e.bg instanceof HTMLImageElement&&(o.uniform1i(o.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(e.bg)),e.waterMark&&(o.uniform1i(o.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(e.waterMark.image)),o.uniform1i(o.getUniformLocation(this.program,"lastMask"),4),this._weixin){let s=this.context.createShader(o.FRAGMENT_SHADER,uS),n=this.context.createShader(o.VERTEX_SHADER,dS);this._prePrograme=this.context.createProgram(n,s),o.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),o.uniform1i(o.getUniformLocation(this._prePrograme,"mask"),1)}}onPredict(e){var o;let r=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture))),this.useProgram(),this._weixin?this.useTexture():this==null||this._selfieSegmentation.bindTexture(),r.activeTexture(r.TEXTURE1),(o=this._selfieSegmentation)==null||o.bindTexture2d(e),r.activeTexture(r.TEXTURE2),r.bindTexture(r.TEXTURE_2D,this._bgTexture||null),r.activeTexture(r.TEXTURE3),r.bindTexture(r.TEXTURE_2D,this._waterMarkTexture||null),this.useBufferFrame(),r.drawArrays(r.TRIANGLE_STRIP,0,4),this._segmentationMask=e,this.totalFrames++}onFirstFrame(){this.waitingFirstFrame=!1;let e=this.context.ctx;this.useTexture(),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.image)}render(e){var m,l,g,_;let r=this.context.ctx,{image:o}=this;this.tryVideoFrameCallback();let{videoWidth:s,videoHeight:n}=o;if(s===0||n===0||!this.available)return!1;o.width=s,o.height=n;let d=!1;if(this.totalFrames)this._weixin?this.useTexture():(m=this._selfieSegmentation)==null||m.bindTexture(),d=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(this.program)this.useTexture();else return!1;d=this._textureValid,this._textureValid=!0}return this.width!==s||this.height!==n||!d?(this.resize(s,n),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,o)):r.texSubImage2D(r.TEXTURE_2D,0,0,0,r.RGBA,r.UNSIGNED_BYTE,o),this._weixin&&(r.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask&&(r.activeTexture(r.TEXTURE1),(l=this._selfieSegmentation)==null||l.bindTexture2d(this._segmentationMask),r.bindFramebuffer(r.FRAMEBUFFER,this._lastMaskFbo||null)),r.drawArrays(r.TRIANGLE_STRIP,0,4),(g=this._selfieSegmentation)==null||g.bindTexture(),this._segmentationMask?r.copyTexSubImage2D(r.TEXTURE_2D,0,0,0,0,0,s,n):r.copyTexImage2D(r.TEXTURE_2D,0,r.RGBA,0,0,s,n,0)),this.wasm.vbMode&&((_=this._selfieSegmentation)==null||_.send(s,n)),this.totalFrames||(r.activeTexture(r.TEXTURE2),r.bindTexture(r.TEXTURE_2D,this._bgTexture||null),r.activeTexture(r.TEXTURE3),r.bindTexture(r.TEXTURE_2D,this._waterMarkTexture||null),r.drawArrays(r.TRIANGLE_STRIP,0,4)),!1}close(){var r;super.close();let e=this.context.ctx;this._bgTexture&&e.deleteTexture(this._bgTexture),this._waterMarkTexture&&e.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&e.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&e.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&e.deleteProgram(this._prePrograme),(r=this.wasm)==null||r.close()}};var uu=class extends Gt{constructor(e){super(e,{name:"yuv-source",useDefaultProgram:!1,create2d:!1,useFbo:!1,createTexture:!1,logger:e.log,fragmentShaderSource:`
|
|
86
118
|
precision highp float;
|
|
87
119
|
uniform sampler2D ySampler;
|
|
88
120
|
uniform sampler2D uSampler;
|
|
@@ -107,13 +139,4 @@ void main() {
|
|
|
107
139
|
void main() {
|
|
108
140
|
gl_Position = vertexPos;
|
|
109
141
|
textureCoord = texturePos;
|
|
110
|
-
}`});c(this,"yTextureRef");c(this,"uTextureRef");c(this,"vTextureRef");c(this,"Y");c(this,"U");c(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 Su=[s=>{s.codec="avc1.420028"},s=>{delete s.hardwareAcceleration}],_p=(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")};function HT(s){return s[0]===0&&s[1]===0&&s[2]===0&&s[3]===1}var $T=0,mc=class{constructor(i){c(this,"id",$T++);c(this,"trackDoneOB");c(this,"startOB");c(this,"stopOB");c(this,"decoder");c(this,"videoContext");c(this,"gop",0);c(this,"gop_helper",0);c(this,"waitFirstKeyFrame",!0);c(this,"startTimestamp",0);c(this,"startTime",0);c(this,"startPerformanceTime",0);c(this,"inputFrameCount",0);c(this,"decodedFrameCount",0);c(this,"decodeFrameCount",0);c(this,"downgradeLevel",0);c(this,"lastDowngradeTime",0);c(this,"lastFrameDiff",0);c(this,"lastDecodeFrameTimestamp",0);c(this,"config");c(this,"gop_before_configure",[]);c(this,"videoElement");c(this,"type","wasm");c(this,"goodType");c(this,"renderer","2d");c(this,"wasmOption");c(this,"createDecoder");c(this,"_decodeSink");c(this,"isReported",!1);c(this,"track");c(this,"stateChangeOB");c(this,"failedReason");let{track:e,createDecoder:t}=i;if(this.stateChangeOB=Ze(),this.track=e,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=ue(e.availableState,F.OFF),this.stopOB=Ze(),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),de(this.stateChangeOB,Ol((r,o)=>(r!==o&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:r,state:o}),o),"INITIALIZED"),we(this.stopOB),Ae()),this.start()}start(i=0){this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let e=de(this.pipe(this.track),we(this.stopOB),wi());de(e,Ae(()=>{this.track.stat.framesDecoded++},t=>{if(this.track.log.error(`${this.id} play failed: ${t} retryCount: ${i}`),N.addFailedEvent({key:_p(this.type,this.renderer),error:t}),i>4)this.failedReason=t,this.stateChangeOB.next("FAILED");else{if(this.goodType){this.start(i);return}switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":switch(this.renderer){case"webgl":this.changeRenderer("videoFrame");break}}this.start(i+1)}},()=>{this.track.log.warn(`${this.id} decoderOB completed`),N.addSuccessEvent({key:_p(this.type,this.renderer)}),N.addSuccessEvent({key:514704})})),de(e,xi(1),Ae(()=>{this.track.player.handlePlaying("canvas"),this.goodType=this.type,this.stateChangeOB.next("STARTED")}))}mock(i){this._decodeSink?this._decodeSink.error(i):this.start()}close(i){this.stopOB.next(i)}changeRenderer(i){this.renderer=i,this.renderer==="videoFrame"&&!Nd()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(i,e=!1){var a,d;if(this.failedReason)return;this.inputFrameCount++;let t=new Uint8Array(i.data);if(!HT(t)||t.length<5)return this.stateChangeOB.next("FAILED"),this.close(`not h26x frame ${t.subarray(0,5)}`),i;let r=t[4]&31,o=!1;switch(r){case 5:case 7:o=!0;break}if(((a=this.decoder)==null?void 0:a.state)!=="configured")return this.track.log.debug(`not configured ${this.inputFrameCount}`),o&&(this.gop_before_configure=[]),this.gop_before_configure.push({data:i.data,timestamp:i.timestamp,type:i.type}),i;this.gop_before_configure.length>0&&!e&&(this.gop_before_configure.forEach(l=>this.decode(l,!0)),this.gop_before_configure=[]);let{timestamp:n}=i;if(o?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame)if(o)this.waitFirstKeyFrame=!1,this.startTimestamp=n,this.startTime=Date.now(),this.startPerformanceTime=P();else{this.track.log.debug(`wait first key frame ${this.inputFrameCount} ${t.subarray(0,5).join(" ")}`);return}switch(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.decodeFrameCount<10||this.decodeFrameCount%500===0)&&this.track.log.debug(`decode ${this.decodeFrameCount} gop: ${this.gop} ${n} ${(d=i.getMetadata)==null?void 0:d.call(i).rtpTimestamp}`),this.decodeFrameCount++,this.lastDecodeFrameTimestamp=n,this.decoder.decode({data:i.data,type:i.type,timestamp:this.lastDecodeFrameTimestamp});return}return i}checkDowngradeByFrameDiff(){let i=this.downgradeLevel,e=this.decodeFrameCount-this.decodedFrameCount;e>this.lastFrameDiff?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):e<=this.lastFrameDiff&&this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==i&&this.track.log.debug(`downgrade level ${i} to ${this.downgradeLevel} ${this.decodeFrameCount} frameDiff: ${e}, lastFrameDiff: ${this.lastFrameDiff}`),this.lastFrameDiff=e,this.lastDowngradeTime=Date.now()}checkDowngradeByTimestampDiff(i){let e=this.downgradeLevel;this.lastDecodeFrameTimestamp-i>9e4?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==e&&this.track.log.debug(`downgrade level ${e} to ${this.downgradeLevel}`)}pipe(i){return e=>p(this,null,function*(){this._decodeSink=e;let t,r=i.mediaTrack;e.defer(()=>{var a;r&&(i.player.setCanvas(),i.setInputMediaStreamTrack(r)),t==null||t.close(),(a=this.videoContext)==null||a.destroy(),delete this._decodeSink});let{renderer:o,type:n}=this;i.log.info(`decoder type: ${this.type} renderer: ${this.renderer}`);try{switch(n){case"wasm":t=this.createDecoder(n,this.wasmOption);break;case"webCodecs":for(let d=0;d<=Su.length;d++){let{supported:l}=yield VideoDecoder.isConfigSupported(this.config);if(l)break;if(d===Su.length){e.error(3);return}Su[d](this.config)}t=this.createDecoder(n);break;default:throw new Error("not supported yet")}let a=0;if(t.on("videoFrame",d=>{this.decodedFrameCount++,a++,(a<=10||a%500===0)&&i.log.debug(`frame ${a} ${this.decodedFrameCount}/${this.decodeFrameCount} decoded ${d.timestamp}`),Date.now()-this.lastDowngradeTime>5e3&&(this.type==="webCodecs"?this.checkDowngradeByFrameDiff():this.type==="wasm"&&this.checkDowngradeByTimestampDiff(d.timestamp)),e.next(d)}),t.on("error",d=>{i.log.error(d),e.error(n==="webCodecs"?4:8)}),yield t.initialize(this.videoElement),!this._decodeSink)return;if(t.configure(this.config),n==="wasm"&&o==="webgl"){this.videoContext=new De({frameRate:15,logger:i.log,name:i.userId}),this.videoContext.create(),this.videoContext.on(De.UNAVAILABLE,l=>{i.log.error(l),e.error(7)});let d=new hc(this.videoContext);t.on("videoCodecInfo",l=>d.resize(l.width,l.height)),t.on("videoFrame",l=>{({y:d.Y,u:d.U,v:d.V}=l),this.downgradeLevel===1?this.decodedFrameCount%2===0&&d.render(this.decodedFrameCount):d.render(this.decodedFrameCount)}),i.source=d,i.player.setCanvas(this.videoContext._canvas,2)}else if(o==="videoFrame"){i.player.setCanvas();let d=new MediaStreamTrackGenerator({kind:"video"}),l=d.writable.getWriter();i.setInputMediaStreamTrack(d),t.on("videoFrame",u=>l.write(u))}else{this.videoContext=new Je({frameRate:15,logger:i.log,name:i.userId}),this.videoContext.create({alpha:!1});let d=this.videoContext.createVideoImageSource();t.on("videoFrame",u=>{try{d.image=u,d.update()}catch(h){delete this.goodType,i.log.error(h),e.error(11)}});let l=new Lr(this.videoContext,{name:"remotePlayer",logger:i.log});d.connect(l),i.source=d,i.player.setCanvas(this.videoContext._canvas,2)}this.decoder=t}catch(a){i.log.error(a),e.error(n==="webCodecs"?2:6)}})}};var rn=class extends gp.EventEmitter{constructor(e){super();this.room=e;c(this,"videoContext");c(this,"_glVideoContext");c(this,"_2dVideoContext");c(this,"destination");c(this,"smallVideoContext");c(this,"smallDestination");c(this,"smallTrackSource");c(this,"smallImageSource");c(this,"_isMirror",!1);c(this,"cameraTrack");c(this,"cameraNode");c(this,"mirrorNode");c(this,"mixNode");c(this,"screenTrack");c(this,"screenNode");c(this,"selfModel",!1);c(this,"blurRadius",3);c(this,"arTrack");c(this,"Wasm");c(this,"waterMarkNode");c(this,"_waterMarkOption");c(this,"watermarkImageList",[]);c(this,"_beautyParams");c(this,"isUsingArTrack",!1);c(this,"_isMixScreen",!1);c(this,"_virtualBackground");c(this,"_virtualBackgroundAbortCallback");c(this,"virtualBackgroundInstance");c(this,"_bgAssetPath");c(this,"log",C.createLogger({id:"vm"}));c(this,"_checkId",0);c(this,"_use2d",!1);c(this,"_autoSwitchRenderMode",!0);c(this,"_selfieSegmentation");c(this,"encodePipeline",[]);c(this,"decodePipeline",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new Je({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 Je({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new De({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(De.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(Xi||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 De({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()}setSmallVideo(e,t){if(e){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new Fa(this.smallVideoContext,e,this.log),this.smallVideoContext.on(De.UNAVAILABLE,r=>{this.log.warn("small video context lost",r)})}if(this.smallVideoContext.frameRate=e.frameRate,this.smallDestination.resolution=e,t)this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=t:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(t),this.smallImageSource.resize(t.width,t.height),this.smallImageSource.connect(this.smallDestination));else if(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource)this.smallTrackSource.replaceTrack(this.initialTrack);else{this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource");let{width:r,height:o}=this.cameraTrack.settings;this.smallTrackSource.resize(r,o),this.smallTrackSource.connect(this.smallDestination)}}else this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource)}_setMainOutput(e){var t;try{let r=this.cameraTrack,{small:o,player:n}=r;this.setSmallVideo(o,e),Xi&&n.setCanvas(e);let a=e&&((t=this.destination)==null?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),a=this.arTrack),this._selfieSegmentation&&e&&!this._use2d&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),this.log.info(`set main output ${a?a.label:"no output track"}`),r.setOutputMediaStreamTrack(a)}catch(r){this.log.error("set main output failed",r)}}update(e=!1){return p(this,null,function*(){var o,n,a;if(!this.cameraTrack||!this.initialTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:t,profile:r}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log})),ut===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof Ui?(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 Ui?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(t.width,t.height)):e&&this.cameraNode&&this.destination?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():this.destination=new Ba(this.videoContext,{name:"mainDestination",logger:this.log}),this.cameraNode=new uc(this.videoContext,{input:this.initialTrack,width:t.width,height:t.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=r.frameRate,this._use2d){let d=this.cameraNode;d.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new dc(this.videoContext,this.log)),d=d.connect(this.mirrorNode),d.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new lc(this.videoContext,this.log),d.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):(o=this.waterMarkNode)==null||o.resize(t.width,t.height),(n=this.waterMarkNode)==null||n.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource")),(a=this.screenNode)==null||a.connect(this.mixNode,{zIndex:0}),d=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)),d.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 ct)return this.log.info("change screen input",(t=e.mediaTrack)==null?void 0:t.label),this.setScreenTrack(e);if(e instanceof We)return this.log.info("change video input",(r=e.mediaTrack)==null?void 0:r.label),this.setCameraTrack(e);if(e instanceof di){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 ct?((t=this.screenNode)==null||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof We?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof di&&e.source&&e.source.context.destroy()}setCameraTrack(e){return p(this,null,function*(){this.cameraTrack=e,this.update(!0)})}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 p(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:I.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:d,width:l,height:u})=>{o.drawImage(n,a,d,l,u)}),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 p(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return p(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return p(this,null,function*(){var h,f;let t;try{t=yield Yr((e==null?void 0:e.imageElement)||e.imageUrl)}catch(g){throw new b({code:I.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:d="watermark",zIndex:l=2}=e;this.watermarkImageList.some(g=>g.type===d)?(this.watermarkImageList=this.watermarkImageList.filter(g=>g.type!==d),this.pushWaterMarkImageList({x:r,y:o,width:n,height:a,image:t,zIndex:l,type:d,imageUrl:e.imageUrl}),t=yield this.getWatermarkImage((h=this.cameraTrack)==null?void 0:h.settings.width,(f=this.cameraTrack)==null?void 0:f.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:d,imageUrl:e.imageUrl}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(g,D)=>g==="imageUrl"?void 0:D))})}deleteWatermark(e="watermark"){return p(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 p(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 p(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:I.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 p(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 mc(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([Ea(function(e){this.log.error("update failed",e)})],rn.prototype,"update",1);var GT=0;var pc=class extends F{constructor(e){super("room");c(this,"seq",++GT);c(this,"sdkAppId");c(this,"userId");c(this,"userSig");c(this,"privateMapKey");c(this,"latencyLevel");c(this,"tinyId");c(this,"scene");c(this,"roomId");c(this,"useStringRoomId");c(this,"role","anchor");c(this,"joinParams",null);c(this,"localTracks",new Set);c(this,"enableAutoPlayDialog",!0);c(this,"autoReceiveAudio",!0);c(this,"autoReceiveVideo",!0);c(this,"proxy_ws");c(this,"proxy_wt");c(this,"proxy_unified");c(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}});c(this,"keyPointManager");c(this,"audioManager");c(this,"videoManager");c(this,"callDurationCalculator");c(this,"badCaseDetector");c(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null});c(this,"videoDecodeFallbackType");c(this,"_isUsingCachedSchedule",!1);c(this,"_log",C.createLogger({id:`r${this.seq}`}));c(this,"_joinedTimestamp",0);c(this,"_sdkType");c(this,"heartbeatReport");c(this,"quality");c(this,"enableSEI");c(this,"isDestroyed",!1);this.useStringRoomId=!!e.useStringRoomId,_e(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),_e(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),_e(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new mp({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new pp({room:this}),this.badCaseDetector=new fp({room:this}),this.audioManager=new Ra(this),this.videoManager=new rn(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 p(this,null,function*(){return this.publish(e)})}removeTrack(e){return p(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return p(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(Z(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(rt(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?(Ja([a,a]),ar(`https://${a}`)):(o&&ar(o),n&&Ja(n))}S.once(E.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:nr.main,sched_back_domain:nr.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return p(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(t=>{e[t.userId]=t.remoteAudioTrack.stat}),e})}getTransportStats(){return p(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 p(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:I.INVALID_OPERATION,message:V({key:U.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Pe.INVALID_DESTROY),new b({code:I.INVALID_OPERATION,message:V({key:U.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,S.emit(E.ROOM_DESTROY,{room:this})}schedule(e,t){return p(this,null,function*(){var o,n,a;let r=P();try{let{isCached:d,result:l,detailCost:u}=yield $l({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:Oe,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:t,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=d,this._log.info(`schedule cache:${+d} ${Tt(l,{keysToExclude:["username","credential"]})}`),d&&S.once(E.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=v(v({},this.scheduleResult),l),Y((o=l.config)==null?void 0:o.retryCount)&&kc(l.config.retryCount),Z((n=l.config)==null?void 0:n.loggerDomain)&&ar(l.config.loggerDomain),this.videoDecodeFallbackType=((a=l.config)==null?void 0:a.videoDecodeFallback)||this.videoDecodeFallbackType,S.emit(E.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:u}),N.addSuccessEvent({key:521700,cost:P()-r,split:50})}catch(d){throw N.addFailedEvent({key:521700,error:d}),d}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}};var Dp=Be(ze());var Iu=Be(uu());var Tp=s=>{let i=Se(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&&!T(t.ssrcs[0].id)){let n=Number(t.ssrcs[0].id),a=Number((o=t.ssrcs.filter(d=>d.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 Ep(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 WT(){return p(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=Se(i.sdp),t=Ep(e.media[0]);return s.close(),t})}var Sp=(s,i)=>p(void 0,null,function*(){var d;let e=Se(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};(d=r.rtcpFb)==null||d.forEach(({payload:l,type:u,subtype:h})=>{if(l===n.payload){let f={id:u,params:[]};h&&f.params.push(h),n.rtcpfb.push(f)}}),t.audio.codecs.push(n);let a=["h264","vp8"];return i&&a.shift(),t.video.codecs=[...Ep(o)].filter(l=>a.includes(l.codec.toLocaleLowerCase())),t.video.decoders=(yield WT()).filter(l=>["h264","vp8"].includes(l.codec.toLocaleLowerCase())),t}),Ip=({serverAbility:s,clientAbility:i,offerSDP:e,enableCustomMessage:t})=>{let r=Se(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(Au({mid:a,serverAbility:s,clientAbility:i,parsedOffer:r}))}),t&&o.media.push(r.media.find(a=>a.mid==="dc")),Ct(o)},Au=({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=>{Fr(o,a)})}else{let n=i.video.codecs.findIndex(d=>d.codec.toLowerCase()===(i.useVp8?"vp8":"h264")),a=i.video.codecs[n]||e.video.codecs[0];Fr(o,a)}return o},Fr=(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 JT(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 jT(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 qT(s){s.type===m.VIDEO&&s.fmtp&&s.fmtp.forEach(i=>{i.config.includes("apt")||(i.config+=";sps-pps-idr-in-keyframe=1")})}function XT(s){s.type===m.AUDIO&&s.fmtp&&s.fmtp.forEach(i=>{i.config+=";sprop-stereo=1;stereo=1"})}var Ap=(s,i,e)=>{let t=Iu.default.parse(s);return t.media.forEach((r,o)=>{var n;if((r.type===m.AUDIO||r.type===m.VIDEO)&&(jT(r),qT(r),XT(r),JT(r),r.type===m.VIDEO)){if(o<4)r.payloads="",r.fmtp=[],r.rtp=[],r.rtcpFb=[],i.video.codecs.forEach(a=>Fr(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(d=>Fr(r,d))}}(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")}),Iu.default.write(t)};var Cp=Be(ze());var fc=class extends Cp.EventEmitter{constructor(e){super();this.room=e;c(this,"mainFpsHealth",1);c(this,"mainBitrateHealth",1);c(this,"badMainBitrateHealthCount",0);c(this,"lastEmitBadHealthTime",0);c(this,"log");!he&&Qe&&S.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(){S.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};c(fc,"EVENT_BAD_HEALTH","bad_health");var Rp=fc;function yp({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 bp(s,i,e){return new TransformStream({transform(t,r){let o=t;videoDecodePipeline.forEach(n=>{o=n({frame:o,onSEI:a=>{a.forEach(d=>{self.postMessage({type:"sei",seiPayloadType:d.seiPayloadType,data:d.seiPayload.buffer,userId:s,streamType:i})})},onDump:()=>{self.postMessage({type:"dump",isAudio:e,data:o.data,userId:s,streamType:i})}})}),r.enqueue(o)}})}function Np(s){let i=[Li],e=[Kl,Ql,Yl,zl,yp,bp],t=()=>{let l=[],u=[],h=[];self.onmessage=f=>{f.data.type==="sei"&&(f.data.isMain?(l.push(f.data.data),f.data.small&&h.push(f.data.data)):u.push(f.data.data))},self.onrtctransform=f=>{let{options:g}=f.transformer,D=g.isReceiver?bp(g.userId,g.streamType,g.isAudio):yp({isAudio:g.isAudio,seiMessageList:g.isMain?g.small?h:l:u,isMain:g.isMain});f.transformer.readable.pipeThrough(D).pipeTo(f.transformer.writable)}},r=`const videoEncodePipeline=[${s.videoEncodePipeline.toString()}];
|
|
111
|
-
const videoDecodePipeline=[${s.videoDecodePipeline.toString()}];
|
|
112
|
-
const audioEncodePipeline = [${s.audioEncodePipeline.toString()}];
|
|
113
|
-
const audioDecodePipeline = [${s.audioDecodePipeline.toString()}];`,o=`(()=>{${i.map(l=>`const ${l.name}=(()=>${l.toString()})()`).join(`
|
|
114
|
-
`)}
|
|
115
|
-
${e.map(l=>l.toString()).join(`
|
|
116
|
-
`)};(${t})();${r}})()`,n=new Blob([o],{type:"text/javascript"}),a=URL.createObjectURL(n),d=new Worker(a);return URL.revokeObjectURL(a),d}var ui=(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))(ui||{}),Op=0,kp=!1,zT=new Set,QT=s=>Op>2&&!kp&&zT.size===0&&s,YT=1,Bt=class extends Dp.default{constructor({signalChannel:e,room:t,enableCustomMessage:r}){super();c(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0});c(this,"currentState","DISCONNECTED");c(this,"_room");c(this,"_signalChannel");c(this,"_peerConnection",null);c(this,"_datachannel",null);c(this,"_enableCustomMessage");c(this,"_log");c(this,"_downlinkMIDMap",new Map);c(this,"_downlinkMIDUserIDMap",new Map);c(this,"_reconnectionTimer",-1);c(this,"reconnectionCount",0);c(this,"clientAbility");c(this,"_serverAbility",null);c(this,"addDownlinkQueue",new Set);c(this,"removeDownlinkQueue",new Set);c(this,"_parsedAnswer",null);c(this,"_updateSDPPromise",null);c(this,"_waitForPCConnectedPromise");c(this,"clearConnectTimeout");c(this,"_isSDPLogged",!1);c(this,"enableInsertableStreams",!1);c(this,"insertableStreamsAbortMap",new Map);c(this,"receiverRemoteTrackMap",new WeakMap);c(this,"scriptTransformWorker");c(this,"_isRelayTried",!1);c(this,"_rttOverCount",0);c(this,"originOffer",null);this._room=t,this._enableCustomMessage=r,this._signalChannel=e,this._log=C.createLogger({id:`spc${YT++}`,userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(Di?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?Tp(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(){sa&&(this.scriptTransformWorker=Np({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}getPeerConnectionConfig(e){var o;let t={encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:e,iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},r=(o=this._peerConnection)==null?void 0:o.getConfiguration().encodedInsertableStreams;return Nn(r)&&(t.encodedInsertableStreams=r),this._log.debug("getPeerConnectionConfig",JSON.stringify(t)),t}initialize(e){return p(this,null,function*(){var r;let t;try{return this._peerConnection=new RTCPeerConnection(this.getPeerConnectionConfig(e)),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let o=this._peerConnection.iceConnectionState;this._log.debug(`ice state: ${o}`),o==="checking"&&this.stat.iceStartTime===0?this.stat.iceStartTime=Date.now():o==="connected"&&this.stat.iceEndTime===0?(this.stat.iceEndTime=Date.now(),this._signalChannel.clearBakRelayIps(),N.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):o==="failed"&&N.addFailedEvent({key:521711})},this._peerConnection.onsignalingstatechange=()=>{var n;let o=((n=this._peerConnection)==null?void 0:n.signalingState)||"";this._log[o==="closed"?"debug":"info"](`signaling state: ${o}`)},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=o=>this.emit("track",o),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=o=>{let n=new Ru(o.data);this.emit("data_channel_msg",{data:n})},this._datachannel.onerror=o=>{this._log.warn("datachannel error",o)}),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}),t=yield this._peerConnection.createOffer(),this.clientAbility=yield Sp(t.sdp,((r=this._room.scheduleResult.config)==null?void 0:r.remove264FromSDP)||!1),this.originOffer=t,this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:o}=this;o&&(this._log.debug(`dtls state: ${o.state}`),o.state==="connecting"&&this.stat.dtlsStartTime===0?this.stat.dtlsStartTime=Date.now():o.state==="connected"&&this.stat.dtlsEndTime===0&&(this.stat.dtlsEndTime=Date.now()))}),N.addSuccessEvent({key:521707}),this.clientAbility}catch(o){throw N.addFailedEvent({key:521707,error:o}),this._log.error(`initialize failed ${o}
|
|
117
|
-
offer: ${t==null?void 0:t.sdp}`),o}})}setIceServers(e){return p(this,null,function*(){var t;if(!(!this._peerConnection||e.length===0))try{if(this._log.info("setIceServers",JSON.stringify(e)),this._peerConnection.setConfiguration(this.getPeerConnectionConfig(e)),(t=this._peerConnection)!=null&&t.localDescription||!this.originOffer){this._log.warn("setIceServers already has localDescription or no origin Offer");return}yield this.setOffer(this.originOffer)}catch(r){this._log.warn("setIceServers error ",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 p(this,null,function*(){var r,o,n;try{if(this.currentState==="CONNECTED")return;!((r=this._peerConnection)!=null&&r.localDescription)&&this.originOffer&&(yield this.setOffer(this.originOffer));let a=P(),d={type:"answer",sdp:Ip({serverAbility:e,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableCustomMessage})};this._serverAbility=e,yield this.setAnswer(d),yield this.waitForPeerConnectionConnected();let l=((o=this._room.scheduleResult.config)==null?void 0:o.priority)||((n=this._room.joinParams)==null?void 0:n.priority)||new URLSearchParams(location.search).get("priority");l&&this.setPriority(l),t||N.addSuccessEvent({key:521703,cost:P()-a})}catch(a){let d=a instanceof b&&a.code===I.API_CALL_ABORTED;throw d||this._log.error(`connect failed: ${a}`,e),this.reset(),!d&&!this.isReconnecting&&(N.addFailedEvent({key:521703,error:a}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),a}})}reconnect(){return p(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(Ce.CONNECTED,this.reconnect,this);return}try{this.reconnectionCount+=1,this._log.warn(`reconnect() trying [${this.reconnectionCount}]`),this.reset();let e=this._signalChannel.getBackupRelayIpPair(),t=yield this.initialize(this._room.getIceServers(e!=null&&e.iceServer?[e.iceServer]:[])),r=v({ability:t},e),o=yield this._signalChannel.sendWaitForResponse({command:Q.REBUILD_PEER_CONNECTION,responseCommand:H.REBUILD_PEER_CONNECTION_RES,data:r,enableLog:!1});if(o.data.code!==0)throw new b({code:o.data.code,message:o.data.message});yield this.connect(o.data.data.ability,!0),N.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),S.emit(E.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(e){if(!this.isReconnecting)return;if(e!=null&&e.message.includes("timeout")){let t=Nt(this.reconnectionCount);this._log.warn(`reconnect() timeout, try again after ${t/1e3}s`),yield Ei(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>=fi()&&this._log.warn(`SDK has tried reconnect for ${fi()} times, but all failed, please check your network`),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}})}getPeerConnection(){return this._peerConnection}startReconnection(){return p(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(Ce.CONNECTED,this.reconnect,this),this.currentState==="RECONNECTING"&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var e;!this.isReconnecting&&((e=this._peerConnection)==null?void 0:e.connectionState)===me.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===me.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(e.target.connectionState===me.FAILED||e.target.connectionState===me.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(e.target.connectionState===me.CONNECTED||e.target.connectionState===me.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),S.emit(E.SINGLE_CONNECTION_STAT,{room:this._room,stat:{ice:this.stat.iceEndTime-this.stat.iceStartTime,dtls:this.stat.dtlsEndTime-this.stat.dtlsStartTime,peerConnection:this.stat.peerConnectionEndTime-this.stat.peerConnectionStartTime}}),this.logSelectedCandidate(),this.emitConnectionStateChangedEvent("CONNECTED"))}getDTLSTransportState(){if(!this._peerConnection)return yt;let e=null;return!Ki()||this._peerConnection.getSenders().length===0?yt:(e=this._peerConnection.getSenders()[0].transport,!Ar()||this._peerConnection.getReceivers().length===0?yt:e?e.state:yt)}emitConnectionStateChangedEvent(e){e!==this.currentState&&(this.currentState==="RECONNECTING"&&e==="CONNECTING"||(this.emit(ui.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:e}),this.currentState=e))}logSelectedCandidate(){return p(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&&Sn(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=d=>{d.state==="CONNECTED"&&(clearTimeout(a),n(),e())},o=({room:d})=>{d===this._room&&(clearTimeout(a),n(),t(new b({code:I.API_CALL_ABORTED,message:V({key:U.CONNECTION_ABORTED,data:"leave room"})})))},n=()=>{S.off(E.LEAVE_SUCCESS,o,this),this.off(ui.CONNECTION_STATE_CHANGED,r,this)},a=setTimeout(()=>{n();let d=new b({code:I.API_CALL_TIMEOUT,message:"connection timeout"});Op+=1,QT(this._signalChannel.isConnected)&&(this._log.warn("firewall restriction"),kp=!0,this.emit(ui.FIREWALL_RESTRICTION)),t(d)},qs);this.clearConnectTimeout=()=>{n(),clearTimeout(a),delete this.clearConnectTimeout},S.on(E.LEAVE_SUCCESS,o,this),this.on(ui.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 p(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(f=>f.direction==="inactive").slice(0,3).map(f=>(f.direction=m.TRANSCEIVER_DIRECTION_RECVONLY,Number(f.mid)));this._parsedAnswer||(this._parsedAnswer=Se(this._peerConnection.remoteDescription.sdp));let n=this._parsedAnswer.media.filter(f=>{var g;return(g=f.ssrcs)==null?void 0:g.find(D=>{var _;return(_=D.value)==null?void 0:_.includes(r)})}),a,d,l;if(n.length===3)a=n[0],d=n[1],l=n[2];else if(o.length===3)a=this._parsedAnswer.media.find(f=>Number(f.mid)===Number(o[0])),d=this._parsedAnswer.media.find(f=>Number(f.mid)===Number(o[1])),l=this._parsedAnswer.media.find(f=>Number(f.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 f=Au({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:Se(this._peerConnection.localDescription.sdp),isDownlink:!0});d=JSON.parse(JSON.stringify(f)),l=JSON.parse(JSON.stringify(f)),a.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(a),d.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(d),l.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(l)}a.direction=m.TRANSCEIVER_DIRECTION_SENDONLY;let u=`${r}-${e.audio}`;a.ssrcs=[{id:e.audio,attribute:"cname",value:`${u}`},{id:e.audio,attribute:"msid",value:`${u}-${m.MAIN} ${u}-audio`}],d.direction=m.TRANSCEIVER_DIRECTION_SENDONLY,d.ssrcs=[{id:e.video,attribute:"cname",value:`${u}`},{id:e.video,attribute:"msid",value:`${u}-${m.MAIN} ${u}-bigvideo`},{id:e.videoRtx,attribute:"cname",value:`${u}`},{id:e.videoRtx,attribute:"msid",value:`${u}-${m.MAIN} ${u}-bigvideo`}],d.ssrcGroups=[{semantics:"FID",ssrcs:`${e.video} ${e.videoRtx}`}],l.direction=m.TRANSCEIVER_DIRECTION_SENDONLY;let h=`${u}-aux`;l.ssrcs=[{id:e.auxiliary,attribute:"cname",value:h},{id:e.auxiliary,attribute:"msid",value:`${h} ${u}-aux${m.VIDEO}`},{id:e.auxiliaryRtx,attribute:"cname",value:`${h} ${u}-aux${m.VIDEO}`},{id:e.auxiliaryRtx,attribute:"msid",value:`${h} ${u}-aux${m.VIDEO}`}],l.ssrcGroups=[{semantics:"FID",ssrcs:`${e.auxiliary} ${e.auxiliaryRtx}`}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map(f=>f.mid).join(" ")),this._downlinkMIDMap.set(t,[a.mid,d.mid,l.mid]),this._downlinkMIDUserIDMap.set(a.mid,t),this._downlinkMIDUserIDMap.set(d.mid,t),this._downlinkMIDUserIDMap.set(l.mid,t)}removeDownlink(e){return p(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=Se(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 p(this,null,function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:r,smallVideo:o,auxVideo:n}=e;try{if(Ro()){let a=this._peerConnection.getSenders().slice(0,4);for(let l=0;l<a.length;l++){let u=a[l],h;l===0&&t?h=t:l===1&&r?h=r:l===2&&o?h=o:l===3&&n&&(h=n),h&&(yield this.setSenderMaxBitrate(u,h))}let d=!1;r&&a[1].track&&(d=this.setStartBitrate(1,r)),n&&a[3].track&&(d=this.setStartBitrate(3,n)||d),d&&(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=Se(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=Se(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=Se(this._peerConnection.remoteDescription.sdp));let a=se?"TIAS":"AS";e&&(n.media[0].bandwidth=[{type:a,limit:se?e*1e3:e}],this._parsedAnswer.media[0].bandwidth=[{type:a,limit:se?e*1e3:e}]),t&&(n.media[1].bandwidth=[{type:a,limit:se?t*1e3:t}],this._parsedAnswer.media[1].bandwidth=[{type:a,limit:se?t*1e3:t}]),r&&(n.media[2].bandwidth=[{type:a,limit:se?r*1e3:r}],this._parsedAnswer.media[2].bandwidth=[{type:a,limit:se?r*1e3:r}]),o&&(n.media[3].bandwidth=[{type:a,limit:se?o*1e3:o}],this._parsedAnswer.media[3].bandwidth=[{type:a,limit:se?o*1e3:o}]);let d={type:"offer",sdp:Ct(n)};return this.updateSDP({localDescription:d})}setScaleResolutionDownBy(e,t,r){let o=e.getParameters();(!o.encodings||o.encodings.length===0)&&(o.encodings=[{}]);let n=o.encodings[0].scaleResolutionDownBy;if(T(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)}setDegradationPreference(e,t,r){if(Qe&<<83||Te&&Zc(Xt,"12.1")||se&&to<138)return;let o=e.getParameters(),n="balanced";if(t==="motion"?n="maintain-framerate":t==="detail"&&(n="maintain-resolution"),o.degradationPreference===n)return;let a=`setDegradationPreference ${r} ${n}`;return this._log.info(a),o.degradationPreference=n,e.setParameters(o).catch(d=>this._log.warn(`${a} failed: ${d}`))}updateSDP({localDescription:e}={}){if(!this._parsedAnswer)return Promise.resolve();let t=Ct(this._parsedAnswer);return this._updateSDPPromise=new Promise((r,o)=>p(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(d){this._log.error(d),!this._isSDPLogged&&this._peerConnection&&(this._log.warn(`current offer: ${this.filterSDPDirection((n=this._peerConnection.localDescription)==null?void 0:n.sdp)}
|
|
118
|
-
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)}
|
|
119
|
-
next answer: ${this.filterSDPDirection(t)}`),this._log.warn(`offer: ${e==null?void 0:e.sdp}`),this._log.warn(`answer: ${t}`),this._log.warn(`transceivers: ${JSON.stringify(this._peerConnection.getTransceivers().map(({mid:l,currentDirection:u,direction:h,stopped:f})=>({mid:l,currentDirection:u,direction:h,stopped:f})))}`),this._log.warn(`parsedAnswer: ${JSON.stringify(this._parsedAnswer)}`),this._isSDPLogged=!0),this._updateSDPPromise=null,o(d)}})),this._updateSDPPromise}setTransceiverDirection(e,t){return p(this,null,function*(){if(!se||!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===K.INACTIVE&&n===K.RECVONLY&&(this._parsedAnswer.media[o].direction=e),e===K.SENDONLY&&n===K.INACTIVE&&(this._parsedAnswer.media[o].direction=K.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(e=""){return Se(e).media.map(r=>r.direction)}setOffer(e){this._log.info("setting offer");let t=Ap(e.sdp,this.clientAbility,this._serverAbility);return this._log.debug(t),this._peerConnection.setLocalDescription({type:"offer",sdp:t})}setAnswer(e){return this._log.info("setting answer"),this._log.debug(e.sdp),this._peerConnection.setRemoteDescription(e)}switchVideoEncoder(e){return p(this,null,function*(){if(!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=[],Fr(r,n),t=!0)}}),t&&(this._log.warn(`switch video encoder to ${e}`),yield this.updateSDP())})}useHWEncoder(e=!0,t){return p(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let r=!1,o=[];T(t)?o=this._parsedAnswer.media.slice(1,4):t===2?o.push(this._parsedAnswer.media[1]):t===3?o.push(this._parsedAnswer.media[2]):t===7&&o.push(this._parsedAnswer.media[3]),o.forEach(n=>{var a;if(n.type===m.VIDEO){let d;e&&this.is42001fSupported?d=this.clientAbility.video.codecs.find(l=>l.fmtp.includes("42001f")):e||(d=this._serverAbility.video.codecs.find(l=>l.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264"))),d&&!((a=n.payloads)!=null&&a.includes(String(d.payload)))&&(n.fmtp=[],n.payloads="",n.rtp=[],n.rtcpFb=[],Fr(n,d),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,this.originOffer=null}close(){this._log.info("close pc"),this.removeRTCListener(),this.insertableStreamsAbortMap.forEach(e=>Jt(e.abort)&&e.abort("destroy")),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners(),this._room.healthDetector.off("1",this.onBadHealth,this)}getReceiversByUserId(e){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(e)||[]).map(r=>t[r])}get isUsingRelay(){return this._room.getIceTransportPolicy()==="relay"}detectTCPAndUDP({uplinkRTT:e,downlinkRTT:t}){var u;if(this.currentState!=="CONNECTED"||this._isRelayTried&&!this._room.forceRelay||this._room.getIceServers().length===0)return;let r=this._signalChannel.rtt,o=Math.max(e,t),{rttRatioThreshold:n,rttThreshold:a}=((u=this._room.scheduleResult.config)==null?void 0:u.useTurnTcpInfo)||{};if(!n||!a||!r||!o)return;let d=Math.floor(o/r),l=(this._isRelayTried||d>n)&&o>a;if(!l){this._rttOverCount=0;return}++this._rttOverCount<5||(this._log.warn(`detectTCPAndUDP ws-rtt: ${r} upRTT: ${e} downRTT: ${t} ratio: ${d} over-count: ${this._rttOverCount} isOver: ${l} isRelayTried: ${this._isRelayTried} force-relay: ${this._room.forceRelay}`),!this.isUsingRelay&&!this._isRelayTried?(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0)):this._room.forceRelay&&this.switchRelay(!1))}switchRelay(e,t=!1){return p(this,null,function*(){if(this.isUsingRelay===e)return;let r=e?"relay":"udp",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([Aa("reconnect")],Bt.prototype,"startReconnection",1),y([Mi(e=>e.userId)],Bt.prototype,"addDownlink",1),y([Mi(e=>e)],Bt.prototype,"removeDownlink",1),y([si(!0)],Bt.prototype,"updateSDP",1),y([at(521712,!1)],Bt.prototype,"setOffer",1),y([at(521713,!1)],Bt.prototype,"setAnswer",1);var Cu=class{constructor(i){c(this,"tag");c(this,"len");c(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}},Ru=class{constructor(i){c(this,"tinyId");c(this,"data");let e=new DataView(i),t=0,r=[];for(;t<e.byteLength;){let o=e.getUint16(t+2),n=new Cu(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)})}},vp=new Set;function Hr(){let s=Math.floor(Math.random()*4294967296);return vp.has(s)?Hr():(vp.add(s),s)}var Mp=Be(ze());var $r=class extends Mp.default{constructor(e){super();c(this,"userId");c(this,"tinyId");c(this,"_sdpSemantics");c(this,"_isUplink");c(this,"_room");c(this,"_log");c(this,"_currentState","DISCONNECTED");c(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:(S.emit(E.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:e,remoteUserId:this._isUplink?void 0:this.userId}),this.emit("connection-state-changed",{prevState:this._currentState,state:e}),this._currentState=e,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}getCurrentState(){return this._currentState}get isH264(){var e,t;return!!((t=(e=this._peerConnection)==null?void 0:e.remoteDescription)!=null&&t.sdp.includes("H264"))}};var sn=class extends $r{constructor(e){super(L(v({},e),{isUplink:!0}));c(this,"localMainAudioTrack",null);c(this,"localMainVideoTrack",null);c(this,"localAuxAudioTrack",null);c(this,"localAuxVideoTrack",null);c(this,"_isPublishingAux",!1);c(this,"_publishingLocalAudioTrack");c(this,"_publishingLocalVideoTrack");c(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});c(this,"_flag",0);c(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:d}=this.singlePC.uplinkSSRC;return{audio:e||0,video:t||0,videoRtx:r||0,small:o||0,smallRtx:n||0,auxiliary:a||0,auxiliaryRtx:d||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]} ${Ri()} ${_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&&(Yt()?(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(d=>{d.track&&(d.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&Wi),bigVideo:!!(this.flag&Gi),smallVideo:!!(this.flag&Js),auxVideo:!!(this.flag&cr)}}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,d;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}),(d=this._publishingLocalVideoTrack)==null||d.emit("connection-state-changed",{prevState:r,state:e}))),o}onVideoEncodeFailed(e){var t;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"),this.singlePC.switchVideoEncoder("vp8")))}publish(o){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t,isAuxiliary:r}){var l,u,h,f,g,D,_;if(!this.singlePC)return;this.installEvents(),yield Promise.all([this.singlePC.waitForPeerConnectionConnected(),this.singlePC.waitForReconnected()]);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:I.NOT_SUPPORTED_H264,message:V({key:U.NOT_SUPPORTED_H264ENCODE})});this.singlePC.isUsingH264&&!this.singlePC.isH264EncodeSupported&&this.singlePC.isVP8EncodeSupported&&(this._log.warn("h264 encoder not supported"),yield this.singlePC.switchVideoEncoder("vp8")),he&&as()===115&&t.profile.width*t.profile.height<=640*360&&(this._log.warn("fallback video to 480p"),t.setProfile(gt["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 d;if(t&&!r&&t.small&&(d=this._room.videoManager.smallTrack,n.smallVideo=!0),yield this._signalChannel.sendWaitForResponseWithRetry({command:Q.SPC_PUBLISH,responseCommand:H.SPC_PUBLISH_RESULT,data:L(v({},this.singlePC.uplinkSSRC),{state:n,muteState:a}),retries:3}),yield this.publishByTransceiver({localAudioTrack:e,localVideoTrack:t,smallTrack:d,isAuxiliary:r}),this._publishingLocalAudioTrack=null,this._publishingLocalVideoTrack=null,this._isPublishingAux=!1,t){this[r?"localAuxVideoTrack":"localMainVideoTrack"]=t,yield this.singlePC.setDegradationPreference(this._peerConnection.getSenders()[r?3:1],t.contentHint,t.streamType);let{scaleResolutionDownBy:R}=t;yield this.singlePC.setScaleResolutionDownBy(this._peerConnection.getSenders()[r?3:1],R,t.streamType)}e&&(this[r?"localAuxAudioTrack":"localMainAudioTrack"]=e),yield this.singlePC.setBandwidth({audio:((l=this.localMainAudioTrack)==null?void 0:l.profile.bitrate)||((u=this.localAuxAudioTrack)==null?void 0:u.profile.bitrate),bigVideo:(h=this.localMainVideoTrack)==null?void 0:h.profile.bitrate,smallVideo:(g=(f=this.localMainVideoTrack)==null?void 0:f.small)==null?void 0:g.bitrate,auxVideo:(D=this.localAuxVideoTrack)==null?void 0:D.profile.bitrate}),this.sendMediaSettings(),this.installTrackMuteEvents(e,t),(this._room.preferHW||(_=this._room.scheduleResult.config)!=null&&_.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(!mt())return;this._log.info("publish by transceiver");let n=t==null?void 0:t.outMediaTrack,a=e==null?void 0:e.outMediaTrack,d=this._peerConnection.getTransceivers(),l=[],u=[],h=(g,D,_)=>{var k,j;let R=d[D].sender.replaceTrack(_);u.push(D),(k=this.singlePC)!=null&&k.enableInsertableStreams&&R.then(()=>this.createEncodedStreams(d[D].sender,g)),(j=this.singlePC)!=null&&j.scriptTransformWorker&&this.initSenderTransfrom(d[D].sender,g),l.push(R)};a&&h(e.mediaType,0,a),n&&h(t.mediaType,o?3:1,n),r&&h(8,2,r);let f=this.singlePC.setTransceiverDirection(K.SENDONLY,u);return l.push(f),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,d;if(this.singlePC.insertableStreamsAbortMap.has(e))return;let r=e.createEncodedStreams(),o=new AbortController;(a=this.singlePC)==null||a.addAbortController(e,o),((d=this.getTrackByMediaType(t))!=null&&d.enableEncodeFrame?r.readable.pipeThrough(new TransformStream({transform:(l,u)=>{var f;let h=this.getTrackByMediaType(t);u.enqueue((f=this.singlePC)!=null&&f.isUsingH264&&h?h.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 p(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(K.SENDONLY,[2])}}else yield t[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(K.INACTIVE,[2]);this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.on("mute",this.sendMutedFlag,this),t==null||t.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(...e){e.forEach(t=>{t&&(t==null||t.off("mute",this.sendMutedFlag,this),t==null||t.off("unmute",this.sendMutedFlag,this))})}unpublish(r){return p(this,arguments,function*({localAudioTrack:e,localVideoTrack:t}){var l,u;yield Promise.all([(l=this.singlePC)==null?void 0:l.waitForPeerConnectionConnected(),(u=this.singlePC)==null?void 0:u.waitForReconnected()]);let o=t&&t===this.localAuxVideoTrack,n=t==null?void 0:t.outMediaTrack,a=this._peerConnection.getSenders(),d=[];e&&(o?this.localAuxAudioTrack=null:this.localMainAudioTrack=null,!this.localMainAudioTrack&&!this.localAuxAudioTrack&&(yield a[0].replaceTrack(null),d.push(0))),n&&(o?(yield a[3].replaceTrack(null),this.localAuxVideoTrack=null,this._mediaSettings=L(v({},this._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),d.push(3)):(yield a[1].replaceTrack(null),yield a[2].replaceTrack(null),this.localMainVideoTrack=null,this._mediaSettings=L(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}),d.push(1,2))),this.isMainStreamPublished||this.isAuxStreamPublished?(yield this.singlePC.setTransceiverDirection(K.INACTIVE,d),yield this.doPublishChange(!1)):yield this.doUnpublish(),this.uninstallTrackMuteEvents(e,t),t==null||t.emit("connection-state-changed",{prevState:this._currentState,state:"DISCONNECTED"})})}doPublishChange(e=!0){return p(this,null,function*(){let t={state:this.publishingState,constraintConfig:this._mediaSettings},r=yield this._signalChannel.sendWaitForResponseWithRetry({command:Q.PUBLISH_STATE_CHANGE,data:t,responseCommand:H.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:H.UNPUBLISH_RESULT,enableLog:e}).catch(t=>{if(t.getCode()===I.API_CALL_TIMEOUT)return Promise.resolve();throw t})}updateMediaSettings(){var o;this._mediaSettings.videoCodec=((o=this.singlePC)==null?void 0:o.videoCodec)||"h264";let e=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:t,localAuxVideoTrack:r}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?r=this._publishingLocalVideoTrack:t=this._publishingLocalVideoTrack),Kt){if(e&&e.outMediaTrack){let n=e.outMediaTrack.getSettings();this._mediaSettings.audioChannel=n.channelCount||1,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=n.sampleRate||0}if(t&&t.outMediaTrack){let n=t.outMediaTrack.getSettings(),{scaleResolutionDownBy:a}=t;this._mediaSettings.videoWidth=n.width/a||0,this._mediaSettings.videoHeight=n.height/a||0,this._mediaSettings.videoFps=n.frameRate||0,this._mediaSettings.videoBps=t.profile.bitrate*1e3,t.small&&(this._mediaSettings.smallVideoWidth=t.small.width,this._mediaSettings.smallVideoHeight=t.small.height,this._mediaSettings.smallVideoFps=t.small.frameRate,this._mediaSettings.smallVideoBps=t.small.bitrate*1e3)}if(r&&r.outMediaTrack){let n=r.outMediaTrack.getSettings(),{scaleResolutionDownBy:a}=r;this._mediaSettings.auxVideoWidth=n.width/a||0,this._mediaSettings.auxVideoHeight=n.height/a||0,this._mediaSettings.auxVideoFps=n.frameRate||0,this._mediaSettings.auxVideoBps=r.profile.bitrate*1e3}}else e&&e.outMediaTrack&&(this._mediaSettings.audioChannel=e.profile.channelCount,this._mediaSettings.audioBps=e.profile.bitrate*1e3,this._mediaSettings.audioFs=e.profile.sampleRate),t&&t.outMediaTrack&&(this._mediaSettings.videoWidth=t.profile.width,this._mediaSettings.videoHeight=t.profile.height,this._mediaSettings.videoFps=t.profile.frameRate,this._mediaSettings.videoBps=t.profile.bitrate*1e3);this._log.info(`updateMediaSettings: ${JSON.stringify(this._mediaSettings)}`)}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Q.UPDATE_CONSTRAINT_CONFIG,data:this._mediaSettings,responseCommand:H.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return p(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is adding ${e.kind} track to current published local ${t?m.AUXILIARY:m.MAIN} stream`),Yt()&&(yield this.addTrackByTransceiver(e,t))})}addTrackByTransceiver(e,t){return p(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===K.INACTIVE&&(yield this.singlePC.setTransceiverDirection(K.SENDONLY,[n]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(e){return p(this,null,function*(){if(!this._peerConnection)return;let t=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info(`is removing ${e.kind} track from current published local ${t?m.AUXILIARY:m.MAIN} stream`),Yt()&&(yield this.removeTrackByTransceiver(e,t))})}removeTrackByTransceiver(e,t){return p(this,null,function*(){if(!e.mediaTrack)return;let r=this._peerConnection.getTransceivers();if(e.kind===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(K.INACTIVE,[o])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(e){return p(this,null,function*(){var n;let t=(n=this._peerConnection)==null?void 0:n.getSenders(),r=e.outMediaTrack||e.mediaTrack;if(!t||t.length===0||!r||t.find(a=>a.track===r))return!1;let 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 p(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:H.MUTE_RESULT,data:this.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&S.emit(E.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(Pe.NOT_SUPPORTED_H264ENCODE),new b({code:I.NOT_SUPPORTED_H264,message:V({key:U.NOT_SUPPORTED_H264ENCODE})})):new b({code:I.UNKNOWN,message:V({key:U.SIGNAL_RESPONSE_FAILED,data:{signalResponse:H.PUBLISH_RESULT,code:e,message:t}})})}onSinglePCReconnected(){return p(this,null,function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))})}};y([Ke(function({localVideoTrack:e}){e==null||e.once("6",this.onVideoEncodeFailed,this)})],sn.prototype,"publish",1),y([Ke(function({localVideoTrack:e}){e==null||e.off("6",this.onVideoEncodeFailed,this)})],sn.prototype,"unpublish",1);var yu=sn;function Lp(s){return Object.keys(s).filter(i=>s[i])}var xs=class extends $r{constructor(e){super(L(v({},e),{isUplink:!1}));c(this,"_flag",0);c(this,"isRobot",!1);c(this,"role","anchor");c(this,"remoteAudioTrack");c(this,"remoteVideoTrack");c(this,"remoteAuxiliaryTrack");c(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0});c(this,"jitterBufferTimeoutId",-1);this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=new Pi(this._room,this),this.remoteVideoTrack=new di(this._room,this),this.remoteAuxiliaryTrack=new ys(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 Ti(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 u,h;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 d=m.AUDIO;r.kind===m.VIDEO&&(d=a===m.MAIN?m.VIDEO:m.AUXILIARY);let l=this.remoteAudioTrack;d===m.VIDEO?l=this.remoteVideoTrack:d===m.AUXILIARY&&(l=this.remoteAuxiliaryTrack),(u=this.singlePC)==null||u.receiverRemoteTrackMap.set(o,l),(h=this.singlePC)!=null&&h.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 d,l;let a=(d=this.singlePC)==null?void 0:d.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 d=o.enqueue(n);d&&a.enqueue(d)}})).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 p(this,null,function*(){try{if(this._log.info(`subscribe ${t} ${Lp(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:I.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"),Qe&<<92)return;this.singlePC.startReconnection()}}unsubscribe(r){return p(this,arguments,function*({remoteTracks:e,streamType:t}){var a;if(t==="main"&&!this.isMainStreamSubscribed||t==="auxiliary"&&!this.isAuxStreamSubscribed){this._log.info(`${t} stream already unsubscribed`);return}let o=v({},this.subscribeState);e.forEach(d=>{switch(d.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(d=>d===!0)||(n="unsubscribe"),this._log.info(`${n==="unsubscribe"?n:"subscribe"} ${t} [${Lp(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=H.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=H.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:o,data:r,responseCommand:n,timeout:1e4,retries:3}).then(({data:a})=>{if(a.code!==0){let d=new b({code:a.code,message:V({key:U.ERROR_MESSAGE,data:{type:e,message:a.message}})});throw this._log.error(d),d}})}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay({audioDelay:e,videoDelay:t}){this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=t}onSinglePCReconnected(){return p(this,null,function*(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary)&&(this._log.warn(`resubscribe ${JSON.stringify(this.subscribeState)}`),yield this.doSubscribe(this.subscribeState),this.remoteAudioTrack.checkDecodeResult(),this.remoteVideoTrack.checkDecodeResult(),this.remoteAuxiliaryTrack.checkDecodeResult())})}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return p(this,arguments,function*(e=this.subscribeState,t=!0){if(this.singlePC){this.singlePC.addDownlinkQueue.add(this.tinyId),yield this.singlePC.waitForPeerConnectionConnected();try{if(t||!this.hasSSRC){let r={audioSsrc:Hr(),bigVideoSsrc:Hr(),bigVideoRtxSsrc:Hr(),auxVideoSsrc:Hr(),auxVideoRtxSsrc:Hr()},{audioSsrc:o,bigVideoSsrc:n,bigVideoRtxSsrc:a,auxVideoSsrc:d,auxVideoRtxSsrc:l}=r;this.ssrc={audio:o,video:n,videoRtx:a,auxiliary:d,auxiliaryRtx:l},this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc});try{let u=yield this._signalChannel.sendWaitForResponseWithRetry({command:Q.SPC_SUBSCRIBE,responseCommand:H.SPC_SUBSCRIBE_RESULT,data:{srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:!1,ssrc:r},retries:3,retryTimeout:0});if(u.data.code!==0)throw new b({code:u.data.code,message:u.data.message})}catch(u){throw yield this.removeDownlink(),u}return}this.singlePC.addDownlinkQueue.delete(this.tinyId),yield this.singlePC.addDownlink({userId:this.userId,tinyId:this.tinyId,ssrc:this.ssrc})}finally{if(!oa)return;let{main:r,aux:o}=this._room.jitterBufferDelay||{},{jitterDelay:n=r,jitterDelayAux:a=o}=this._room.scheduleResult.config||{};(Y(n)||Y(a))&&this.setJitterBufferDelay({mainDelay:n,auxDelay:a})}}})}removeDownlink(){return p(this,null,function*(){if(!this.singlePC)return;this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId);let e=this._room.scheduleResult.config;(e!=null&&e.jitterDelay||e!=null&&e.jitterDelayAux)&&this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),yield this.singlePC.removeDownlink(this.userId)})}setJitterBufferDelay({mainDelay:e,auxDelay:t}){if(!oa||!this.singlePC||!this._peerConnection||Ii(e)&&Ii(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,Ii(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 h;let d=a.track===this.remoteAuxiliaryTrack.outMediaTrack||Ii(e)&&a.track===this.remoteAudioTrack.outMediaTrack;if(d&&Ii(t)||!d&&Ii(e))return;let l=d?t||0:e,u=(a.jitterBufferTarget||0)+100;u>l||(a.jitterBufferTarget=u,this._log.debug(`set ${d?"aux ":""}${(h=a==null?void 0:a.track)==null?void 0:h.kind} jitterBuffer delay ${u} -> ${l}`))}),!r.find(a=>{let d=a.track===this.remoteAuxiliaryTrack.outMediaTrack?t||0:e;return a.jitterBufferTarget<d}))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([si(),z(e=>function(...t){return new Promise((r,o)=>{let n=a=>{this.off("closed",n),o(new b({code:I.API_CALL_ABORTED,message:V({key:U.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([si()],xs.prototype,"unsubscribe",1),y([Mi(()=>"jitter")],xs.prototype,"setJitterBufferDelay",1);var Pp=xs;function wp(){return z(s=>function(...i){return p(this,null,function*(){if(this.scene==="live"&&this.role!=="anchor"||(i=i.filter(t=>t.outMediaTrack&&t.state==="capture"),!i.length))return;S.emit("61",{room:this});let e=s.apply(this,i);return i.forEach(t=>t.publish(this,e)),e})})}function xp(){return z(s=>function(...i){let e=s.apply(this,i);return i.forEach(t=>t.unpublish()),e})}var Up=Be(ze());function KT(){return Math.floor(Math.random()*16383)}var gc=class gc extends Up.EventEmitter{constructor(e,t){super();this.room=e;this.signalChannel=t;c(this,"log");c(this,"cmdIdSeqMap",new Map);c(this,"messageMap",new Map);this.log=C.createLogger({id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),t.on(H.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)||KT(),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)>gc.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 d=setTimeout(()=>this.emitMessage(o,!0),5e3);a.cachedMessageMap.set(o.seq,{message:o,timeoutId:d})}}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),Ei(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 d=[...r.cachedMessageMap.values()].sort((l,u)=>l.message.seq-u.message.seq);d[0]&&(o=d[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)}};c(gc,"SEQ_INTERVAL",300);var _c=gc;var{isString:Vp,isUndefined:Us,getNetworkType:ZT,isEmpty:on}=dt,Ft=class extends pc{constructor(e){super(e);c(this,"_businessInfo");c(this,"userManager");c(this,"_version");c(this,"_heartbeat",-1);c(this,"_lastHeartBeatTime",-1);c(this,"_stats");c(this,"_joinTimeout",-1);c(this,"_firstPublishedList",null);c(this,"_joinReject",null);c(this,"_isRelayChanged",!1);c(this,"sdpSemantics");c(this,"signalChannel",null);c(this,"uplinkConnection",null);c(this,"singlePC",null);c(this,"enableSPC",ms);c(this,"_changeBigSmallRecords",new Map);c(this,"networkQuality");c(this,"_iceTransportPolicy");c(this,"forceRelay",!1);c(this,"_turnServers",[]);c(this,"_iceServersFromJoin");c(this,"_syncUserListInterval",-1);c(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160});c(this,"enableSEI",!1);c(this,"_enableAudioVolumeEvaluation",!1);c(this,"_audioVolumeIntervalId",0);c(this,"_enableMultiAuxStream",!1);c(this,"_pureAudioPushMode",!1);c(this,"_customMessageManager");c(this,"preferHW",!1);c(this,"healthDetector");c(this,"playoutDelay");c(this,"jitterBufferDelay");c(this,"_updateAudioLevelTaskId",-1);this._stats=new en(this,this._log),this.userManager=new Ha(this.userId,this._log),this._version=Oe,this.sdpSemantics=Wr,Us(e.sdpSemantics)?Zt.isUnifiedPlanDefault()&&(this.sdpSemantics=Ji):this.sdpSemantics=e.sdpSemantics,this._log.info(`sdpSemantics: ${this.sdpSemantics}, netType: ${ZT()}`),e.iceTransportPolicy&&(this._iceTransportPolicy=e.iceTransportPolicy),this._enableMultiAuxStream=Us(e.enableMultiAuxStream)?!1:e.enableMultiAuxStream,this.enableSEI=e.enableSEI&&ms,!Us(e.enableSPC)&&ms&&(this.enableSPC=e.enableSPC),this.preferHW=!!e.preferHW,this._initBusinessInfo(e),this.healthDetector=new Rp(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 p(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=Du(n,[]);S.emit(E.REMOTE_PUBLISH_STATE_CHANGED,v({room:this},o)),this.emit("remote-publish-state-changed",v({},o))}),this.joinParams=e,new Promise((o,n)=>p(this,null,function*(){var a,d;this._joinReject=n;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(u){if(u instanceof b&&u.code===I.SPC_INITIALIZED_FAILED)(a=this.signalChannel)==null||a.destroy(),yield this.initialize();else return n(u)}let l=P();yield this.doJoin(e,(d=this.singlePC)==null?void 0:d.clientAbility),N.addSuccessEvent({key:521708,cost:P()-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 p(this,null,function*(){if(!(!this.enableSPC||this.singlePC)){this.singlePC=new Bt({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:I.SPC_INITIALIZED_FAILED,message:e==null?void 0:e.message})}}})}doJoin(e,t){return new Promise((r,o)=>p(this,null,function*(){var d,l,u;e.privateMapKey&&(this.privateMapKey=e.privateMapKey),e.latencyLevel&&(this.latencyLevel=e.latencyLevel),this.signalChannel.once(Ce.SETUP_FAILED,h=>{this.clearJoinTimeout(),S.emit(E.JOIN_SIGNAL_CONNECTION_END,{room:this,error:h}),o(h)}),_e((l=(d=this.scheduleResult)==null?void 0:d.config)==null?void 0:l.singlePC)&&ms&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),t&&this.playoutDelay&&(t.playoutDelay=this.playoutDelay);let n={roomId:String(e.roomId||e.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:e.role,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:od(),netType:hr(),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;(u=this.scheduleResult.config)!=null&&u.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(a=this.scheduleResult.config.enterRoomTimeout*1e3),this._joinTimeout=window.setTimeout(()=>{o(new b({code:I.JOIN_ROOM_FAILED,message:V({key:U.JOIN_ROOM_TIMEOUT})}))},a),S.emit(E.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?Q.SPC_JOIN_ROOM:Q.JOIN_ROOM,n),this.signalChannel.once(H.JOIN_ROOM_RESULT,h=>p(this,null,function*(){this.clearJoinTimeout();let{code:f,message:g,data:D,tinyId:_}=h.data;S.emit(E.JOIN_RECEIVED_CMD_RES,{room:this,code:f}),f===0?(this._log.info("Join room success, start heartbeat"),_&&(this.tinyId=_),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=D.publishers,this._iceServersFromJoin=D.iceServer?[D.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then(()=>{var R;(R=this.singlePC)==null||R.connect(L(v({},D.ability),{useVp8:D.ability.useVp8||!!e.useVp8})).catch(()=>{})}),r()):(this._log.error(`Join room failed result: ${f} error: ${g}`),o(new b({code:I.JOIN_ROOM_FAILED,extraCode:f,message:V({key:U.JOIN_ROOM_FAILED,data:{error:g,code:f}})})))}))}))}reJoin(){return p(this,null,function*(){if(!this.isJoined){this._log.warn("reJoin abort");return}try{this._log.warn(`reJoin pending: ${this.joinParams.roomId}`);let e,t=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,t.push(this.initSinglePC().then(r=>(e=r,r)))),this.signalChannel&&(this.signalChannel.close(),t.push(this.signalChannel.connect())),yield Promise.all(t),yield this.doJoin(L(v({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),e),this._log.warn("reJoin success"),te.logSuccessEvent({userId:this.userId,eventType:it.REJOIN}),this.singlePC){let r=o=>{var n;o.state==="CONNECTED"&&((n=this.singlePC)==null||n.off(ui.CONNECTION_STATE_CHANGED,r),this.uplinkConnection instanceof yu&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(a=>{a.installEvents(),a.onSinglePCReconnected()}))};this.singlePC.on(ui.CONNECTION_STATE_CHANGED,r),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof Zo&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(e){this._log.warn(`reJoin fail ${e}`),this.reset(),te.logFailedEvent({userId:this.userId,eventType:it.REJOIN,error:e}),this.emit("error",new b({code:I.JOIN_ROOM_FAILED,message:V({key:U.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}})}initialize(){return p(this,null,function*(){let{mainUrl:e,backupUrl:t}=this.getSignalChannelUrl(),r=this.signalChannel||Ym(this.userId),o=!!(r&&r.isConnected&&r.keepAlive&&r.userId===this.userId),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):(r&&r.close(),this.signalChannel=new ks({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:e,backupUrl:t,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?n:void 0}),this._customMessageManager=new _c(this,this.signalChannel),this._customMessageManager.on("message",a=>{this.emit("custom-message",a)})),this.networkQuality||(this.networkQuality=new ws({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(ws.EVENT_NETWORK_QUALITY,a=>{var d;this.emit("network-quality",a),(d=this.singlePC)==null||d.detectTCPAndUDP(a)})),$e(this,this.signalChannel).add(Ce.CONNECTION_STATE_CHANGED,a=>{S.emit(E.SIGNAL_CONNECTION_STATE_CHANGED,v({room:this},a)),this.emit("signal-connection-state-changed",a)}).add(Ce.RECONNECT_FAILED,a=>{this.reset(),this.emit("error",a)}).add(H.PEER_JOIN,a=>{let{srcTinyId:d,userId:l,role:u}=a.data.data;this.userManager.addUser({userId:l,tinyId:d,role:u})}).add(H.PEER_LEAVE,a=>{let{userId:d,reason:l=0}=a.data.data;this.userManager.deleteUser(d,l)}).add(H.UPDATE_REMOTE_MUTE_STAT,a=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=10*1e3&&this.doHeartbeat(),this.onPublishedUserList(a.data)}).add(H.CLIENT_BANNED,a=>{let d=a.data.data,{reason:l}=d;if(te.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(Ce.SETUP_SUCCESS,a=>{this.tinyId=a.signalInfo.tinyId,S.emit(E.JOIN_SIGNAL_CONNECTION_END,{room:this})}),S.emit(E.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),o&&S.emit(E.JOIN_SIGNAL_CONNECTION_END,{room:this}),o})}setSignalChannel(e){this.signalChannel=e,e||Re(this)}leave(){return p(this,null,function*(){var e;try{yield this.doHeartbeat()}catch(t){}this._log.info("leave() => leaving room"),S.emit(E.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 p(this,null,function*(){var n;let e=this.badCaseDetector.getMonitorFreeze(),t=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});this.badCaseDetector.resetMonitor();let r=(n=this.signalChannel)!=null&&n.isConnected?Tm(this.userId):[],o=L(v({str_sdk_version:$s,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:hr()},t.msg_device_info)});if(this.heartbeatReport=o,S.emit(E.HEARTBEAT_REPORT,{room:this,report:o}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(Q.ON_QUALITY_REPORT,o);let a=Date.now();this._lastHeartBeatTime>0&&a-this._lastHeartBeatTime>1e4&&this._log.warn(`heartbeat took ${a-this._lastHeartBeatTime}`),this._lastHeartBeatTime=a,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",L(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!==Nc).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})}),S.emit(E.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:t}),this.userManager.setRemotePublishedUserList(t)}closeUplink(e="you unpublished"){this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish(),this.uplinkConnection.close(e),this.uplinkConnection instanceof Zo&&(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?Pp:pu)({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!==I.ICE_TRANSPORT_ERROR&&(o===I.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",r))}),e.on("connection-state-changed",r=>{this.emit("media-connection-state-changed",L(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:H.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:d,role:l})=>({userId:a,tinyId:d,role:l}));throw V({key:U.SIGNAL_RESPONSE_FAILED,data:{signalResponse:H.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||!cu)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)===me.CLOSED&&!this.singlePC.isReconnecting&&(this._log.warn("spc pc is closed but not reconnect"),this.singlePC.startReconnection()):this.getAllConnections().forEach(r=>{if(r instanceof tt&&!r.getIsReconnecting()){let o=r.getPeerConnection();o&&o.connectionState===me.CLOSED&&(this._log.warn(`[${r.getUserId()}] pc is closed but not reconnect`),r.startReconnection())}})}fallbackToMPC(){return p(this,null,function*(){var e;if(this._log.warn("fallback to multi pc"),te.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(e=this.singlePC)==null||e.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin()),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new Zo({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 pu({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:I.INVALID_OPERATION,message:V({key:U.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.removeAllListeners(),this.healthDetector.destroy(),re.clearTask(this._audioVolumeIntervalId))}switchRole(e){return p(this,null,function*(){this.role!==e&&(e==="audience"&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(e))})}doSwitchRole(e){let t={command:Q.SWITCH_ROLE,data:{role:e==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:H.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:I.SWITCH_ROLE_FAILED,message:V({key:U.SWITCH_ROLE_FAILED,data:{message:n,code:o}})});this.role=e}).catch(r=>{throw r instanceof b&&r.getCode()===I.API_CALL_TIMEOUT&&(r=new b({code:I.SWITCH_ROLE_FAILED,message:V({key:U.SWITCH_ROLE_TIMEOUT})})),this._log.error(r),r})}publish(...e){return p(this,null,function*(){let t={},r={};e.forEach(d=>{d instanceof St&&(d instanceof ni?r.audio=d:t.audio=d),d instanceof We&&(d instanceof ct&&d.mediaType===2?r.video=d:t.video=d)});let o=on(t),n=on(r);(!o||!n)&&!this.uplinkConnection&&(this.singlePC?this.uplinkConnection=new yu({userId:this.userId,tinyId:this.tinyId,room:this}):this.uplinkConnection=new Zo({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",d=>{this.emit("media-connection-state-changed",L(v({},d),{userId:this.userId}))}),this.uplinkConnection.on("firewall-restriction",()=>{this.emit("firewall-restriction")}),this.uplinkConnection.on("error",d=>{let l=d.getCode();l!==I.ICE_TRANSPORT_ERROR&&(l===I.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",d))}));let a=e.map(d=>d.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 p(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 St&&(o instanceof ni?r.audio=o:t.audio=o),o instanceof We&&(o instanceof ct&&o.mediaType===2?r.video=o:t.video=o))});try{let o=e.map(n=>n.kind).join(",");on(t)||(this._log.info(`unpublish() => main ${o}`),yield this.uplinkConnection.unpublish({localAudioTrack:t.audio,localVideoTrack:t.video})),on(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||!vd()?Promise.resolve():this.uplinkConnection.replaceTrack(e).then(t=>{t&&S.emit(E.LOCAL_TRACK_REPLACED,{track:e})})}setBandWidth(e){return p(this,null,function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(e),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(e){return p(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();e&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:m.VIDEO,videoType:m.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(e)})}subscribe(...e){return p(this,null,function*(){if(e=e.filter(n=>!n.isSubscribed),e.length===0)return;let{userId:t}=e[0],r=this.remotePublishedUserMap.get(t);if(!r)return;let o=e.find(n=>n.mediaType===2)?"auxiliary":"main";try{let n=v({},r.subscribeState);e.forEach(d=>{switch(d.mediaType){case 1:n.audio=!0;break;case 4:n.video=!0;break;case 8:n.smallVideo=!0;break;case 2:n.auxiliary=!0;break}});let a=this._changeBigSmallRecords.get(t);a&&a.options.smallVideo&&r.muteState.hasSmall&&n.video&&(n.video=!1,n.smallVideo=!0),S.emit(E.SUBSCRIBE_START,{room:this,streamType:o,remotePublishedUser:r,subscribeState:n}),this._log.info(`subscribe() => ${t} ${o} [${nc(n)}] prev: [${nc(r.subscribeState)}]`),yield r.subscribe(n,o),this._log.info(`subscribe ${t} ${o} done`);for(let d of e)d.mediaTrack||(yield d.waitHasMediaTrack());S.emit(E.SUBSCRIBE_SUCCESS,{room:this,streamType:o,remotePublishedUser:r})}catch(n){let a=n instanceof b?n.getCode():I.UNKNOWN,d=n;throw n instanceof b?a===I.REMOTE_STREAM_NOT_EXIST&&(d=new b({code:I.API_CALL_ABORTED,message:V({key:U.API_CALL_ABORTED,data:{message:n.message,userId:t,streamType:o}})}),this._log.warn(d)):(d=new b({code:a,message:V({key:U.SUBSCRIBE_FAILED,data:{message:n.message,userId:t,streamType:o}})}),this._log.error(d)),d}})}unsubscribe(...e){return p(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)}),S.emit(E.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)),S.emit(E.AUDIO_LEVEL_INTERVAL,{interval:e}),this._audioVolumeIntervalId&&re.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=re.run("intervalInWorker",()=>{var o;yr.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(e,t);let r=[];(o=this.remotePublishedUserMap)==null||o.forEach(n=>{if(n.muteState.hasAudio){!yr.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 p(this,null,function*(){var n;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||this._updateAudioLevelTaskId!==-1)return;let r=(n=this.uplinkConnection.getPeerConnection())==null?void 0:n.getSenders()[0];if(!r)return;let o=Math.max(e,500);this._log.warn(`updateAudioLevelFromSenderStat ${o}`),this._updateAudioLevelTaskId=re.run("intervalInWorker",()=>p(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack){this.stopUpdateAudioLevelFromSenderStat();return}let a=yield r.getStats();if(this._updateAudioLevelTaskId<0)return;let{localMainAudioTrack:d}=this.uplinkConnection;a.forEach(l=>{l.type==="media-source"&&l.audioLevel&&(d.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(!Dd||!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 p(this,null,function*(){var t;let e={};return e[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},(t=this.uplinkConnection)!=null&&t.localMainAudioTrack&&(e[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),e})}getLocalVideoStats(){return p(this,null,function*(){var t,r;let e={};return e[this.userId]=((r=(t=this.uplinkConnection)==null?void 0:t.localMainVideoTrack)==null?void 0:r.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},e})}getTransportStats(){return p(this,null,function*(){let e={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);e.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let r=yield this._stats.getReceiverStats(t);e.downlinksRTT[r.userId]=r.rtt}return e})}getRemoteVideoStats(e){return p(this,null,function*(){let t={};for(let[r,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 p(this,null,function*(){let e={};for(let[t,r]of this.remotePublishedUserMap)r.muteState.hasAudio&&(e[t]=r.remoteAudioTrack.stat);return e})}setTurnServer(e,t){this._log.info(`set turn server: ${JSON.stringify(e)} ${t||""}`);let r=[];Array.isArray(e)?e.forEach(o=>r.push(dt.getTurnServer(o))):dt.isPlainObject(e)&&r.push(dt.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:H.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"})}sendStopMixTranscode(e){return this.signalChannel.sendWaitForResponse({command:Q.STOP_MIX_TRANSCODE,data:e,timeout:5e3,responseCommand:H.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?H.START_PUBLISH_TENCENT_CDN_RES:H.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?H.STOP_PUBLISH_TENCENT_CDN_RES:H.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"})}sendStartPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Q.START_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:H.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"})}sendUpdatePushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Q.UPDATE_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:H.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"})}sendStopPushStreamToRoom(e){return this.signalChannel.sendWaitForResponse({command:Q.STOP_PUBLISH_CDN_STREAM,data:e,timeout:5e3,responseCommand:H.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:H.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(r=>{})}getIceServers(e){var t,r;return this._turnServers.length>0?this._turnServers:(t=this.scheduleResult.iceServers)!=null&&t.length?this.scheduleResult.iceServers:e!=null&&e.length?e:(r=this._iceServersFromJoin)!=null&&r.length?this._iceServersFromJoin:[]}getIceTransportPolicy(){return this.forceRelay?"relay":this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let e={mainUrl:"",backupUrl:""},t=dt.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 p(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:d,reSubscribeCount:l}=a;if(d.video&&t.video||d.smallVideo&&t.smallVideo&&o)return;let u={audio:e.remoteAudioTrack.isSubscribed||e.remoteAudioTrack.isSubscribing,auxiliary:e.remoteAuxiliaryTrack.isSubscribed||e.remoteAuxiliaryTrack.isSubscribing,video:d.video,smallVideo:d.smallVideo};try{if(!o&&u.smallVideo&&(u.video=!0,u.smallVideo=!1),u.smallVideo===t.smallVideo&&u.video===t.video)return;a.isSubscribing=!0,a.reSubscribeCount=l-1,yield e.subscribe(u,"main"),e.remoteVideoTrack.setMediaType(u.smallVideo?8:4),this._log.info(`change [${r}] to ${u.smallVideo?"small":"big"} video successfully. count ${Jr-a.reSubscribeCount}.`),a.isSubscribing=!1,a.reSubscribeCount=Jr}catch(h){this._log.info(`change [${r}] to ${u.smallVideo?"small":"big"} video failed. count ${Jr-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:Jr};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)),!Us(e.pureAudioPushMode)){if(!Number.isInteger(Number(e.pureAudioPushMode)))throw new b({code:I.INVALID_PARAMETER,message:V({key:U.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(!Us(e.userDefineRecordId)){let r=/^[A-Za-z0-9_-]{1,64}$/gi;if(e.userDefineRecordId.match(r)===null)throw new b({code:I.INVALID_PARAMETER,message:V({key:U.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=e.userDefineRecordId}if(!Us(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:I.INVALID_PARAMETER,message:V({key:U.INVALID_USER_DEFINE_PUSH_ARGS})});on(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(e){var t;(t=this._customMessageManager)==null||t.send(e)}enableInsertableStreams(){return p(this,null,function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&Di)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:I.INVALID_OPERATION,message:"not join"}))}get enableCodecPipeline(){return this.videoManager.encodePipeline.length>0||this.videoManager.decodePipeline.length>0||this.audioManager.encodePipeline.length>0||this.audioManager.decodePipeline.length>0}get scriptTransformWorker(){var e;return(e=this.singlePC)==null?void 0:e.scriptTransformWorker}};y([pe(["left",F.INIT],"joined"),ot({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"),Ut(!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())}}),jm()],Ft.prototype,"join",1),y([pe("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),qm(),Aa("leave room"),ko({fnName:"publish",validateArgs:!1}),ko({fnName:"unsubscribe",validateArgs:!1})],Ft.prototype,"leave",1),y([si(),wp(),ot({settings:{retries:fi,timeout:e=>Nt(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),S.emit(E.PUBLISH_FAILED,{room:this}))}})],Ft.prototype,"publish",1),y([ko({fnName:"publish"}),sm("api-call"),si(),xp(),Ke(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)))})],Ft.prototype,"unpublish",1),y([Ea(e=>{if(e.code!==I.API_CALL_ABORTED)throw e}),Mi(e=>e.userId)],Ft.prototype,"replaceTrack",1),y([Mi((...e)=>e[0].userId),ya(),Xm(),ot({settings:{retries:fi,timeout:e=>Nt(e)},onError(e,t,r,o){e.message.includes("timeout")?(this._log.warn("subscribe timeout"),t()):(this._log.error(`subscribe failed: ${e}`),r(e),S.emit(E.SUBSCRIBE_FAILED,{room:this,remoteTracks:o}))}})],Ft.prototype,"subscribe",1),y([ko({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")})}}),Mi((...e)=>e[0].userId)],Ft.prototype,"unsubscribe",1);Yo.create=Yo._create.bind(Yo,Ft);var dH=Yo;export{dH as default};
|
|
142
|
+
}`});u(this,"yTextureRef");u(this,"uTextureRef");u(this,"vTextureRef");u(this,"Y");u(this,"U");u(this,"V");this.useProgram();let r=this.context.ctx;r.pixelStorei(r.PACK_ALIGNMENT,1),r.pixelStorei(r.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,r){let o=this.context.ctx,s=o.createTexture();return o.bindTexture(o.TEXTURE_2D,s),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.bindTexture(o.TEXTURE_2D,null),o.uniform1i(o.getUniformLocation(this.program,e),r),s}render(e){let r=this.context.ctx,o=this.width,s=this.height;return this.useProgram(),r.viewport(0,0,o,s),r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,this.yTextureRef),r.texSubImage2D(r.TEXTURE_2D,0,0,0,o,s,r.LUMINANCE,r.UNSIGNED_BYTE,this.Y),r.activeTexture(r.TEXTURE1),r.bindTexture(r.TEXTURE_2D,this.uTextureRef),r.texSubImage2D(r.TEXTURE_2D,0,0,0,o/2,s/2,r.LUMINANCE,r.UNSIGNED_BYTE,this.U),r.activeTexture(r.TEXTURE2),r.bindTexture(r.TEXTURE_2D,this.vTextureRef),r.texSubImage2D(r.TEXTURE_2D,0,0,0,o/2,s/2,r.LUMINANCE,r.UNSIGNED_BYTE,this.V),this.draw(),!0}resize(e,r){super.resize(e,r);let o=this.context.ctx;o.activeTexture(o.TEXTURE0),o.bindTexture(o.TEXTURE_2D,this.yTextureRef),o.texImage2D(o.TEXTURE_2D,0,o.LUMINANCE,e,r,0,o.LUMINANCE,o.UNSIGNED_BYTE,null),o.activeTexture(o.TEXTURE1),o.bindTexture(o.TEXTURE_2D,this.uTextureRef),o.texImage2D(o.TEXTURE_2D,0,o.LUMINANCE,e/2,r/2,0,o.LUMINANCE,o.UNSIGNED_BYTE,null),o.activeTexture(o.TEXTURE2),o.bindTexture(o.TEXTURE_2D,this.vTextureRef),o.texImage2D(o.TEXTURE_2D,0,o.LUMINANCE,e/2,r/2,0,o.LUMINANCE,o.UNSIGNED_BYTE,null)}};var rs=[i=>{i.codec="avc1.420028"},i=>{delete i.hardwareAcceleration}],bg=(i,t)=>{switch(i){case"webCodecs":return t==="videoFrame"?514705:514706;case"wasm":return t==="webgl"?514707:t==="videoFrame"?514708:514709}throw new Error("decoder type not supported")};function lS(i){return i[0]===0&&i[1]===0&&i[2]===0&&i[3]===1}var mS=0,lu=class{constructor(t){u(this,"id",mS++);u(this,"trackDoneOB");u(this,"startOB");u(this,"stopOB");u(this,"decoder");u(this,"videoContext");u(this,"gop",0);u(this,"gop_helper",0);u(this,"waitFirstKeyFrame",!0);u(this,"startTimestamp",0);u(this,"startTime",0);u(this,"startPerformanceTime",0);u(this,"inputFrameCount",0);u(this,"decodedFrameCount",0);u(this,"decodeFrameCount",0);u(this,"downgradeLevel",0);u(this,"lastDowngradeTime",0);u(this,"lastFrameDiff",0);u(this,"lastDecodeFrameTimestamp",0);u(this,"config");u(this,"gop_before_configure",[]);u(this,"videoElement");u(this,"type","wasm");u(this,"goodType");u(this,"renderer","2d");u(this,"wasmOption");u(this,"createDecoder");u(this,"_decodeSink");u(this,"isReported",!1);u(this,"track");u(this,"stateChangeOB");u(this,"failedReason");let{track:e,createDecoder:r}=t;if(this.stateChangeOB=It(),this.track=e,this.createDecoder=r,this.wasmOption={yuvMode:t.renderer==="webgl",wasmPath:t.wasmPath,workerMode:t.workerMode,canvas:t.canvas},this.config=t.config,this.videoElement=t.videoElement,this.renderer=t.renderer,this.trackDoneOB=Ce(e.availableState,oe.OFF),this.stopOB=It(),t.type==="auto"){switch(t.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=t.type;this.changeRenderer(this.renderer),ye(this.stateChangeOB,Um((o,s)=>(o!==s&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:o,state:s}),s),"INITIALIZED"),Xe(this.stopOB),ke()),this.start()}start(t=0){this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let e=ye(this.pipe(this.track),Xe(this.stopOB),fi());ye(e,ke(()=>{this.track.stat.framesDecoded++},r=>{if(this.track.log.error(`${this.id} play failed: ${r} retryCount: ${t}`),X.addFailedEvent({key:bg(this.type,this.renderer),error:r}),t>4)this.failedReason=r,this.stateChangeOB.next("FAILED");else{if(this.goodType){this.start(t);return}switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":switch(this.renderer){case"webgl":this.changeRenderer("videoFrame");break}}this.start(t+1)}},()=>{this.track.log.warn(`${this.id} decoderOB completed`),X.addSuccessEvent({key:bg(this.type,this.renderer)}),X.addSuccessEvent({key:514704})})),ye(e,Rr(1),ke(()=>{this.track.player.handlePlaying("canvas"),this.goodType=this.type,this.stateChangeOB.next("STARTED")}))}mock(t){this._decodeSink?this._decodeSink.error(t):this.start()}close(t){this.stopOB.next(t)}changeRenderer(t){this.renderer=t,this.renderer==="videoFrame"&&!xl()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(t,e=!1){var d,m;if(this.failedReason)return;this.inputFrameCount++;let r=new Uint8Array(t.data);if(!lS(r)||r.length<5)return this.stateChangeOB.next("FAILED"),this.close(`not h26x frame ${r.subarray(0,5)}`),t;let o=r[4]&31,s=!1;switch(o){case 5:case 7:s=!0;break}if(((d=this.decoder)==null?void 0:d.state)!=="configured")return this.track.log.debug(`not configured ${this.inputFrameCount}`),s&&(this.gop_before_configure=[]),this.gop_before_configure.push({data:t.data,timestamp:t.timestamp,type:t.type}),t;this.gop_before_configure.length>0&&!e&&(this.gop_before_configure.forEach(l=>this.decode(l,!0)),this.gop_before_configure=[]);let{timestamp:n}=t;if(s?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame)if(s)this.waitFirstKeyFrame=!1,this.startTimestamp=n,this.startTime=Date.now(),this.startPerformanceTime=Te();else{this.track.log.debug(`wait first key frame ${this.inputFrameCount} ${r.subarray(0,5).join(" ")}`);return}switch(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.decodeFrameCount<10||this.decodeFrameCount%500===0)&&this.track.log.debug(`decode ${this.decodeFrameCount} gop: ${this.gop} ${n} ${(m=t.getMetadata)==null?void 0:m.call(t).rtpTimestamp}`),this.decodeFrameCount++,this.lastDecodeFrameTimestamp=n,this.decoder.decode({data:t.data,type:t.type,timestamp:this.lastDecodeFrameTimestamp});return}return t}checkDowngradeByFrameDiff(){let t=this.downgradeLevel,e=this.decodeFrameCount-this.decodedFrameCount;e>this.lastFrameDiff?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):e<=this.lastFrameDiff&&this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==t&&this.track.log.debug(`downgrade level ${t} to ${this.downgradeLevel} ${this.decodeFrameCount} frameDiff: ${e}, lastFrameDiff: ${this.lastFrameDiff}`),this.lastFrameDiff=e,this.lastDowngradeTime=Date.now()}checkDowngradeByTimestampDiff(t){let e=this.downgradeLevel;this.lastDecodeFrameTimestamp-t>9e4?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==e&&this.track.log.debug(`downgrade level ${e} to ${this.downgradeLevel}`)}pipe(t){return e=>A(this,null,function*(){this._decodeSink=e;let r,o=t.mediaTrack;e.defer(()=>{var d;o&&(t.player.setCanvas(),t.setInputMediaStreamTrack(o)),r==null||r.close(),(d=this.videoContext)==null||d.destroy(),delete this._decodeSink});let{renderer:s,type:n}=this;t.log.info(`decoder type: ${this.type} renderer: ${this.renderer}`);try{switch(n){case"wasm":r=this.createDecoder(n,this.wasmOption);break;case"webCodecs":for(let m=0;m<=rs.length;m++){let{supported:l}=yield VideoDecoder.isConfigSupported(this.config);if(l)break;if(m===rs.length){e.error(3);return}rs[m](this.config)}r=this.createDecoder(n);break;default:throw new Error("not supported yet")}let d=0;if(r.on("videoFrame",m=>{this.decodedFrameCount++,d++,(d<=10||d%500===0)&&t.log.debug(`frame ${d} ${this.decodedFrameCount}/${this.decodeFrameCount} decoded ${m.timestamp}`),Date.now()-this.lastDowngradeTime>5e3&&(this.type==="webCodecs"?this.checkDowngradeByFrameDiff():this.type==="wasm"&&this.checkDowngradeByTimestampDiff(m.timestamp)),e.next(m)}),r.on("error",m=>{t.log.error(m),e.error(n==="webCodecs"?4:8)}),yield r.initialize(this.videoElement),!this._decodeSink)return;if(r.configure(this.config),n==="wasm"&&s==="webgl"){this.videoContext=new Et({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create(),this.videoContext.on(Et.UNAVAILABLE,l=>{t.log.error(l),e.error(7)});let m=new uu(this.videoContext);r.on("videoCodecInfo",l=>m.resize(l.width,l.height)),r.on("videoFrame",l=>{({y:m.Y,u:m.U,v:m.V}=l),this.downgradeLevel===1?this.decodedFrameCount%2===0&&m.render(this.decodedFrameCount):m.render(this.decodedFrameCount)}),t.source=m,t.player.setCanvas(this.videoContext._canvas,2)}else if(s==="videoFrame"){t.player.setCanvas();let m=new MediaStreamTrackGenerator({kind:"video"}),l=m.writable.getWriter();t.setInputMediaStreamTrack(m),r.on("videoFrame",g=>l.write(g))}else{this.videoContext=new Vt({frameRate:15,logger:t.log,name:t.userId}),this.videoContext.create({alpha:!1});let m=this.videoContext.createVideoImageSource();r.on("videoFrame",g=>{try{m.image=g,m.update()}catch(_){delete this.goodType,t.log.error(_),e.error(11)}});let l=new Qo(this.videoContext,{name:"remotePlayer",logger:t.log});m.connect(l),t.source=m,t.player.setCanvas(this.videoContext._canvas,2)}this.decoder=r}catch(d){t.log.error(d),e.error(n==="webCodecs"?2:6)}})}};var Pa=class extends Rg.EventEmitter{constructor(e){super();this.room=e;u(this,"videoContext");u(this,"_glVideoContext");u(this,"_2dVideoContext");u(this,"destination");u(this,"smallVideoContext");u(this,"smallDestination");u(this,"smallTrackSource");u(this,"smallImageSource");u(this,"_isMirror",!1);u(this,"cameraTrack");u(this,"cameraNode");u(this,"mirrorNode");u(this,"mixNode");u(this,"screenTrack");u(this,"screenNode");u(this,"selfModel",!1);u(this,"blurRadius",3);u(this,"arTrack");u(this,"Wasm");u(this,"waterMarkNode");u(this,"_waterMarkOption");u(this,"watermarkImageList",[]);u(this,"_beautyParams");u(this,"isUsingArTrack",!1);u(this,"_isMixScreen",!1);u(this,"_virtualBackground");u(this,"_virtualBackgroundAbortCallback");u(this,"virtualBackgroundInstance");u(this,"_bgAssetPath");u(this,"log",F.createLogger({id:"vm"}));u(this,"_checkId",0);u(this,"_use2d",!1);u(this,"_autoSwitchRenderMode",!0);u(this,"_selfieSegmentation");u(this,"encodePipeline",[]);u(this,"decodePipeline",[]);e&&(this.log.setUserId(e.userId),this.log.setSdkAppId(e.sdkAppId)),this.smallVideoContext=new Vt({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 r=e==="2d";this._use2d!==r&&(this._use2d=r,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new Vt({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(!this._glVideoContext)this._glVideoContext=new Et({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(Et.UNAVAILABLE,e=>{var r;this.emit("error",e),this.log.warn("video context unavailable",e),(r=this._virtualBackgroundAbortCallback)==null||r.call(this,e),this.update().catch(o=>{this.log.error(o)})})}catch(e){this.emit("error",e)}}enablePrintDetail(e=2e3){this._checkId=bt.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:e})}destroy(){var e,r;(e=this._2dVideoContext)==null||e.destroy(),(r=this._glVideoContext)==null||r.destroy(),this.smallVideoContext.destroy(),bt.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(Bi||this._isMixScreen||this._isMirror||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(e="videoCtxGl",r){let o=e==="videoCtxGl"?512700:512701;r?X.addFailedEvent({key:o,error:r}):X.addSuccessEvent({key:o})}checkOrCreateVideoContext(){let e=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let r=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&e===this._hasVirtualBg)this.clear();else if(r)if(this._use2d)this.clear();else return!0;else return!0}else{if(this._glVideoContext=new Et({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()}setSmallVideo(e,r){if(e){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new Od(this.smallVideoContext,e,this.log),this.smallVideoContext.on(Et.UNAVAILABLE,o=>{this.log.warn("small video context lost",o)})}if(this.smallVideoContext.frameRate=e.frameRate,this.smallDestination.resolution=e,r)this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=r:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(r),this.smallImageSource.resize(r.width,r.height),this.smallImageSource.connect(this.smallDestination));else if(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource)this.smallTrackSource.replaceTrack(this.initialTrack);else{this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource");let{width:o,height:s}=this.cameraTrack.settings;this.smallTrackSource.resize(o,s),this.smallTrackSource.connect(this.smallDestination)}}else this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource)}_setMainOutput(e){var r;try{let o=this.cameraTrack,{small:s,player:n}=o;this.setSmallVideo(s,e),Bi&&n.setCanvas(e);let d=e&&((r=this.destination)==null?void 0:r.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),d=this.arTrack),this._selfieSegmentation&&e&&!this._use2d&&(this._selfieSegmentation._glName||this._selfieSegmentation.setCanvas(e)),this.log.info(`set main output ${d?d.label:"no output track"}`),o.setOutputMediaStreamTrack(d)}catch(o){this.log.error("set main output failed",o)}}update(e=!1){return A(this,null,function*(){var s,n,d;if(!this.cameraTrack||!this.initialTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:r,profile:o}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams?(this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log})),er===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof Ei?(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 Ei?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(r.width,r.height)):e&&this.cameraNode&&this.destination?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():this.destination=new Md(this.videoContext,{name:"mainDestination",logger:this.log}),this.cameraNode=new du(this.videoContext,{input:this.initialTrack,width:r.width,height:r.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=o.frameRate,this._use2d){let m=this.cameraNode;m.disconnect(),this._isMirror&&(this.mirrorNode||(this.mirrorNode=new au(this.videoContext,this.log)),m=m.connect(this.mirrorNode),m.disconnect(),this.log.info("start mirror")),this.mixNode&&this.mixNode.close(),delete this.mixNode,(this._isMixScreen||this._hasWaterMark)&&(this.mixNode=new cu(this.videoContext,this.log),m.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption?(this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y):(s=this.waterMarkNode)==null||s.resize(r.width,r.height),(n=this.waterMarkNode)==null||n.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&!this.screenNode&&(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource")),(d=this.screenNode)==null||d.connect(this.mixNode,{zIndex:0}),m=this.mixNode,this.log.info("start mix",`${this.mixNode.width}x${this.mixNode.height}`)),m.connect(this.destination)}return this.log.info(`update ${this._use2d?"2d":"webgl"}`),this._setMainOutput(this.videoContext._canvas)})}changeInput(e){var r,o,s,n;if(e instanceof Yi)return this.log.info("change screen input",(r=e.mediaTrack)==null?void 0:r.label),this.setScreenTrack(e);if(e instanceof br)return this.log.info("change video input",(o=e.mediaTrack)==null?void 0:o.label),this.setCameraTrack(e);if(e instanceof to){this.log.info("change remote input",(s=e.mediaTrack)==null?void 0:s.label);let d=e.mediaTrack;return e.setOutputMediaStreamTrack(d)}this.log.warn("change unknown input",(n=e.mediaTrack)==null?void 0:n.label)}removeInput(e){var r;e instanceof Yi?((r=this.screenNode)==null||r.close(),delete this.screenNode,delete this.screenTrack,this.update()):e instanceof br?(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):e instanceof to&&e.source&&e.source.context.destroy()}setCameraTrack(e){return A(this,null,function*(){this.cameraTrack=e,this.update(!0)})}setScreenTrack(e){return this.screenTrack=e,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(e.mediaTrack):this.update()),e.setOutputMediaStreamTrack(e.mediaTrack)}getWatermarkImage(e,r){return A(this,null,function*(){let o=document.createElement("canvas");r&&e&&(o.height=r,o.width=e);let s=o.getContext("2d");if(!s)throw new ae({code:q.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((n,d)=>n.zIndex-d.zIndex),this.watermarkImageList.forEach(({image:n,x:d,y:m,width:l,height:g})=>{s.drawImage(n,d,m,l,g)}),As(o.toDataURL())})}pushWaterMarkImageList(e){let{type:r}=e;this.watermarkImageList.some(s=>s.imageUrl===e.imageUrl&&s.height===e.height&&s.width===e.width&&s.x===e.x&&s.y===e.y&&s.type===e.type&&s.zIndex===e.zIndex)||((r==="mute"||r==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(s=>s.type!==r)),this.watermarkImageList.push(e))}setBeautyParams(e){return A(this,null,function*(){this._beautyParams=e,this.update()})}stopBeauty(){return A(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(e){return A(this,null,function*(){var _,S;let r;try{r=yield As((e==null?void 0:e.imageElement)||e.imageUrl)}catch(v){throw new ae({code:q.INVALID_PARAMETER,message:`load image failed, url: ${e.imageUrl}`})}let{x:o=0,y:s=0,width:n=r.width,height:d=r.height,type:m="watermark",zIndex:l=2}=e;this.watermarkImageList.some(v=>v.type===m)?(this.watermarkImageList=this.watermarkImageList.filter(v=>v.type!==m),this.pushWaterMarkImageList({x:o,y:s,width:n,height:d,image:r,zIndex:l,type:m,imageUrl:e.imageUrl}),r=yield this.getWatermarkImage((_=this.cameraTrack)==null?void 0:_.settings.width,(S=this.cameraTrack)==null?void 0:S.settings.height),this._waterMarkOption={x:0,y:0,width:r.width,height:r.height,image:r},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(r.width,r.height),this.waterMarkNode.image=r):this.update()):(this.pushWaterMarkImageList({x:o,y:s,width:n,height:d,image:r,zIndex:l,type:m,imageUrl:e.imageUrl}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(v,x)=>v==="imageUrl"?void 0:x))})}deleteWatermark(e="watermark"){return A(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(r=>r.type!==e),this.log.info("delete watermark",e,JSON.stringify(this.watermarkImageList,(r,o)=>r==="imageUrl"?void 0:o)),yield this.freshWatermark()})}freshWatermark(){return A(this,null,function*(){var r,o,s;(r=this.waterMarkNode)==null||r.close(),delete this.waterMarkNode,delete this._waterMarkOption;let e=yield this.getWatermarkImage((o=this.cameraTrack)==null?void 0:o.settings.width,(s=this.cameraTrack)==null?void 0:s.settings.height);this._waterMarkOption={x:0,y:0,width:e.width,height:e.height,image:e},this.update()})}setVirtualBackground(e){return A(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 As(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 ae({code:q.INVALID_OPERATION,message:`webgl context create failed, ${this._glVideoContext.error}`})})}get mixScreen(){return this._isMixScreen}set mixScreen(e){var r;this._isMixScreen=e,this._isMixScreen||((r=this.screenNode)==null||r.close(),delete this.screenNode),this.update()}set mirror(e){var r;this._isMirror!==e&&(this._isMirror=e,this._isMirror||((r=this.mirrorNode)==null||r.close(),delete this.mirrorNode),this.update())}get mirror(){return this._isMirror}enableAr(e){this.arTrack=e,this.isUsingArTrack=!0,this.update()}updateAr(){return A(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 lu(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:r}){var o;this.encodePipeline.includes(e)||(this.encodePipeline[r]=e,(o=this.room)==null||o.enableInsertableStreams())}addDecodeProcessor({processor:e,type:r}){var o;this.decodePipeline.includes(e)||(this.decodePipeline[r]=e,(o=this.room)==null||o.enableInsertableStreams())}removeEncodeProcessor({type:e}){this.encodePipeline[e]=void 0}removeDecodeProcessor({type:e}){this.decodePipeline[e]=void 0}};J([lf(function(e){this.log.error("update failed",e)})],Pa.prototype,"update",1);var pS=0;var mu=class extends oe{constructor(e){super("room");u(this,"seq",++pS);u(this,"sdkAppId");u(this,"userId");u(this,"userSig");u(this,"privateMapKey");u(this,"latencyLevel");u(this,"tinyId");u(this,"scene");u(this,"roomId");u(this,"useStringRoomId");u(this,"role","anchor");u(this,"joinParams",null);u(this,"localTracks",new Set);u(this,"enableAutoPlayDialog",!0);u(this,"autoReceiveAudio",!0);u(this,"autoReceiveVideo",!0);u(this,"proxy_ws");u(this,"proxy_wt");u(this,"proxy_unified");u(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}});u(this,"keyPointManager");u(this,"audioManager");u(this,"videoManager");u(this,"callDurationCalculator");u(this,"badCaseDetector");u(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null});u(this,"videoDecodeFallbackType");u(this,"_isUsingCachedSchedule",!1);u(this,"_log",F.createLogger({id:`r${this.seq}`}));u(this,"_joinedTimestamp",0);u(this,"_sdkType");u(this,"heartbeatReport");u(this,"quality");u(this,"enableSEI");u(this,"isDestroyed",!1);this.useStringRoomId=!!e.useStringRoomId,dt(e.autoReceiveAudio)&&(this.autoReceiveAudio=e.autoReceiveAudio),dt(e.autoReceiveVideo)&&(this.autoReceiveVideo=e.autoReceiveVideo),dt(e.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=e.enableAutoPlayDialog),this._sdkType=e.sdkType,this.keyPointManager=new Sg({room:this,frameWorkType:e.frameWorkType,component:e.component,language:e.language}),this.callDurationCalculator=new yg({room:this}),this.badCaseDetector=new Ag({room:this}),this.audioManager=new gd(this),this.videoManager=new Pa(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 A(this,null,function*(){return this.publish(e)})}removeTrack(e){return A(this,null,function*(){return this.unpublish(e)})}replaceTrack(e){return A(this,null,function*(){})}setEncodedDataProcessingListener(e){throw new Error("Method not implemented.")}enableAIVoice(e){throw new Error("Method not implemented.")}setProxyServer(e){if(ve(e))e.startsWith("wss://")?this.proxy_ws=e:e.startsWith("https://")&&(this.proxy_wt=e);else if(xt(e)){let{websocketProxy:r,webtransportProxy:o,loggerProxy:s,scheduleProxy:n,unifiedProxy:d}=e;this.proxy_ws=r,this.proxy_wt=o,this.proxy_unified=d,d?(Gd([d,d]),Ro(`https://${d}`)):(s&&Ro(s),n&&Gd(n))}L.once(U.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:co.main,sched_back_domain:co.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return A(this,null,function*(){let e={};return this.remotePublishedUserMap.forEach(r=>{e[r.userId]=r.remoteAudioTrack.stat}),e})}getTransportStats(){return A(this,null,function*(){var r;let e={rtt:((r=this.quality)==null?void 0:r.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let o of this.quality.downlinkInfo)e.downlinksRTT[o.userId]=o.rtt;return e})}getRemoteVideoStats(){return A(this,arguments,function*(e="main"){let r={};return this.remotePublishedUserMap.forEach(o=>{let s=e==="auxiliary"?o.remoteAuxiliaryTrack:o.remoteVideoTrack;r[o.userId]=s.stat}),r})}checkDestroy(){if(this.isDestroyed)throw new ae({code:q.INVALID_OPERATION,message:$e({key:Fe.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Jt.INVALID_DESTROY),new ae({code:q.INVALID_OPERATION,message:$e({key:Fe.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,L.emit(U.ROOM_DESTROY,{room:this})}schedule(e,r){return A(this,null,function*(){var s,n,d;let o=Te();try{let{isCached:m,result:l,detailCost:g}=yield Zm({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?e.strRoomId:e.roomId,useStringRoomId:this.useStringRoomId,version:st,userSig:this.userSig,role:this.scene==="live"?e.role:void 0,frameWorkType:r,latencyLevel:e.latencyLevel});this._isUsingCachedSchedule=m,this._log.info(`schedule cache:${+m} ${ar(l,{keysToExclude:["username","credential"]})}`),m&&L.once(U.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=Z(Z({},this.scheduleResult),l),We((s=l.config)==null?void 0:s.retryCount)&&$u(l.config.retryCount),ve((n=l.config)==null?void 0:n.loggerDomain)&&Ro(l.config.loggerDomain),this.videoDecodeFallbackType=((d=l.config)==null?void 0:d.videoDecodeFallback)||this.videoDecodeFallbackType,L.emit(U.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:g}),X.addSuccessEvent({key:521700,cost:Te()-o,split:50})}catch(m){throw X.addFailedEvent({key:521700,error:m}),m}})}sendAbilityStatus(e){}enableInsertableStreams(){return Promise.resolve()}};function vg(i,t=!1){let e=Object.defineProperties(It(),{postMessage:{value:i.postMessage.bind(i)},port:{get(){return i},set(o){i.onmessage=Be,i.onmessageerror=Be,i=o,r()}}});function r(){i.onmessage=o=>{o.data?o.ports.length||t?e.next(o):e.next(o.data):(e.complete(),i.close())},i.onmessageerror=o=>{e.error(o),i.close()}}return r(),e}var gp=class extends me{constructor(t,e){super(t);let r=new me(t);r.next=Be,e(r)}},T1=ge(gp,"takeUntilComplete");var Nt={useWt:!0,useAINS:!0,useHardDecoder:"prefer-software",useHardEncoder:"prefer-software",unreliable:!1,debug:!1,assetsPath:"",enableUpload:!0},Cg="__INLINE__WORKER__",Dg="__INLINE__WASM__",{debug:Ng}=console;Nt.debug||(console.debug=()=>{});var hS=!Cg.startsWith("__"),fS=!Dg.startsWith("__");function pu(){let i=Mo(`${Nt.assetsPath?`${Nt.assetsPath}/`:""}worker.js`);return hS?URL.createObjectURL(new Blob([atob(Cg)],{type:"application/javascript"})):i.startsWith("http")?fetch(i).then(t=>t.blob().then(e=>URL.createObjectURL(e))):i}var xa;function hu(){return A(this,null,function*(){let i=Nt.assetsPath?`${Nt.assetsPath}/`:"";return xa||(fS?xa=new TextEncoder().encode(atob(Dg)).buffer:xa=yield fetch(Mo(`${i}av_processing.wasm`)).then(t=>t.arrayBuffer()),xa)})}var Ep=class{constructor(){u(this,"playPort");u(this,"playPortSent",!1);u(this,"worklet");u(this,"workletPromise")}init(){return this.workletPromise||(this.workletPromise=this._init()),this.workletPromise}_init(){return A(this,null,function*(){let t=Ke("player"),e=pu();try{yield t.audioWorklet.addModule(typeof e=="string"?e:yield e),F.info("global audio player worklet addModule success",e)}catch(r){throw F.error("global audio player worklet addModule failed:",r),r}return this.worklet=new AudioWorkletNode(t,"global-audio-player",{processorOptions:{wasm:yield hu(),flag:Nt},numberOfInputs:2}),F.info("global audio player worklet created",t.state),this.worklet.connect(t.destination),this.playPort=this.worklet.port,this.playPort})}playAudio(t){return A(this,null,function*(){this.playPortSent||(this.playPortSent=!0,t(yield this.init()))})}},fu=new Ep;var _p=(()=>{if(typeof self=="undefined")return!1;if(!("top"in self&&self!==top)){if("showOpenFilePicker"in self)return"showOpenFilePicker"}return!1})(),C1=_p?Promise.resolve().then(function(){return TS}):Promise.resolve().then(function(){return RS});var D1=_p?Promise.resolve().then(function(){return SS}):Promise.resolve().then(function(){return CS});var gS=_p?Promise.resolve().then(function(){return AS}):Promise.resolve().then(function(){return NS});function Tp(...i){return A(this,null,function*(){return(yield gS).default(...i)})}var ES=i=>A(void 0,null,function*(){let t=yield i.getFile();return t.handle=i,t}),_S=(...t)=>A(void 0,[...t],function*(i=[{}]){Array.isArray(i)||(i=[i]);let e=[];i.forEach((s,n)=>{e[n]={description:s.description||"Files",accept:{}},s.mimeTypes?s.mimeTypes.map(d=>{e[n].accept[d]=s.extensions||[]}):e[n].accept["*/*"]=s.extensions||[]});let r=yield window.showOpenFilePicker({id:i[0].id,startIn:i[0].startIn,types:e,multiple:i[0].multiple||!1,excludeAcceptAllOption:i[0].excludeAcceptAllOption||!1}),o=yield Promise.all(r.map(ES));return i[0].multiple?o:o[0]}),TS={__proto__:null,default:_S};function gu(i){function t(e){if(Object(e)!==e)return Promise.reject(new TypeError(e+" is not an object."));var r=e.done;return Promise.resolve(e.value).then(function(o){return{value:o,done:r}})}return gu=function(e){this.s=e,this.n=e.next},gu.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var r=this.s.return;return r===void 0?Promise.resolve({value:e,done:!0}):t(r.apply(this.s,arguments))},throw:function(e){var r=this.s.return;return r===void 0?Promise.reject(e):t(r.apply(this.s,arguments))}},new gu(i)}var wg=(o,s,...n)=>A(void 0,[o,s,...n],function*(i,t,e=i.name,r){let d=[],m=[];var l,g=!1,_=!1;try{for(var S,v=function(x){var P,M,G,se=2;for(typeof Symbol!="undefined"&&(M=Symbol.asyncIterator,G=Symbol.iterator);se--;){if(M&&(P=x[M])!=null)return P.call(x);if(G&&(P=x[G])!=null)return new gu(P.call(x));M="@@asyncIterator",G="@@iterator"}throw new TypeError("Object is not async iterable")}(i.values());g=!(S=yield v.next()).done;g=!1){let x=S.value,P=`${e}/${x.name}`;x.kind==="file"?m.push(x.getFile().then(M=>(M.directoryHandle=i,M.handle=x,Object.defineProperty(M,"webkitRelativePath",{configurable:!0,enumerable:!0,get:()=>P})))):x.kind!=="directory"||!t||r&&r(x)||d.push(wg(x,t,P,r))}}catch(x){_=!0,l=x}finally{try{g&&v.return!=null&&(yield v.return())}finally{if(_)throw l}}return[...(yield Promise.all(d)).flat(),...yield Promise.all(m)]}),IS=(...t)=>A(void 0,[...t],function*(i={}){i.recursive=i.recursive||!1,i.mode=i.mode||"read";let e=yield window.showDirectoryPicker({id:i.id,startIn:i.startIn,mode:i.mode});return wg(e,i.recursive,void 0,i.skipDirectory)}),SS={__proto__:null,default:IS},yS=(s,...n)=>A(void 0,[s,...n],function*(i,t=[{}],e=null,r=!1,o=null){Array.isArray(t)||(t=[t]),t[0].fileName=t[0].fileName||"Untitled";let d=[],m=null;if(i instanceof Blob&&i.type?m=i.type:i.headers&&i.headers.get("content-type")&&(m=i.headers.get("content-type")),t.forEach((_,S)=>{d[S]={description:_.description||"Files",accept:{}},_.mimeTypes?(S===0&&m&&_.mimeTypes.push(m),_.mimeTypes.map(v=>{d[S].accept[v]=_.extensions||[]})):m?d[S].accept[m]=_.extensions||[]:d[S].accept["*/*"]=_.extensions||[]}),e)try{yield e.getFile()}catch(_){if(e=null,r)throw _}let l=e||(yield window.showSaveFilePicker({suggestedName:t[0].fileName,id:t[0].id,startIn:t[0].startIn,types:d,excludeAcceptAllOption:t[0].excludeAcceptAllOption||!1}));!e&&o&&o(l);let g=yield l.createWritable();return"stream"in i?(yield i.stream().pipeTo(g),l):"body"in i?(yield i.body.pipeTo(g),l):(yield g.write(yield i),yield g.close(),l)}),AS={__proto__:null,default:yS},bS=(...t)=>A(void 0,[...t],function*(i=[{}]){return Array.isArray(i)||(i=[i]),new Promise((e,r)=>{let o=document.createElement("input");o.type="file";let s=[...i.map(l=>l.mimeTypes||[]),...i.map(l=>l.extensions||[])].join();o.multiple=i[0].multiple||!1,o.accept=s||"",o.style.display="none",document.body.append(o);let n=l=>{typeof d=="function"&&d(),e(l)},d=i[0].legacySetup&&i[0].legacySetup(n,()=>d(r),o),m=()=>{window.removeEventListener("focus",m),o.remove()};o.addEventListener("click",()=>{window.addEventListener("focus",m)}),o.addEventListener("change",()=>{window.removeEventListener("focus",m),o.remove(),n(o.multiple?Array.from(o.files):o.files[0])}),"showPicker"in HTMLInputElement.prototype?o.showPicker():o.click()})}),RS={__proto__:null,default:bS},vS=(...t)=>A(void 0,[...t],function*(i=[{}]){return Array.isArray(i)||(i=[i]),i[0].recursive=i[0].recursive||!1,new Promise((e,r)=>{let o=document.createElement("input");o.type="file",o.webkitdirectory=!0;let s=d=>{typeof n=="function"&&n(),e(d)},n=i[0].legacySetup&&i[0].legacySetup(s,()=>n(r),o);o.addEventListener("change",()=>{let d=Array.from(o.files);i[0].recursive?i[0].recursive&&i[0].skipDirectory&&(d=d.filter(m=>m.webkitRelativePath.split("/").every(l=>!i[0].skipDirectory({name:l,kind:"directory"})))):d=d.filter(m=>m.webkitRelativePath.split("/").length===2),s(d)}),"showPicker"in HTMLInputElement.prototype?o.showPicker():o.click()})}),CS={__proto__:null,default:vS},DS=(e,...r)=>A(void 0,[e,...r],function*(i,t={}){Array.isArray(t)&&(t=t[0]);let o=document.createElement("a"),s=i;"body"in i&&(s=yield function(m,l){return A(this,null,function*(){let g=m.getReader(),_=new ReadableStream({start:x=>function P(){return A(this,null,function*(){return g.read().then(({done:M,value:G})=>{if(!M)return x.enqueue(G),P();x.close()})})}()}),S=new Response(_),v=yield S.blob();return g.releaseLock(),new Blob([v],{type:l})})}(i.body,i.headers.get("content-type"))),o.download=t.fileName||"Untitled",o.href=URL.createObjectURL(yield s);let n=()=>{typeof d=="function"&&d()},d=t.legacySetup&&t.legacySetup(n,()=>d(),o);return o.addEventListener("click",()=>{setTimeout(()=>URL.revokeObjectURL(o.href),3e4),n()}),o.click(),null}),NS={__proto__:null,default:DS};var Ip=class{constructor(t){this.name=t;u(this,"ready");u(this,"worker");u(this,"ports");u(this,"ids",1);u(this,"transactions",new Map);u(this,"log");u(this,"addTransaction",t=>(this.transactions.set(++this.ids,t),this.ids))}postMessage(t,e){var r;(r=this.worker)==null||r.postMessage(t,e)}create(t){return A(this,null,function*(){if(this.ready)return this.ready;t||(t=this.name),console.time(`createWorker_${t}`);let e=pu(),r=new Worker(typeof e=="string"?e:yield e,{name:t});return this.worker=r,this.ready=new Promise((o,s)=>A(this,null,function*(){r.onmessage=({data:{id:n,type:d,payload:m}})=>{var l;if(n)(l=this.transactions.get(n))==null||l(m),this.transactions.delete(n);else switch(d){case"error":console.timeEnd(`createWorker_${t}`),console.warn("worker error:",m),s(m);break;case"ready":console.timeEnd(`createWorker_${t}`),o(this);break;case"updateAFSM":if(m.value){let g=typeof m.old=="string"?m.old:`${m.old.action}ing`,_=typeof m.value=="string"?m.value:`${m.value.action}ing`;console.log(fc(),m.group,m.name,g,"\u{1F449}",_)}break;case"log":console.log(m);break;case"glog":window.dispatchEvent(new CustomEvent(d,{detail:m}));break}},r.postMessage({wasm:yield hu(),flag:Nt},this.ports)}))})}destroy(){var t;console.log("destroy worker",this.name),delete this.ready,(t=this.worker)==null||t.terminate()}},Sp=class{constructor(t,e,r){this.worker=t;u(this,"channel",new MessageChannel);u(this,"ready");this.ready=new Promise((o,s)=>{this.worker.postMessage({id:this.worker.addTransaction(o),payload:e},[this.channel.port2])}).then(o=>(o.err===0&&(this.worker.sessionCount++,this.channel.port1.onmessage=r),o))}postMessage(...t){this.channel.port1.postMessage(...t)}destroy(){--this.worker.sessionCount===0&&this.worker.destroy()}},yp=class i extends Ip{constructor(){super("main");u(this,"switchValue",new Map);u(this,"extendChannel");u(this,"sessionCount",0)}setSwitchValue(e,r){var o;this.switchValue.set(e,r),(o=this.extendChannel)==null||o.port1.postMessage([e,r])}create(){return A(this,null,function*(){return this.ready?this.ready:(this.extendChannel=new MessageChannel,this.ports=[this.extendChannel.port2],yield Bt(i.prototype,this,"create").call(this),this.switchValue.forEach((e,r)=>{this.extendChannel.port1.postMessage([r,e])}),this)})}},uo=new yp,is,wS=-1;function Mg(i){return console.log(i),is.push(i.slice()),is.length>1e3&&is.shift(),i}function Og(i){return A(this,null,function*(){switch(wS){case 0:this.edpl.willDecodeAudio=Mg;break;case 2:this.edpl.didEncodeAudio=Mg;break}yield uo.create(),L.emit(U.JOIN_SEND_CMD,{room:this});let t=new Sp(uo,i,o=>{let s=o.data;if(typeof s=="string")this.onWorkerEvent(s);else if(s==null)this.onWorkerEvent("client-banned",0),t.destroy();else{let{cmd:n,payload:d}=s;this.onWorkerEvent(n,d)}}),{err:e,data:r}=yield t.ready;if(typeof e=="number"){if(L.emit(U.JOIN_RECEIVED_CMD_RES,{room:this,code:e}),e===0)return Object.assign(this,r,{session:t});throw new ae({code:q.JOIN_ROOM_FAILED,extraCode:Number(e),message:$e({key:Fe.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:e,errorMsg:""}})})}else throw e})}Object.defineProperties(window,{useAINS:{set:Ap},useWt:{set:MS},enableDebug:{set(i){console.debug=i?Ng:()=>{},uo.setSwitchValue("enableDebug",i)}},useV2:{set:bp},dump:{value(){if(is||(console.warn("dump audio will be activated at next time join room"),is=[]),!is.length){console.warn("no audio data to dump,try it later");return}let i=[];return is.forEach(t=>{i.push(new Uint16Array([t.length])),i.push(t)}),Tp(new Blob(i),{fileName:"audio dump hex",extensions:[".hex"]})}},dumpAudio:{value(i="audio",t=2e3){let e=[],r=new Promise(o=>{let s=new MessageChannel;uo.extendChannel.port1.postMessage(["dump",i],[s.port1]),s.port2.onmessage=({data:n})=>{console.log(n),e.push(n),e.length>t&&(s.port2.onmessage=null,uo.extendChannel.port1.postMessage(["dump",i]),s.port2.close(),o(new Blob(e)))}});return Tp(r,{fileName:i,extensions:[".pcm"]})}},hardDec:{set(i){switch(i){case!0:Nt.useHardDecoder="prefer-hardware";break;case!1:Nt.useHardDecoder="prefer-software";break;default:Nt.useHardDecoder="no-preference"}}}});function Ap(i){return A(this,null,function*(){uo.setSwitchValue("useAINS",i)})}function bp(i){return A(this,null,function*(){uo.setSwitchValue("useV2",i)})}function MS(i){return A(this,null,function*(){uo.setSwitchValue("useWt",i)})}function Pg(i){let t=new MediaStreamTrackGenerator({kind:"audio"});i.setInputMediaStreamTrack(t),this.postMessage({cmd:"pullAudio",payload:{tinyId:i.tinyId,writable:t.writable}},[t.writable])}function xg(i){return A(this,null,function*(){var o;this._log.info("pull video",i);let t=Date.now(),e=0,r=new MessageChannel;this.postMessage({cmd:"pullVideo",payload:{mediaType:i.mediaType,tinyId:i.tinyId}},[r.port1]),(o=i.stat).framesReceived||(o.framesReceived=0),ye(vg(r.port2),Xe(Ce(i,oe.INIT)),ke(s=>{let{data:n,packetsReceived:d}=s;i.stat.packetsReceived=d,i.stat.framesReceived++,e++;let m=n[4]&31;if(e<=10){let g=Array.from(n.slice(0,10)).map(_=>_.toString(16).padStart(2,"0")).join(" ");this._log.info(`Frame ${e} - Size: ${n.length} bytes, Type: ${m}, Timestamp: ${Date.now()-t}ms First 10 bytes: ${g}`)}let l;switch(m){case 5:case 7:l="key";break;default:l="delta";break}i.isAvailable?i.decodeFrame({data:n.buffer,type:l,timestamp:(Date.now()-t)*1e3}):console.warn("track is not available")},()=>{},()=>{r.port2.postMessage(null),r.port2.close()}))})}var Eu=[];function Lg(i){var m;let t=It();if(this.state!=="joined")throw new Error("Room is not joined");if(i.state==="publish")return;for(let l=0;l<=Eu.length;l++)if(!Eu[l]){Eu[l]=this,this.index=l;break}let e=i.profile;this._log.info("start push audio",this.index,e);let r=new MessageChannel,o=i.enableEncodeFrame?new MessageChannel:null;(m=this.session)==null||m.postMessage({cmd:"pushAudio",payload:Z({index:this.index},e)},o?[r.port2,o.port2]:[r.port2]),r.port1.onmessage=l=>{l.data==null||(typeof l.data=="number"?t.next(l.data):o&&o.port1.postMessage(Ee(Z({},l.data),{data:new Uint8Array(i.encodeFrame({data:l.data.data.buffer,timestamp:l.data.timestamp}).data)})))};let s=new MediaStream,n,d=l=>{let g=s.getAudioTracks()[0];g&&(n.disconnect(),s.removeTrack(g)),s.addTrack(l),this._log.info("push audio track:",l.readyState,l.getSettings().deviceId),n=Ke("player").createMediaStreamSource(s),n.connect(fu.worklet,0,this.index)};ye(Ce(i,"output-media-track-changed"),Xe(Ce(i,"capture")),ke(d,console.error,()=>{this._log.info("stop push audio",e),i.volume=0,n.disconnect(),Eu[this.index]=null,o&&o.port1.postMessage(null),r.port1.postMessage(null)})),ye(t,Ia(l=>i.volume=l),gi(wd(1e3)),ke(()=>{i.volume=0})),d(i.outMediaTrack)}var cF=new Intl.DateTimeFormat("zh-CN",{dateStyle:"short",timeStyle:"medium"});var Rp=class{constructor(t,e,r,o){this.localTrack=t;this.type=e;this.config=r;this.port=o;u(this,"track");u(this,"label");u(this,"insertKeyFrame",!0);u(this,"encoder");u(this,"tsMap",new Map);t._log.info("create Video Encoder",r)}trans(t,e,r){return A(this,null,function*(){let o=yield this.recreate(r);e.signal.addEventListener("abort",()=>{o.close()});let s=0;return t.pipeThrough(new TransformStream({transform:(n,d)=>{o.state==="configured"&&(this.tsMap.set(s,Date.now()),this.encode(n),s++,d.enqueue(n))}}),e)})}encode(t){this.encoder.encode(t,{keyFrame:this.insertKeyFrame}),this.insertKeyFrame=!1}start(t,e,r){return A(this,null,function*(){let o=yield this.recreate(r),s=0;t.pipeTo(new WritableStream({write:n=>{o.state==="configured"&&(s<10&&this.localTrack.log.info(`capture ${this.label} track frame:`,s,Date.now(),n.timestamp,n.displayWidth,n.displayHeight),(n.displayWidth!==this.config.width||n.displayHeight!==this.config.height)&&(this.localTrack.log.info("resize video track frame:",n.displayWidth,n.displayHeight,this.config.width,this.config.height),this.configure({width:n.displayWidth,height:n.displayHeight})),this.tsMap.set(s,Date.now()),this.encode(n),s<10&&this.localTrack.log.info(`encode ${this.label} track frame:`,s),s++,n.close())}}),e).catch(n=>{this.localTrack.log.warn(n),o.close()})})}recreate(t,e=0){return A(this,null,function*(){let r=0,o=new VideoEncoder({output:s=>{let n=this.tsMap.get(r);if(this.tsMap.delete(s.timestamp),r<10&&(r===0&&e===0&&L.emit(U.SEND_FIRST_VIDEO_FRAME,{room:t}),this.localTrack.log.info(`encoded ${this.label} track frame:`,r,Date.now(),s.timestamp)),r++,this.track.enabled===!1)return;let d=null;if(this.localTrack.enableEncodeFrame){d=new Uint8Array(s.byteLength),s.copyTo(d);let m=this.localTrack.encodeFrame({data:d.buffer},this.type===3);d=new Uint8Array(m.data)}d?(this.localTrack.stat.bytesSent+=d.length,this.port.postMessage({chunk:{type:s.type,timestamp:s.timestamp,data:d,duration:s.duration},timestamp:n},[d.buffer])):(this.localTrack.stat.bytesSent+=s.byteLength,this.port.postMessage({chunk:s,timestamp:n}))},error:s=>{this.localTrack.log.warn(s,this.config),setTimeout(()=>this.recreate(t,e+1),100)}});return this.encoder=o,yield this.configure({}),o})}configure(t){return A(this,null,function*(){var e;Object.assign(this.config,t);for(let r=0;r<=rs.length;r++){let{supported:o}=yield VideoDecoder.isConfigSupported(this.config);if(o)break;if(r===rs.length)return;rs[r](this.config)}(e=this.encoder)==null||e.configure(this.config)})}close(){this.port.postMessage(null),this.port.close()}};function _u(i,t){return A(this,null,function*(){let e=i.mediaType===2,r=e?"screen":"video",o={codec:"avc1.640028",latencyMode:"realtime",avc:{format:"annexb"},hardwareAcceleration:Nt.useHardEncoder,width:t.profile.width,height:t.profile.height,framerate:t.profile.frameRate,bitrate:t.profile.bitrate*1e3},s=new MessageChannel;this.postMessage({cmd:"pushVideo",payload:t},[s.port1]);let n=new Rp(i,t.type,o,s.port2);return s.port2.onmessage=d=>{if(d.data===260)n.insertKeyFrame=!0;else if(!e){let{bitrate:m}=d.data;Cn({configureBr:[d.data.bitrate,m]}),n.configure({bitrate:m})}},this._log.info("start push",r,t),n})}function Ug(i){return A(this,null,function*(){var g;let t=i.mediaType===2,e=t?"screen":"video",r={type:t?7:2,profile:i.profile,trackType:t?"screen":"camera",crypto:!!((g=i.manager)!=null&&g.encodePipeline[0])};!t&&i.outMediaTrack instanceof CanvasCaptureMediaStreamTrack&&(r.trackType="canvas");let{trackType:o}=r,{width:s,height:n}=i.outMediaTrack.getSettings();r.profile.width=s,r.profile.height=n;let d=yield _u.call(this,i,r);this._log.info("VideoEncoder created",r);let m,l=_=>A(this,null,function*(){if(m==null||m.abort("track changed"),!_)return;m=new AbortController;let{width:S,height:v,displaySurface:x}=_.getSettings();S&&(d.config.width=S),v&&(d.config.height=v);let P=Kt.match(/Chrome\/(\d+)/);(P==null?void 0:P[1])==="114"&&x==="browser"&&delete d.config.hardwareAcceleration,this._log.info("push",e,"track:",_.readyState,_.getSettings());let M;if(typeof MediaStreamTrackProcessor!="undefined")M=new MediaStreamTrackProcessor({track:_}).readable;else{let se;M=new ReadableStream({pull(ne){return A(this,null,function*(){if(li())return new Promise(Ae=>{var ie;(ie=i.player.element)==null||ie.requestVideoFrameCallback((Pe,Le)=>{let po=new VideoFrame(i.player.element);ne.enqueue(po),Ae()})})})}})}let G="small"in i&&i.small;return G?(this.smallEncoder||(this.smallEncoder=yield _u.call(this,i,{profile:G,type:3,trackType:o})),this.smallEncoder.track=_,this.smallEncoder.label="small",M=yield this.smallEncoder.trans(M,m,this)):this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder),d.track=_,d.label=e,d.start(M,m,this)});return ye(Ce(i,"output-media-track-changed"),Xe(Ce(i,"capture")),ke(l,console.error,()=>{var _;this._log.info("stop push",e,r),m.abort("unpublish"),d.close(),(_=this.smallEncoder)==null||_.close()})),l(i.outMediaTrack)})}var lo=class lo extends oe{constructor(e){var r,o;super((o=(r=e.roomid)==null?void 0:r.toString())!=null?o:e.name,"volumeEvaluation");this.room=e;u(this,"enableInBackground",!1);u(this,"interval",400);e.on("joined",()=>{this.emit(lo.INTERVALCHANGED,this.interval)}),ye(Ce(this,lo.INTERVALCHANGED),eo(s=>this.room.state==="joined"?this.room.fromWorker("getAudioEnergy",s):ye(Mf(s),Ki(()=>[]))),ke(s=>{s.forEach(n=>{this.room.remotePublishedUserMap.has(n.userId)&&(this.room.remotePublishedUserMap.get(n.userId).remoteAudioTrack.volume=n.volume)}),(!document.hidden||this.enableInBackground)&&this.state==oe.ON&&this.room.emit("audio-volume",s)}))}start(e,r){this.interval=e,this.enableInBackground=r,this.emit(lo.INTERVALCHANGED,this.interval)}stop(){}};u(lo,"INTERVALCHANGED","intervalChanged"),J([Je([oe.INIT,oe.OFF],oe.ON)],lo.prototype,"start",1),J([Je([],oe.OFF)],lo.prototype,"stop",1);var Tu=lo;var mo=class mo extends mu{constructor(e){super(e);u(this,"index",0);u(this,"session");u(this,"tinyid");u(this,"roomid");u(this,"openid");u(this,"socketid");u(this,"relayip");u(this,"clientip");u(this,"remotePublishedUserMap",new Map);u(this,"bussinessInfo");u(this,"token");u(this,"audioVolumeEvalution",new Tu(this));u(this,"enableAIVoice",Ap);u(this,"AbilityOption",{AVLimit:{EncVideoCodec:"H265",EncVideoWidth:0,EncVideoHeight:0,EncVideoBr:"0",EncVideoFps:0,EncAudioCodec:"opus",EncAudioFS:0,EncAudioCh:0,EncAudioBr:"0"},GeneralLimit:{CPULimit:{uint32_CPU_num:navigator.hardwareConcurrency||0,str_CPU_name:navigator.platform,uint32_CPU_maxfreq:0,model:"",uint32_total_memory:0},uint32_terminal_type:ul(),uint32_device_type:0,str_os_verion:ll(),uint32_link_type:1,str_client_version:st,uint32_net_type:vo[Ur.getNetworkType()],ua:navigator.userAgent,version:""}});u(this,"joinAbortController",new AbortController);u(this,"smallAbortCtrl");u(this,"smallEncoder");e.tinyId&&(this.tinyId=e.tinyId,bp(!0)),this._log||(this._log=e.logger),this.bussinessInfo=e.bussinessInfo,e.encodedDataProcessingListener&&this.setEncodedDataProcessingListener(e.encodedDataProcessingListener)}replaceTrack(e){return A(this,null,function*(){})}getLogger(){return this._log}postMessage(e,r){this.session&&(e?typeof e=="string"?this.session.postMessage({cmd:e,payload:r}):this.session.postMessage(e,r):this.session.postMessage(null))}sendMessage(e,r){return new Promise((o,s)=>{this.state!="joined"&&s("join room first");let n=new MessageChannel;this.postMessage({cmd:e,payload:r},[n.port1]),n.port2.onmessageerror=s,n.port2.onmessage=d=>{n.port2.close(),o(d.data)}})}fromWorker(e,r){if(this.state!="joined")throw"join room first";return o=>{var n;let s=new MessageChannel;s.port2.onmessage=d=>{d.data?o.next(d.data):o.complete()},s.port2.onmessageerror=d=>o.error(d),o.defer(()=>{s.port2.postMessage(null),s.port2.close()}),(n=this.session)==null||n.postMessage({cmd:e,payload:r},[s.port1])}}switchRole(e){return A(this,null,function*(){if(e!==this.role)return this._log.info(`switchRole() => switch role to: ${e}`),e=="audience"&&this.unpublish(...this.localTracks),this.sendMessage("switchRole",e=="audience"?21:20).then(r=>{this.role=e})})}join(e,r,o){return A(this,null,function*(){var m,l,g;let s=Ur.getEnv(),n=Qc(),d={isH264EncodeSupported:this.checkSystemResult.detail.isH264EncodeSupported,isVp8EncodeSupported:this.checkSystemResult.detail.isVp8EncodeSupported,frameWorkType:o,params:e,proxy_wt:(m=this.proxy_wt)==null?void 0:m.replace("https://",""),proxy_ws:(l=this.proxy_ws)==null?void 0:l.replace("wss://",""),proxy_cloud:(g=this.scheduleResult.iceServers)!=null&&g.length?this.scheduleResult.iceServers[0].urls:[],proxy_unified:this.proxy_unified,domains:this.scheduleResult.domains,env:s,osName:xs(),browserInfo:Qc(),tinyId:this.tinyId,joinReq:{useStrRoomid:!!this.useStringRoomId,roomid:String(e.roomId||e.strRoomId),sdkAppID:String(e.sdkAppId),userSig:e.userSig,privMapEncrypt:e.privateMapKey||"",privMap:"",pstnBizType:0,role:"user",jsSdkVersion:st,browserVersion:n.browserName+n.browserVersion,closeLocalMedia:!0,trtcscene:r==="live"?2:1,trtcrole:e.role,bussinessInfo:e.businessInfo||this.bussinessInfo||"",isAuxUser:0,autoSubscribe:this.autoReceiveAudio&&this.autoReceiveVideo,AbilityOption:this.AbilityOption}};yield Og.call(this,d),console.log(this),fu.playAudio(_=>this.postMessage({cmd:"setAudioWorkletPort"},[_])),this.checkDestroy()})}leave(){return A(this,null,function*(){this.remotePublishedUserMap.forEach(e=>{e.remoteAudioTrack.close(),e.remoteAuxiliaryTrack.close(),e.remoteVideoTrack.close()}),this.postMessage(null),this.remotePublishedUserMap.clear(),this.localTracks.forEach((e,r)=>r.unpublish())})}getSignalInfo(){return{tinyId:this.tinyid,clientIp:this.clientip,signalIp:"",relayIp:this.relayip,relayInnerIp:"",relayPort:0}}enableAudioVolumeEvaluation(e=2e3,r=!1){e<=0?this.audioVolumeEvalution.stop():this.audioVolumeEvalution.start(e,r)}getLocalAudioStats(){return this.sendMessage("getLocalAudioStats")}getLocalVideoStats(){return this.sendMessage("getLocalVideoStats")}afterJoin(){return A(this,null,function*(){let e=Xe(Ce(this,"left"));ye(r=>A(this,null,function*(){let o=new MessageChannel;o.port2.onmessage=s=>{s.data?r.next({data:s.data,port:o.port2}):r.complete()},o.port2.onmessageerror=s=>r.error(s),r.defer(()=>{o.port2.postMessage(null),o.port2.close()}),this.postMessage({cmd:"decodeAudio",payload:!!this.audioManager.decodePipeline[0]},[o.port1])}),e,ke(({data:r,port:o})=>{let s=this.audioManager.decodePipeline[0]({frame:{data:r.data.buffer}});o.postMessage(Ee(Z({},r),{data:new Uint8Array(s.data)}),[s.data])}))})}onWorkerEvent(e,r){switch(e!=="network-quality"&&console.info(this.userId,"onWorkerEvent",e,JSON.stringify(r)),e){case U.RECEIVED_PUBLISHED_USER_LIST:L.emit(e,Z({room:this},r));return;case"1":if(r.userId===this.userId)return;this.emit("peer-join",r);return;case"2":this.emit("peer-leave",r);return;case"3":let o=new ou(this,r);this.remotePublishedUserMap.set(r.userId,o),this.emit("remote-published",o);return;case"5":{let _=r,S=this.remotePublishedUserMap.get(_);S&&(S.remoteVideoTrack.close(),S.remoteAuxiliaryTrack.close(),S.remoteAudioTrack.close(),this.remotePublishedUserMap.delete(_),this.emit("remote-unpublished",S))}return;case"banned":switch(r){case 8:this.emit("banned",{reason:"kick",message:""});return;case 2:case 6:case 4:this.emit("banned",{reason:"banned",message:""});return;case 7:case 5:this.emit("banned",{reason:"room_disband",message:""});return}break;case"6":{let{prevMuteState:_,muteState:S,flag:v}=r,x=this.remotePublishedUserMap.get(S.userId);if(!x){this.emit("remote-publish-state-changed",r);return}x.flag=v}L.emit(U.REMOTE_PUBLISH_STATE_CHANGED,Z({room:this},r)),this.emit("remote-publish-state-changed",r);return;case"network-quality":this.quality=Z({},r);let{uplinkLoss:s,uplinkRTT:n,uplinkInfo:d,downlinkInfo:m,msg_down_stream_info:l}=r,g={str_sdk_version:st,uint64_datetime:Date.now(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyid},msg_device_info:{uint32_terminal_type:15,str_device_name:navigator.platform,str_os_version:"",uint32_net_type:vo[vn()]},msg_event_msg:Of(this.userId),str_acc_ip:this.relayip,str_client_ip:this.clientip,msg_up_stream_info:d,msg_down_stream_info:l};L.emit(U.HEARTBEAT_REPORT,{room:this,report:g}),this.emit("heartbeat-report",g),L.emit(U.NETWORK_QUALITY,{room:this,uplink:{rtt:n,loss:s},downlinks:m}),delete r.downlinkInfo;break;case"signal-connection-state-changed":L.emit(U.SIGNAL_CONNECTION_STATE_CHANGED,Z({room:this},r));return}this.emit(e,r)}sendStartPublishCDN(e,r){return e.roomid=this.roomId,e.sdkAppID=String(this.sdkAppId),e.socketid=this.socketid,r&&(e.request_time=e.pushRequestTime),this.sendMessage("publishCdn",e)}sendStopPublishCDN(e,r){return e.roomid=this.roomId,e.sdkAppID=String(this.sdkAppId),e.socketid=this.socketid,r&&(e.request_time=e.pushRequestTime),this.sendMessage("stopPublishCdn",e)}sendStartMixTranscode(e){return this.sendMessage("startMcuMix",e)}sendStopMixTranscode(e){return this.sendMessage("stopMcuMix",e)}publish(...e){return A(this,null,function*(){let r=e.reduce((d,m)=>m.mediaType|d,0),o=this.sendMessage("publish",r).then(d=>d.err!==0?Promise.reject(d.err):d),s=0,n=d=>A(this,null,function*(){switch(yield o,d.muted&&(s|=d.mediaType),Lt(d,d).add("mute",()=>{this.postMessage("mute",{mediaType:d.mediaType,userId:this.userId,srctinyid:this.tinyid,remove:!0})}).add("unmute",()=>{this.postMessage("unmute",{mediaType:d.mediaType,userId:this.userId,srctinyid:this.tinyid,add:!0})}),d.mediaType){case 1:Lg.call(this,d);break;default:yield Ug.call(this,d)}});yield Promise.all(e.map(n)),s&&this.postMessage("mute",{mediaType:s,srctinyid:this.tinyid,userId:this.openid,remove:!0})})}unpublish(...e){return A(this,null,function*(){e.forEach(pt)})}subscribe(...e){return A(this,null,function*(){let r=e.reduce((_,S)=>S.mediaType|_,0),{userId:o,tinyId:s,streamType:n}=e[0],d=this.remotePublishedUserMap.get(o),m=Z({},d.subscribeState),l=Object.assign(new Jn,m);l.mediaType|=r,L.emit(U.SUBSCRIBE_START,{room:this,streamType:n,remotePublishedUser:d,subscribeState:l});let g=yield this.sendMessage("subscribe",{mediaType:l.mediaType,userId:o,srctinyid:s,mediaDescription:{audioParam:{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]},videoParam:[4,8,2].filter(_=>l.mediaType&_).map(_=>({mediaType:_,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]}))}});console.dir("subscribe",g),yield Promise.all(e.filter(_=>!_.isSubscribed).map(_=>{switch(_.mediaType){case 1:return Pg.call(this,_);default:return xg.call(this,_)}})),L.emit(U.SUBSCRIBE_SUCCESS,{room:this,streamType:n,remotePublishedUser:d})})}unsubscribe(...e){return A(this,null,function*(){let r=0;for(let o of e)r|=o.mediaType;if(e.length){let{userId:o,streamType:s,tinyId:n}=e[0];yield this.sendMessage("unSubscribe",{mediaType:r,srctinyid:n,userId:o});for(let d of e)d.unsubscribe();L.emit(U.UNSUBSCRIBE_SUCCESS,{room:this,streamType:s,remotePublishedUser:this.remotePublishedUserMap.get(o)})}})}enableSmall(e){return A(this,null,function*(){var r;if(e){if(this.videoManager.smallTrack){let o=this.videoManager.cameraTrack;this.smallEncoder=yield _u.call(this,o,{profile:o.small,type:3,trackType:"camera"});let s=new MediaStreamTrackProcessor({track:this.videoManager.smallTrack}).readable;this.smallEncoder.track=this.videoManager.smallTrack,this.smallEncoder.label="small",this.smallAbortCtrl=new AbortController,this.smallEncoder.start(s,this.smallAbortCtrl,this),this._log.info("push small")}}else(r=this.smallAbortCtrl)==null||r.abort("stop"),this.smallEncoder&&(this.smallEncoder.close(),delete this.smallEncoder)})}changeType(e,r){let o=this.remotePublishedUserMap.get(r.userId),s=e?8:4;if(o.remoteVideoTrack.mediaType===s)return;let n={srctinyid:r.tinyId,mediaType:s,userId:r.userId,mediaDescription:{audioParam:{mediaType:1,payloadFmtps:[{payloadType:111,fmtp:"minptime=10;useinbandfec=1"}]},videoParam:[4,8].filter(d=>s&d).map(d=>({mediaType:d,payloadFmtps:[{payloadType:100,fmtp:"packetization-mode=1;profile-level-id=42e01f"}]}))}};o.remoteVideoTrack.mediaType=n.mediaType,this.postMessage("changetype",n)}destroy(){this.isDestroyed||(super.destroy(),this.isDestroyed=!0,this.joinAbortController.abort("destroy"))}};J([Qi(mo.prototype.afterJoin),Je(["left",oe.INIT],"joined"),gg()],mo.prototype,"join",1),J([Je("joined","left",{ignoreError:!0}),Eg()],mo.prototype,"leave",1),J([pd((...e)=>0),_g()],mo.prototype,"publish",1),J([pd((...e)=>0),Tg()],mo.prototype,"unpublish",1),J([pd((...e)=>e[0].userId),Ig()],mo.prototype,"subscribe",1);var Iu=mo;rn.frameWorkType=37;rn.create=function(i){let t=rn._create.call(this,Iu,i);return t._use(qm,i==null?void 0:i.assetsPath),i!=null&&i.assetsPath&&(Nt.assetsPath=i==null?void 0:i.assetsPath),console.log("trtc wasm sdk:",st,"created",Nt),t};Object.assign(rn.prototype,{_setCurrentSpeaker(i){let t=Ke("player");return t!=null&&t.setSinkId?t.setSinkId(i):Promise.reject("not support")},_enableVideoDecodeFallback(i,t){return A(this,null,function*(){return this.startPlugin(qm.Name,{type:"webCodecs",renderer:"videoFrame",track:i,config:{codec:"avc1.420028"},fallback:"wasm"}),new Promise((e,r)=>{ye(Ce(i,"decode-downgrade-state-changed"),or(o=>o.state==="STARTED"),Rr(1),Bm(1e4),Xe(Ce(i,oe.INIT)),ke(e,r))})})}});var P$=rn;export{P$ as default};
|